Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Brad Zacher
2016-05-04 09:13:45 +09:30
102 changed files with 6394 additions and 813 deletions
+2 -2
View File
@@ -3,14 +3,14 @@
var app = angular.module("angular-jwt-tests", ["angular-jwt"]);
var $jwtHelper: angular.jwt.IJwtHelper;
var $jwtHelper: ng.jwt.IJwtHelper;
var expToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tLyIsInN1YiI6ImZhY2Vib29rfDEwMTU0Mjg3MDI3NTEwMzAyIiwiYXVkIjoiQlVJSlNXOXg2MHNJSEJ3OEtkOUVtQ2JqOGVESUZ4REMiLCJleHAiOjE0MTIyMzQ3MzAsImlhdCI6MTQxMjE5ODczMH0.7M5sAV50fF1-_h9qVbdSgqAnXVF7mz3I6RjS6JiH0H8';
var tokenPayload = $jwtHelper.decodeToken(expToken);
var date = $jwtHelper.getTokenExpirationDate(expToken);
var bool = $jwtHelper.isTokenExpired(expToken);
var $jwtInterceptor: angular.jwt.IJwtInterceptor;
var $jwtInterceptor: ng.jwt.IJwtInterceptor;
$jwtInterceptor.tokenGetter = () => {
return expToken;
+8 -8
View File
@@ -8,14 +8,14 @@
declare namespace angular.jwt {
interface JwtToken {
iss: string;
sub: string;
aud: string;
exp: number;
nbf: number;
iat: number;
jti: string;
unique_name: string;
iss?: string;
sub?: string;
aud?: string;
exp?: number;
nbf?: number;
iat?: number;
jti?: string;
unique_name?: string;
}
interface IJwtHelper {
@@ -0,0 +1,92 @@
/// <reference path="./angular-permission-2.3.1.d.ts" />
import permission = angular.permission;
angular
.module('fooModule', ['permission', 'user'])
.run(function (PermissionStore: permission.PermissionStore, User: any) {
// Define anonymous permission
PermissionStore
.definePermission('anonymous', function (stateParams) {
// If the returned value is *truthy* then the user has the permission, otherwise they don't
if (!User) {
return true; // Is anonymous
}
return false;
});
});
interface BackendUserService {
checkSession(): angular.IPromise<any>;
getAccessLevel(): angular.IPromise<{accessLevel: string}>;
hasPermissionDefinition(permission: string) : angular.IPromise<any>;
}
angular.module('barModule', ['permission', 'user'])
.run(function (PermissionStore: permission.PermissionStore, User: BackendUserService, $q: angular.IQService) {
PermissionStore
// Define user permission calling back-end
.definePermission('user', function (stateParams) {
// This time we will return a promise
// If the promise *resolves* then the user has the permission, if it *rejects* (you guessed it)
// Let's assume this returns a promise that resolves or rejects if session is active
return User.checkSession();
});
PermissionStore
// A different example for admin
.definePermission('admin', function (stateParams) {
var deferred = $q.defer();
User.getAccessLevel()
.then(function (data) {
if (data.accessLevel === 'admin') {
deferred.resolve();
} else {
deferred.reject();
}
})
.catch(function () {
// Error with request
deferred.reject();
});
return deferred.promise;
});
let arrayOfPermissionNames = ['p1', 'p2'];
PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (stateParams: angular.ui.IStateParamsService, permissionName: string) {
return User.hasPermissionDefinition(permissionName);
});
PermissionStore.clearStore();
PermissionStore.removePermissionDefinition('user');
let permissions: Array<permission.Permission> = PermissionStore.getStore();
});
angular
.module('fooModule', ['permission', 'user'])
.run(function (RoleStore: permission.RoleStore, User: any) {
RoleStore
// Permission array validated role
// Library will internally validate if 'user' and 'editor' permissions are valid when checking if role is valid
.defineRole('admin', ['user', 'editor']);
RoleStore
// Server side validated role
.defineRole('accountant', [], function (stateParams) {
// Let's assume that we are making a request to server here and return response as promise
return User.hasRole('accountant');
});
RoleStore.clearStore();
RoleStore.removeRoleDefinition('user');
let roles: Array<permission.Role> = RoleStore.getStore();
});
+165
View File
@@ -0,0 +1,165 @@
// Type definitions for angular-permission 2.3.1
// Project: https://github.com/Narzerus/angular-permission
// Definitions by: Voislav Mishevski <https://github.com/vmishevski>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="../angular-ui-router/angular-ui-router.d.ts" />
declare namespace angular.permission {
export interface PermissionStore {
/**
* Allows to define permission on application configuration
* @method
*
* @param permissionName {String} Name of defined permission
* @param validationFunction {Function} Function used to validate if permission is valid
*/
definePermission(
name: string,
validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise<any>
): void;
/**
* Allows to define set of permissionNames with shared validation function on application configuration
* @method
* @throws {TypeError}
*
* @param permissionNames {Array} Set of permission names
* @param validationFunction {Function} Function used to validate if permission is valid
*/
defineManyPermissions(
permissions: string[],
validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise<any>
): void;
clearStore(): void;
/**
* Deletes permission
* @method
*
* @param permissionName {String} Name of defined permission
*/
removePermissionDefinition(permission: string): void;
/**
* Checks if permission exists
* @method
*
* @param permissionName {String} Name of defined permission
* @returns {Boolean}
*/
hasPermissionDefinition(permissionName: string): boolean;
/**
* Returns all permissions
* @method
*
* @returns {Object} Permissions collection
*/
getStore(): Permission[];
}
export interface RoleStore {
/**
* Allows to define role
* @method
*
* @param roleName {String} Name of defined role
* @param permissions {Array} Set of permission names
* @param [validationFunction] {Function} Function used to validate if permissions in role are valid
*/
defineRole(
role: string,
permissions: Array<string>,
validationFunction: RoleValidationFunction
): void;
/**
* Allows to define role
* @method
*
* @param roleName {String} Name of defined role
* @param permissions {Array} Set of permission names
*/
defineRole(role: string, permissions: Array<string>): void;
/**
* Checks if role is defined in store
* @method
*
* @param roleName {String} Name of role
* @returns {Boolean}
*/
hasRoleDefinition(role: string): boolean;
/**
* Returns role definition object by it's name
* @method
*
* @returns {permission.Role} Role definition object
*/
getRoleDefinition(roleName: string): Role;
/**
* Removes all role definitions
* @method
*/
clearStore(): void;
/**
* Deletes role from store
* @method
*
* @param roleName {String} Name of defined permission
*/
removeRoleDefinition(roleName: string): void;
/**
* Returns all role definitions
* @method
*
* @returns {Object} Defined roles collection
*/
getStore(): Role[];
}
export interface Role {
roleName: string;
permissionNames: string[];
validationFunction?: RoleValidationFunction;
}
export interface Permission {
permissionName: string;
validationFunction?: PermissionValidationFunction;
}
interface RoleValidationFunction {
(stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise<any>;
}
interface PermissionValidationFunction {
(stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise<any>;
}
export interface IPermissionState extends angular.ui.IState {
data?: any | DataWithPermissions;
}
export interface DataWithPermissions {
permissions?: {
only?: (() => void) | Array<string> | angular.IPromise<any>;
except?: (() => void) | Array<string> | angular.IPromise<any>;
redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | {[index: string]: PermissionRedirectConfigation}
};
}
export interface PermissionRedirectConfigation {
state: string;
params?: {};
options?: angular.ui.IStateOptions;
}
}
@@ -36,7 +36,7 @@ angular
PermissionStore
// A different example for admin
.definePermission('admin', function (stateParams) {
.definePermission('admin', function (permission: string, stateParams: angular.permission.TransitionProperties) {
var deferred = $q.defer();
User.getAccessLevel()
@@ -56,7 +56,7 @@ angular
});
let arrayOfPermissionNames = ['p1', 'p2'];
PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (stateParams: angular.ui.IStateParamsService, permissionName: string) {
PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (permissionName: string, stateParams: angular.permission.TransitionProperties) {
return User.hasPermissionDefinition(permissionName);
});
@@ -79,7 +79,7 @@ angular
RoleStore
// Server side validated role
.defineRole('accountant', [], function (stateParams) {
.defineRole('accountant', [], function (permission, stateParams) {
// Let's assume that we are making a request to server here and return response as promise
return User.hasRole('accountant');
});
+15 -5
View File
@@ -1,4 +1,4 @@
// Type definitions for angular-permission 2.3.1
// Type definitions for angular-permission 2.3.6
// Project: https://github.com/Narzerus/angular-permission
// Definitions by: Voislav Mishevski <https://github.com/vmishevski>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -7,6 +7,16 @@
/// <reference path="../angular-ui-router/angular-ui-router.d.ts" />
declare namespace angular.permission {
/**
* Used as optional parameter provided on definitions of permissions and roles
*/
export interface TransitionProperties {
fromState?: angular.ui.IState;
fromParams?: angular.ui.IStateParamsService;
toState?: angular.ui.IState;
toParams?: angular.ui.IStateParamsService;
options?: angular.ui.IStateOptions;
}
export interface PermissionStore {
/**
@@ -18,7 +28,7 @@ declare namespace angular.permission {
*/
definePermission(
name: string,
validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise<any>
validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise<any>
): void;
/**
@@ -31,7 +41,7 @@ declare namespace angular.permission {
*/
defineManyPermissions(
permissions: string[],
validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise<any>
validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise<any>
): void;
clearStore(): void;
@@ -138,11 +148,11 @@ declare namespace angular.permission {
}
interface RoleValidationFunction {
(stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise<any>;
(permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise<any>;
}
interface PermissionValidationFunction {
(stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise<any>;
(permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise<any>;
}
export interface IPermissionState extends angular.ui.IState {
+1 -1
View File
@@ -1683,7 +1683,7 @@ declare namespace protractor {
* @return {!webdriver.promise.Promise} A promise that will resolve to the
* scripts return value.
*/
waitForAngular(): webdriver.promise.Promise<void>;
waitForAngular(): webdriver.promise.Promise<any>;
/**
* Add a module to load before Angular whenever Protractor.get is called.
+5 -1
View File
@@ -35,7 +35,11 @@ interface Scope extends ng.IScope {
app.controller('Ctrl', ($scope: Scope, $translate: angular.translate.ITranslateService) => {
$scope['changeLanguage'] = function (key: any) {
$translate.use(key);
$translate.onReady().then(() => {
if($translate.isReady()) {
$translate.use(key);
}
});
};
}).run(($filter: ng.IFilterService) => {
var x: string;
+2
View File
@@ -66,6 +66,8 @@ declare namespace angular.translate {
useFallbackLanguage(langKey?: string): void;
versionInfo(): string;
loaderCache(): any;
isReady(): boolean;
onReady(): angular.IPromise<void>;
}
interface ITranslateProvider extends angular.IServiceProvider {
@@ -181,6 +181,10 @@ testApp.controller('TestCtrl', (
$log.log('modal rendered');
});
modalInstance.closed.then(()=> {
$log.log('modal closed');
});
modalInstance.result.then((closeResult:any)=> {
$log.log('modal closed', closeResult);
}, (dismissResult:any)=> {
+5
View File
@@ -270,6 +270,11 @@ declare namespace angular.ui.bootstrap {
* A promise that is resolved when a modal is rendered.
*/
rendered: angular.IPromise<any>;
/**
* A promise that is resolved when a modal is closed and the animation completes.
*/
closed: angular.IPromise<any>;
}
interface IModalScope extends angular.IScope {
+1
View File
@@ -36,6 +36,7 @@ mock.module(
function () { return 2; }
);
mock.module({ module1: function () { return 1; } });
mock.module.sharedInjector();
date = mock.TzDate(-7, '2013-1-1T15:00:00Z');
date = mock.TzDate(-8, 12345678);
+4 -1
View File
@@ -47,7 +47,10 @@ declare namespace angular {
inject: IInjectStatic
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module(...modules: any[]): any;
module: {
(...modules: any[]): any;
sharedInjector(): void;
}
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
@@ -0,0 +1,10 @@
/// <reference path="./array-find-index.d.ts" />
import * as arrayFindIndex from 'array-find-index';
arrayFindIndex(['rainbow', 'unicorn', 'pony'], x => x === 'unicorn');
const ctx = {foo: 'rainbow'};
arrayFindIndex(['rainbow', 'unicorn', 'pony'], function (x) {
return x === this.foo;
}, ctx);
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for array-find-index
// Project: https://github.com/sindresorhus/array-find-index
// Definitions by: Sam Verschueren <https://github.com/samverschueren>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "array-find-index" {
type Predicate = (element: any, index: number, array: any[]) => boolean;
function arrayFindIndex(arr: any[], predicate: Predicate): number;
function arrayFindIndex(arr: any[], predicate: Predicate, ctx: any): number;
namespace arrayFindIndex {}
export = arrayFindIndex;
}
+13 -13
View File
@@ -15,7 +15,7 @@ interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (truthValue: boolean) => void): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (err: string, truthValue: boolean) => void): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
@@ -85,23 +85,23 @@ interface Async {
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
select<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
filterSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
selectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
reject<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
rejectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
+1 -1
View File
@@ -1072,7 +1072,7 @@ declare module "aws-sdk" {
GrantReadACP?: string;
GrantWriteACP?: string;
Key: string;
Metadata?: string[];
Metadata?: { [key: string]:string; };
ServerSideEncryption?: string;
StorageClass?: string;
WebsiteRedirectLocation?: string;
@@ -100,7 +100,7 @@ declare namespace Microsoft.WindowsAzure {
}
}
declare module "WindowsAzure" {
declare module "azure-mobile-apps-client" {
export = WindowsAzure;
}
+3
View File
@@ -15,6 +15,9 @@ var knex = Knex({
var bookshelf = Bookshelf(knex);
bookshelf.plugin('registry');
bookshelf.plugin(['virtuals']);
class User extends bookshelf.Model<User> {
get tableName() { return 'users'; }
messages() : Bookshelf.Collection<Posts> {
+1 -1
View File
@@ -18,7 +18,7 @@ declare module 'bookshelf' {
Model : typeof Bookshelf.Model;
Collection : typeof Bookshelf.Collection;
plugin(name: string) : Bookshelf;
plugin(name: string | string[] | Function, options?: any) : Bookshelf;
transaction<T>(callback : (transaction : knex.Transaction) => T) : Promise<T>;
}
+5
View File
@@ -6211,6 +6211,11 @@ declare namespace chrome.tabs {
* @since Chrome 27.
*/
faviconUrl?: string;
/**
* The tab's new title.
* @since Chrome 48.
*/
title?: string;
}
interface TabMoveInfo {
+3
View File
@@ -41,6 +41,7 @@ declare module "colors" {
america: Color;
trap: Color;
random: Color;
zalgo: Color;
}
namespace e {
@@ -80,6 +81,7 @@ declare module "colors" {
export var america: Color;
export var trap: Color;
export var random: Color;
export var zalgo: Color;
}
export = e;
@@ -120,4 +122,5 @@ interface String {
america: string;
trap: string;
random: string;
zalgo: string;
}
+43 -1
View File
@@ -10,8 +10,50 @@ declare module "compression" {
namespace e {
interface CompressionOptions {
threshold?: number;
/**
* See https://github.com/expressjs/compression#chunksize regarding the usage.
*/
chunkSize?: number;
/**
* See https://github.com/expressjs/compression#level regarding the usage.
*/
level?: number;
/**
* See https://github.com/expressjs/compression#memlevel regarding the usage.
*/
memLevel?: number;
/**
* See https://github.com/expressjs/compression#strategy regarding the usage.
*/
strategy?: number;
/**
* See https://github.com/expressjs/compression#threshold regarding the usage.
*/
threshold?: number|string;
/**
* See https://github.com/expressjs/compression#windowbits regarding the usage.
*/
windowBits?: number;
/**
* See https://github.com/expressjs/compression#filter regarding the usage.
*/
filter?: Function;
/**
* See https://nodejs.org/api/zlib.html#zlib_class_options regarding the usage.
*/
flush?: number;
/**
* See https://nodejs.org/api/zlib.html#zlib_class_options regarding the usage.
*/
finishFlush?: number;
}
}
+1 -1
View File
@@ -398,7 +398,7 @@ declare namespace FixedDataTable {
/**
* Component that defines the attributes of a table column group.
*/
export interface ColumnGroupProps {
export interface ColumnGroupProps extends __React.Props<ColumnGroup> {
/**
* The horizontal alignment of the table cell content.
* 'left', 'center', 'right'
+34 -7
View File
@@ -19,6 +19,7 @@ import {
screen,
shell,
session,
systemPreferences,
hideInternalModules
} from 'electron';
@@ -65,7 +66,7 @@ app.on('ready', () => {
mainWindow.webContents.openDevTools();
mainWindow.webContents.toggleDevTools();
mainWindow.webContents.openDevTools({detach: true});
mainWindow.webContents.openDevTools({mode: 'detach'});
mainWindow.webContents.closeDevTools();
mainWindow.webContents.addWorkSpace('/path/to/workspace');
mainWindow.webContents.removeWorkSpace('/path/to/workspace');
@@ -260,8 +261,8 @@ app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1');
app.commandLine.appendSwitch('v', -1);
app.commandLine.appendSwitch('vmodule', 'console=0');
// app
// https://github.com/atom/electron/blob/master/docs/api/app.md
// systemPreferences
// https://github.com/electron/electron/blob/master/docs/api/system-preferences.md
var browserOptions = {
width: 1000,
@@ -271,7 +272,7 @@ var browserOptions = {
};
// Make the window transparent only if the platform supports it.
if (process.platform !== 'win32' || app.isAeroGlassEnabled()) {
if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) {
browserOptions.transparent = true;
browserOptions.frame = false;
}
@@ -288,9 +289,12 @@ if (browserOptions.transparent) {
}
app.on('platform-theme-changed', () => {
console.log(app.isDarkMode());
console.log(systemPreferences.isDarkMode());
});
// app
// https://github.com/atom/electron/blob/master/docs/api/app.md
app.on('certificate-error', function(event, webContents, url, error, certificate, callback) {
if (url == "https://github.com") {
// Verification logic.
@@ -337,6 +341,9 @@ win.on('closed', () => {
win.loadURL('https://github.com');
win.show();
var toolbarRect = document.getElementById('toolbar').getBoundingClientRect();
win.setSheetOffset(toolbarRect.height);
// content-tracing
// https://github.com/atom/electron/blob/master/docs/api/content-tracing.md
@@ -517,12 +524,20 @@ var template = <Electron.MenuItemOptions[]>[
{
label: 'Reload',
accelerator: 'Command+R',
click: () => { BrowserWindow.getFocusedWindow().webContents.reloadIgnoringCache(); }
click: (item, focusedWindow) => {
if (focusedWindow) {
focusedWindow.webContents.reloadIgnoringCache();
}
}
},
{
label: 'Toggle DevTools',
accelerator: 'Alt+Command+I',
click: () => { BrowserWindow.getFocusedWindow().webContents.toggleDevTools(); }
click: (item, focusedWindow) => {
if (focusedWindow) {
focusedWindow.webContents.toggleDevTools();
}
}
}
]
},
@@ -703,6 +718,18 @@ var image = clipboard.readImage();
var appIcon3 = new Tray(image);
var appIcon4 = new Tray('/Users/somebody/images/icon.png');
// process
// https://github.com/electron/electron/blob/master/docs/api/process.md
console.log(process.type);
console.log(process.resourcesPath);
console.log(process.mas);
console.log(process.windowsStore);
process.noAsar = true;
process.crash();
process.hang();
process.setFdLimit(8192);
// screen
// https://github.com/atom/electron/blob/master/docs/api/screen.md
@@ -171,6 +171,16 @@ var image = clipboard.readImage();
var appIcon3 = new Tray(image);
var appIcon4 = new Tray('/Users/somebody/images/icon.png');
// https://github.com/electron/electron/blob/master/docs/api/process.md
// preload.js
var _setImmediate = setImmediate;
var _clearImmediate = clearImmediate;
process.once('loaded', function() {
global.setImmediate = _setImmediate;
global.clearImmediate = _clearImmediate;
});
// screen
// https://github.com/atom/electron/blob/master/docs/api/screen.md
+149 -34
View File
@@ -1,4 +1,4 @@
// Type definitions for Electron v0.37.6
// Type definitions for Electron v0.37.7
// 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
@@ -149,11 +149,6 @@ declare namespace Electron {
* Emitted when the gpu process crashes.
*/
on(event: 'gpu-process-crashed', listener: Function): this;
/**
* Emitted when the system’s Dark Mode theme is toggled.
* Note: This is only implemented on OS X.
*/
on(event: 'platform-theme-changed', listener: Function): this;
on(event: string, listener: Function): this;
/**
* Try to close all windows. The before-quit event will first be emitted.
@@ -256,10 +251,16 @@ declare namespace Electron {
/**
* Removes the current executable as the default handler for a protocol (aka URI scheme).
*
* Note: This API is only available on Windows.
* Note: This is only implemented on Windows.
* On OS X, removing the app will automatically remove the app as the default protocol handler.
*/
removeAsDefaultProtocolClient(protocol: string): void;
/**
* @returns Whether the current executable is the default handler for a protocol (aka URI scheme).
*
* Note: This is only implemented on OS X and Windows.
*/
isDefaultProtocolClient(protocol: string): boolean;
/**
* Adds tasks to the Tasks category of JumpList on Windows.
*
@@ -285,18 +286,13 @@ declare namespace Electron {
*/
setAppUserModelId(id: string): void;
/**
* This method returns true if DWM composition (Aero Glass) is enabled,
* and false otherwise. You can use it to determine if you should create
* a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled).
* Imports the certificate in pkcs12 format into the platform certificate store.
* @param callback Called with the result of import operation, a value of 0 indicates success
* while any other value indicates failure according to chromium net_error_list.
*
* Note: This is only implemented on Windows.
* Note: This API is only available on Linux.
*/
isAeroGlassEnabled(): boolean;
/**
* @returns If the system is in Dark Mode.
* Note: This is only implemented on OS X.
*/
isDarkMode(): boolean;
importCertificate(options: ImportCertificateOptions, callback: (result: number) => void): void;
commandLine: CommandLine;
/**
* Note: This API is only available on Mac.
@@ -306,6 +302,17 @@ declare namespace Electron {
type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos';
interface ImportCertificateOptions {
/**
* Path for the pkcs12 file.
*/
certificate: string;
/**
* Passphrase for the certificate.
*/
password: string;
}
interface CommandLine {
/**
* Append a switch [with optional value] to Chromium's command line.
@@ -814,6 +821,11 @@ declare namespace Electron {
* @returns The title of the native window.
*/
getTitle(): string;
/**
* Changes the attachment point for sheets on Mac OS X.
* Note: This API is available only on OS X.
*/
setSheetOffset(offset: number): void;
/**
* Starts or stops flashing the window to attract user's attention.
*/
@@ -2244,19 +2256,19 @@ declare namespace Electron {
/**
* Registers a protocol of scheme that will send the file as a response.
*/
registerFileProtocol(scheme: string, handler: (request: ProtocolRequest, callback: FileProtocolCallback) => void, completion?: (error: Error) => void): void;
registerFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void;
/**
* Registers a protocol of scheme that will send a Buffer as a response.
*/
registerBufferProtocol(scheme: string, handler: (request: ProtocolRequest, callback: BufferProtocolCallback) => void, completion?: (error: Error) => void): void;
registerBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void;
/**
* Registers a protocol of scheme that will send a String as a response.
*/
registerStringProtocol(scheme: string, handler: (request: ProtocolRequest, callback: StringProtocolCallback) => void, completion?: (error: Error) => void): void;
registerStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void;
/**
* Registers a protocol of scheme that will send an HTTP request as a response.
*/
registerHttpProtocol(scheme: string, handler: (request: ProtocolRequest, callback: HttpProtocolCallback) => void, completion?: (error: Error) => void): void;
registerHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void;
/**
* Unregisters the custom protocol of scheme.
*/
@@ -2268,25 +2280,30 @@ declare namespace Electron {
/**
* Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a file as a response.
*/
interceptFileProtocol(scheme: string, handler: (request: ProtocolRequest, callback: FileProtocolCallback) => void, completion?: (error: Error) => void): void;
/**
* Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a String as a response.
*/
interceptStringProtocol(scheme: string, handler: (request: ProtocolRequest, callback: BufferProtocolCallback) => void, completion?: (error: Error) => void): void;
interceptFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void;
/**
* Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a Buffer as a response.
*/
interceptBufferProtocol(scheme: string, handler: (request: ProtocolRequest, callback: StringProtocolCallback) => void, completion?: (error: Error) => void): void;
interceptBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void;
/**
* Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a String as a response.
*/
interceptStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void;
/**
* Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a new HTTP request as a response.
*/
interceptHttpProtocol(scheme: string, handler: (request: ProtocolRequest, callback: HttpProtocolCallback) => void, completion?: (error: Error) => void): void;
interceptHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void;
/**
* Remove the interceptor installed for scheme and restore its original handler.
*/
uninterceptProtocol(scheme: string, completion?: (error: Error) => void): void;
}
type FileProtocolHandler = (request: ProtocolRequest, callback: FileProtocolCallback) => void;
type BufferProtocolHandler = (request: ProtocolRequest, callback: BufferProtocolCallback) => void;
type StringProtocolHandler = (request: ProtocolRequest, callback: StringProtocolCallback) => void;
type HttpProtocolHandler = (request: ProtocolRequest, callback: HttpProtocolCallback) => void;
interface ProtocolRequest {
url: string;
referrer: string;
@@ -2392,7 +2409,7 @@ declare namespace Electron {
*/
scaleFactor: number;
/**
* Can be 0, 1, 2, 3, each represents screen rotation in clock-wise degrees of 0, 90, 180, 270.
* Can be 0, 90, 180, 270, represents screen rotation in clock-wise degrees.
*/
rotation: number;
touchSupport: 'available' | 'unavailable' | 'unknown';
@@ -2419,7 +2436,7 @@ declare namespace Electron {
/**
* The screen module retrieves information about screen size, displays, cursor position, etc.
* You should not use this module until the ready event of the app module is emitted.
* You can not use this module until the ready event of the app module is emitted.
*/
interface Screen extends NodeJS.EventEmitter {
/**
@@ -2547,7 +2564,7 @@ declare namespace Electron {
webRequest: WebRequest;
}
type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen';
type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal';
interface ClearStorageDataOptions {
/**
@@ -2926,6 +2943,47 @@ declare namespace Electron {
beep(): void;
}
// https://github.com/electron/electron/blob/master/docs/api/system-preferences.md
/**
* Get system preferences.
*/
interface SystemPreferences {
/**
* @returns If the system is in Dark Mode.
*
* Note: This is only implemented on OS X.
*/
isDarkMode(): boolean;
/**
* Subscribes to native notifications of OS X, callback will be called when the corresponding event happens.
* The id of the subscriber is returned, which can be used to unsubscribe the event.
*
* Note: This is only implemented on OS X.
*/
subscribeNotification(event: string, callback: Function): number;
/**
* Removes the subscriber with id.
*
* Note: This is only implemented on OS X.
*/
unsubscribeNotification(id: number): void;
/**
* Get the value of key in system preferences.
*
* Note: This is only implemented on OS X.
*/
getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url'): any;
/**
* This method returns true if DWM composition (Aero Glass) is enabled,
* and false otherwise. You can use it to determine if you should create
* a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled).
*
* Note: This is only implemented on Windows.
*/
isAeroGlassEnabled(): boolean;
}
// https://github.com/electron/electron/blob/master/docs/api/tray.md
/**
@@ -3253,6 +3311,10 @@ declare namespace Electron {
* @returns Whether web page is still loading resources.
*/
isLoading(): boolean;
/**
* @returns Whether the main frame (and not just iframes or frames within it) is still loading.
*/
isLoadingMainFrame(): boolean;
/**
* @returns Whether web page is waiting for a first-response for the main
* resource of the page.
@@ -3420,9 +3482,9 @@ declare namespace Electron {
*/
openDevTools(options?: {
/**
* Opens devtools in a new window.
* Opens the devtools with specified dock state. Defaults to last used dock state.
*/
detach?: boolean;
mode?: 'right' | 'bottom' | 'undocked' | 'detach'
}): void;
/**
* Closes the developer tools.
@@ -4234,7 +4296,7 @@ declare namespace Electron {
* Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
* <meta name='theme-color' content='#ff0000'>
*/
addEventListener(type: 'did-change-theme-color', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void;
addEventListener(type: 'did-change-theme-color', listener: (event: WebViewElement.DidChangeThemeColorEvent) => void, useCapture?: boolean): void;
/**
* Emitted when DevTools is opened.
*/
@@ -4330,6 +4392,10 @@ declare namespace Electron {
name: string;
version: string;
}
interface DidChangeThemeColorEvent extends Event {
themeColor: string;
}
}
/**
@@ -4386,6 +4452,7 @@ declare namespace Electron {
protocol: Electron.Protocol;
screen: Electron.Screen;
session: typeof Electron.Session;
systemPreferences: Electron.SystemPreferences;
Tray: Electron.Tray;
hideInternalModules(): void;
}
@@ -4424,6 +4491,54 @@ interface File {
path: string;
}
// https://github.com/electron/electron/blob/master/docs/api/process.md
declare namespace NodeJS {
interface Process {
/**
* Process's type
*/
type: 'browser' | 'renderer';
/**
* Path to JavaScript source code.
*/
resourcesPath: string;
/**
* For Mac App Store build, this value is true, for other builds it is undefined.
*/
mas?: boolean;
/**
* If the app is running as a Windows Store app (appx), this value is true, for other builds it is undefined.
*/
windowsStore?: boolean;
/**
* Emitted when Electron has loaded its internal initialization script
* and is beginning to load the web page or the main script.
*/
on(event: 'loaded', listener: Function): this;
on(event: string, listener: Function): this;
/**
* Setting this to true can disable the support for asar archives in Node's built-in modules.
*/
noAsar?: boolean;
/**
* Causes the main thread of the current process crash;
*/
crash(): void;
/**
* Causes the main thread of the current process hang.
*/
hang(): void;
/**
* Sets the file descriptor soft limit to maxDescriptors or the OS hard limit,
* whichever is lower for the current process.
*
* Note: This API is only available on Mac and Linux.
*/
setFdLimit(maxDescriptors: number): void;
}
}
declare module 'electron' {
var electron: Electron.ElectronMainAndRenderer;
export = electron;
+14
View File
@@ -14,14 +14,17 @@ function test_HandsontableInit() {
autoRowSize: true,
autoWrapCol: true,
autoWrapRow: true,
bindRowsWithHeaders: 'foo',
cell: [],
cells: function() {},
checkedTemplate: true,
className: [],
colHeaders: true,
collapsibleColumns: true,
columnHeaderHeight: 123,
columns: [],
columnSorting: {},
columnSummary: {},
colWidths: 123,
commentedCellClassName: 'foo',
comments: [],
@@ -41,15 +44,24 @@ function test_HandsontableInit() {
debug: true,
defaultDate: 'foo',
disableVisualSelection: true,
dropdownMenu: [],
editor: true,
enterBeginsEditing: true,
enterMoves: {},
fillHandle: true,
filter: true,
filteringCaseSensitive: true,
filters: false,
fixedColumnsLeft: 123,
fixedRowsBottom: 123,
fixedRowsTop: 123,
format: 'foo',
fragmentSelection: true,
ganttChart: {},
headerTooltips: true,
height: 123,
hiddenColumns: true,
hiddenRows: {},
invalidCellClassName: 'foo',
label: {},
language: 'foo',
@@ -66,6 +78,7 @@ function test_HandsontableInit() {
minSpareCols: 123,
minSpareRows: 123,
multiSelect: true,
nestedHeaders: [],
noWordWrapClassName: 'foo',
observeChanges: true,
observeDOMVisibility: true,
@@ -85,6 +98,7 @@ function test_HandsontableInit() {
search: true,
selectOptions: [],
skipColumnOnPaste: true,
sortByRelevance: true,
sortFunction: function() {},
sortIndicator: true,
source: [],
+14
View File
@@ -16,14 +16,17 @@ declare namespace ht {
autoRowSize?: Object|boolean;
autoWrapCol?: boolean;
autoWrapRow?: boolean;
bindRowsWithHeaders?: boolean|string;
cell?: any[];
cells?: Function;
checkedTemplate?: boolean|string;
className?: string|any[];
colHeaders?: boolean|any[]|Function;
collapsibleColumns?: boolean|any[];
columnHeaderHeight?: number|any[];
columns?: any[];
columnSorting?: boolean|Object;
columnSummary?: Object;
colWidths?: any[]|Function|number|string;
commentedCellClassName?: string;
comments?: boolean|any[];
@@ -43,15 +46,24 @@ declare namespace ht {
debug?: boolean;
defaultDate?: string;
disableVisualSelection?: boolean|string|any[];
dropdownMenu?: boolean|Object|any[];
editor?: string|Function|boolean;
enterBeginsEditing?: boolean;
enterMoves?: Object|Function;
fillHandle?: boolean|string|Object;
filter?: boolean;
filteringCaseSensitive?: boolean;
filters?: boolean;
fixedColumnsLeft?: number;
fixedRowsBottom?: number;
fixedRowsTop?: number;
format?: string;
fragmentSelection?: boolean|string;
ganttChart?: Object;
headerTooltips?: boolean|Object;
height?: number|Function;
hiddenColumns?: boolean|Object;
hiddenRows?: boolean|Object;
invalidCellClassName?: string;
label?: Object;
language?: string;
@@ -68,6 +80,7 @@ declare namespace ht {
minSpareCols?: number;
minSpareRows?: number;
multiSelect?: boolean;
nestedHeaders?: any[];
noWordWrapClassName?: string;
observeChanges?: boolean;
observeDOMVisibility?: boolean;
@@ -87,6 +100,7 @@ declare namespace ht {
search?: boolean;
selectOptions?: any[];
skipColumnOnPaste?: boolean;
sortByRelevance?: boolean;
sortFunction?: Function;
sortIndicator?: boolean;
source?: any[]|Function;
+138 -92
View File
@@ -10,22 +10,19 @@ var app = express();
*/
function helmetTest() {
app.use(helmet());
app.use(helmet({}));
app.use(helmet({ frameguard: false }));
app.use(helmet({ frameguard: true }));
app.use(helmet({
frameguard: {
action: 'deny'
}
}));
}
/**
* @summary Test for {@see helmet#xssFilter} function.
* @summary Test for {@see helmet#contentSecurityPolicy} function.
*/
function xssFilterTest() {
app.use(helmet.xssFilter());
app.use(helmet.xssFilter({}));
app.use(helmet.xssFilter({ setOnOldIE: false }));
app.use(helmet.xssFilter({ setOnOldIE: true }));
}
/**
* @summary Test for {@see helmet#csp} function.
*/
function contentSecurityPolicyTest() {
const emptyArray: string[] = [];
const config = {
@@ -63,86 +60,6 @@ function contentSecurityPolicyTest() {
},
setAllHeaders: true
}));
app.use(helmet.csp());
app.use(helmet.csp({}));
app.use(helmet.csp(config));
app.use(helmet.csp({
directives: {
defaultSrc: ["'self'"]
},
setAllHeaders: true
}));
}
/**
* @summary Test for {@see helmet#frameguard} function.
*/
function frameguardTest() {
app.use(helmet.frameguard());
app.use(helmet.frameguard("sameorigin"));
}
/**
* @summary Test for {@see helmet#hsts} function.
*/
function hstsTest() {
app.use(helmet.hsts());
app.use(helmet.hsts({ maxAge: 7776000000 }));
}
/**
* @summary Test for {@see helmet#ieNoOpen} function.
*/
function ieNoOpenTest() {
app.use(helmet.ieNoOpen());
}
/**
* @summary Test for {@see helmet#noSniff} function.
*/
function noSniffTest() {
app.use(helmet.noSniff());
}
/**
* @summary Test for {@see helmet#publicKeyPins} function.
*/
function publicKeyPinsTest() {
app.use(helmet.publicKeyPins({
maxAge: 7776000000,
sha256s: ["AbCdEf123=", "ZyXwVu456="],
}));
app.use(helmet.publicKeyPins({
maxAge: 7776000000,
sha256s: ["AbCdEf123=", "ZyXwVu456="],
includeSubdomains: false
}));
app.use(helmet.publicKeyPins({
maxAge: 7776000000,
sha256s: ["AbCdEf123=", "ZyXwVu456="],
includeSubdomains: true
}));
app.use(helmet.publicKeyPins({
maxAge: 7776000000,
sha256s: ["AbCdEf123=", "ZyXwVu456="],
reportUri: "http://example.com"
}));
app.use(helmet.publicKeyPins({
maxAge: 7776000000,
sha256s: ["AbCdEf123=", "ZyXwVu456="],
reportOnly: true
}));
app.use(helmet.publicKeyPins({
maxAge: 7776000000,
sha256s: ["AbCdEf123=", "ZyXwVu456="],
setIf: function (req, res) { return true; }
}));
}
/**
@@ -153,3 +70,132 @@ function dnsPrefetchControlTest() {
app.use(helmet.dnsPrefetchControl({ allow: false }));
app.use(helmet.dnsPrefetchControl({ allow: true }));
}
/**
* @summary Test for {@see helmet#frameguard} function.
*/
function frameguardTest() {
app.use(helmet.frameguard());
app.use(helmet.frameguard({}));
app.use(helmet.frameguard({ action: 'deny' }));
app.use(helmet.frameguard({ action: 'sameorigin' }));
app.use(helmet.frameguard({
action: 'allow-from',
domain: 'http://example.com'
}));
}
/**
* @summary Test for {@see helmet#hidePoweredBy} function.
*/
function hidePoweredBy() {
app.use(helmet.hidePoweredBy());
app.use(helmet.hidePoweredBy({}));
app.use(helmet.hidePoweredBy({ setTo: 'PHP 4.2.0' }));
}
/**
* @summary Test for {@see helmet#hpkp} function.
*/
function hpkpTest() {
app.use(helmet.hpkp({
maxAge: 7776000000,
sha256s: ['AbCdEf123=', 'ZyXwVu456='],
}));
app.use(helmet.hpkp({
maxAge: 7776000000,
sha256s: ['AbCdEf123=', 'ZyXwVu456='],
includeSubdomains: false
}));
app.use(helmet.hpkp({
maxAge: 7776000000,
sha256s: ['AbCdEf123=', 'ZyXwVu456='],
includeSubdomains: true
}));
app.use(helmet.hpkp({
maxAge: 7776000000,
sha256s: ['AbCdEf123=', 'ZyXwVu456='],
reportUri: 'http://example.com'
}));
app.use(helmet.hpkp({
maxAge: 7776000000,
sha256s: ['AbCdEf123=', 'ZyXwVu456='],
reportOnly: true
}));
app.use(helmet.hpkp({
maxAge: 7776000000,
sha256s: ['AbCdEf123=', 'ZyXwVu456='],
setIf: function (req, res) { return true; }
}));
}
/**
* @summary Test for {@see helmet#hsts} function.
*/
function hstsTest() {
app.use(helmet.hsts());
app.use(helmet.hsts({ maxAge: 7776000000 }));
app.use(helmet.hsts({
maxAge: 7776000000,
}));
app.use(helmet.hsts({
maxAge: 7776000000,
includeSubdomains: true
}));
app.use(helmet.hsts({
maxAge: 7776000000,
preload: true
}));
app.use(helmet.hsts({
maxAge: 7776000000,
force: true
}));
app.use(helmet.hsts({
maxAge: 7776000000,
setIf: function (req, res) { return true; }
}));
}
/**
* @summary Test for {@see helmet#ieNoOpen} function.
*/
function ieNoOpenTest() {
app.use(helmet.ieNoOpen());
}
/**
* @summary Test for {@see helmet#noCache} function.
*/
function noCacheTest() {
app.use(helmet.noCache());
app.use(helmet.noCache({}));
app.use(helmet.noCache({ noEtag: true }));
}
/**
* @summary Test for {@see helmet#noSniff} function.
*/
function noSniffTest() {
app.use(helmet.noSniff());
}
/**
* @summary Test for {@see helmet#xssFilter} function.
*/
function xssFilterTest() {
app.use(helmet.xssFilter());
app.use(helmet.xssFilter({}));
app.use(helmet.xssFilter({ setOnOldIE: false }));
app.use(helmet.xssFilter({ setOnOldIE: true }));
}
+76 -49
View File
@@ -5,15 +5,28 @@
/// <reference path="../express/express.d.ts" />
declare module "helmet" {
import express = require("express");
interface IHelmetCspDirectiveFunction {
declare module 'helmet' {
import express = require('express');
interface IHelmetConfiguration {
contentSecurityPolicy? : boolean | IHelmetContentSecurityPolicyConfiguration,
dnsPrefetchControl?: boolean | IHelmetDnsPrefetchControlConfiguration,
frameguard?: boolean | IHelmetFrameguardConfiguration,
hidePoweredBy?: boolean | IHelmetHidePoweredByConfiguration,
hpkp?: boolean | IHelmetHpkpConfiguration,
hsts?: boolean | IHelmetHstsConfiguration,
ieNoOpen?: boolean,
noCache?: boolean,
noSniff?: boolean,
xssFilter?: boolean | IHelmetXssFilterConfiguration
}
interface IHelmetContentSecurityPolicyDirectiveFunction {
(req: express.Request, res: express.Response): string;
}
type HelmetCspDirectiveValue = string | IHelmetCspDirectiveFunction;
type HelmetCspDirectiveValue = string | IHelmetContentSecurityPolicyDirectiveFunction;
interface IHelmetCspDirectives {
interface IHelmetContentSecurityPolicyDirectives {
baseUri? : HelmetCspDirectiveValue[],
childSrc? : HelmetCspDirectiveValue[],
connectSrc? : HelmetCspDirectiveValue[],
@@ -31,36 +44,53 @@ declare module "helmet" {
scriptSrc? : HelmetCspDirectiveValue[],
styleSrc? : HelmetCspDirectiveValue[]
}
interface IHelmetCspConfiguration {
interface IHelmetContentSecurityPolicyConfiguration {
reportOnly? : boolean;
setAllHeaders? : boolean;
disableAndroid? : boolean;
browserSniff?: boolean;
directives? : IHelmetCspDirectives
directives? : IHelmetContentSecurityPolicyDirectives
}
interface IHelmetPublicKeyPinsSetIfFunction {
interface IHelmetDnsPrefetchControlConfiguration {
allow? : boolean;
}
interface IHelmetFrameguardConfiguration {
action? : string,
domain? : string
}
interface IHelmetHidePoweredByConfiguration {
setTo? : string
}
interface IHelmetSetIfFunction {
(req: express.Request, res: express.Response): boolean;
}
interface IHelmetPublicKeyPinsConfiguration {
interface IHelmetHpkpConfiguration {
maxAge : number;
sha256s : string[];
includeSubdomains? : boolean;
reportUri? : string;
reportOnly? : boolean;
setIf?: IHelmetPublicKeyPinsSetIfFunction
setIf?: IHelmetSetIfFunction
}
interface IHelmetHstsConfiguration {
maxAge: number;
includeSubdomains? : boolean;
preload? : boolean;
setIf? : IHelmetSetIfFunction,
force? : boolean;
}
interface IHelmetXssFilterConfiguration {
setOnOldIE? : boolean;
}
interface IHelmetDnsPrefetchControlConfiguration {
allow? : boolean;
}
/**
* @summary Interface for helmet class.
* @interface
@@ -70,77 +100,74 @@ declare module "helmet" {
* @summary Constructor.
* @return {RequestHandler} The Request handler.
*/
():express.RequestHandler;
(options ?: IHelmetConfiguration): express.RequestHandler;
/**
* @summary Set policy around third-party content via headers
* @param {IHelmetContentSecurityPolicyConfiguration} options The options
* @return {RequestHandler} The Request handler
*/
contentSecurityPolicy(options ?: IHelmetContentSecurityPolicyConfiguration): express.RequestHandler;
/**
* @summary Stop browsers from doing DNS prefetching.
* @param {IHelmetDnsPrefetchControlConfiguration} options The options
* @return {RequestHandler} The Request handler
*/
dnsPrefetchControl(options ?: IHelmetDnsPrefetchControlConfiguration):express.RequestHandler;
dnsPrefetchControl(options ?: IHelmetDnsPrefetchControlConfiguration): express.RequestHandler;
/**
* @summary Prevent clickjacking.
* @param {string} header The header.
* @return {RequestHandler} The Request handler.
* @param {IHelmetFrameguardConfiguration} options The options
* @return {RequestHandler} The Request handler
*/
frameguard(header ?: string):express.RequestHandler;
frameguard(options ?: IHelmetFrameguardConfiguration): express.RequestHandler;
/**
* @summary Hide "X-Powered-By" header.
* @param {Object} options The options.
* @param {IHelmetHidePoweredByConfiguration} options The options
* @return {RequestHandler} The Request handler.
*/
hidePoweredBy(options ?: Object):express.RequestHandler;
hidePoweredBy(options ?: IHelmetHidePoweredByConfiguration): express.RequestHandler;
/**
* @summary Adds the "Public-Key-Pins" header.
* @param {IHelmetHpkpConfiguration} options The options
* @return {RequestHandler} The Request handler.
*/
hpkp(options ?: IHelmetHpkpConfiguration): express.RequestHandler;
/**
* @summary Adds the "Strict-Transport-Security" header.
* @param {Object} options The options.
* @param {IHelmetHstsConfiguration} options The options
* @return {RequestHandler} The Request handler.
*/
hsts(options ?: Object):express.RequestHandler;
hsts(options ?: IHelmetHstsConfiguration): express.RequestHandler;
/**
* @summary Add the "X-Download-Options" header.
* @return {RequestHandler} The Request handler.
*/
ieNoOpen():express.RequestHandler;
ieNoOpen(): express.RequestHandler;
/**
* @summary Add the "Cache-Control" and "Pragma" headers to stop caching.
* @return {RequestHandler} The Request handler.
*/
noCache(options ?: Object):express.RequestHandler;
noCache(options ?: Object): express.RequestHandler;
/**
* @summary Adds the "X-Content-Type-Options" header.
* @return {RequestHandler} The Request handler.
*/
noSniff():express.RequestHandler;
/**
* @summary Adds the "Public-Key-Pins" header.
* @return {RequestHandler} The Request handler.
*/
publicKeyPins(options ?: IHelmetPublicKeyPinsConfiguration):express.RequestHandler;
noSniff(): express.RequestHandler;
/**
* @summary Mitigate cross-site scripting attacks with the "X-XSS-Protection" header.
* @param {IHelmetXssFilterConfiguration} options The options
* @return {RequestHandler} The Request handler.
* @param {Object} options The options.
*/
xssFilter(options ?: IHelmetXssFilterConfiguration):express.RequestHandler;
/**
* @summary Set policy around third-party content via headers
* @return {RequestHandler} The Request handler
* @param {Object} options The options
*/
csp(options ?: IHelmetCspConfiguration): express.RequestHandler;
/**
* @see csp
*/
contentSecurityPolicy(options ?: IHelmetCspConfiguration): express.RequestHandler;
xssFilter(options ?: IHelmetXssFilterConfiguration): express.RequestHandler;
}
var helmet: Helmet;
+3 -1
View File
@@ -137,7 +137,9 @@ fooStream = _<Foo>(readable);
fooStream = _<Foo>(emitter);
fooStream = _(fooStreamThen);
fooStream = _(fooArrThen);
fooStream = _(fooThen);
fooArrStream = _(fooArrThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+1 -1
View File
@@ -67,7 +67,7 @@ interface HighlandStatic {
// moar (promise for everything?)
<R>(xs: Highland.Thenable<Highland.Stream<R>>): Highland.Stream<R>;
<R>(xs: Highland.Thenable<R[]>): Highland.Stream<R>;
<R>(xs: Highland.Thenable<R>): Highland.Stream<R>;
/**
* The end of stream marker. This is sent along the data channel of a Stream
+1 -1
View File
@@ -100,7 +100,7 @@ declare namespace I18next {
getFixedT(lng?:string, ns?:string|string[]):TranslationFunction;
t(key:string, options?:TranslationOptions):string;
t(key:string, options?:TranslationOptions):string|any|Array<any>;
exists():boolean;
+2
View File
@@ -9,6 +9,8 @@ testIonic.config(['$ionicConfigProvider', ($ionicConfigProvider: ionic.utility.I
$ionicConfigProvider.views.maxCache(10);
var forwardCache: boolean = $ionicConfigProvider.views.forwardCache();
$ionicConfigProvider.views.forwardCache(true);
var swipeBackEnabled: boolean = $ionicConfigProvider.views.swipeBackEnabled();
$ionicConfigProvider.views.swipeBackEnabled(true);
var jsScrolling: boolean = $ionicConfigProvider.scrolling.jsScrolling();
$ionicConfigProvider.scrolling.jsScrolling(true);
+1
View File
@@ -358,6 +358,7 @@ declare namespace ionic {
transition(transition?: string): string;
maxCache(maxNumber?: number): number;
forwardCache(value?: boolean): boolean;
swipeBackEnabled(value?: boolean): boolean;
};
scrolling: {
jsScrolling(value?: boolean): boolean;
+1 -1
View File
@@ -29,7 +29,7 @@ declare namespace jest {
function fn<T>(implementation?: Function): Mock<T>;
function dontMock(moduleName: string): void;
function genMockFromModule<T>(moduleName: string): Mock<T>;
function mock(moduleName: string): void;
function mock(moduleName: string, factory?: Function): void;
function runAllTicks(): void;
function runAllTimers(): void;
function runOnlyPendingTimers(): void;
@@ -0,0 +1,11 @@
/// <reference path="jquery-mousewheel.d.ts"/>
$('#my_elem').on('mousewheel', (event: JQueryMousewheel.JQueryMousewheelEventObject) => {
console.log(event.deltaX, event.deltaY, event.deltaFactor, event.deltaMode, event.absDelta);
});
$('#my_elem').mousewheel(event => {
console.log(event.deltaX, event.deltaY, event.deltaFactor, event.deltaMode, event.absDelta);
});
$('#my_elem').unmousewheel();
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for jquery-mousewheel v3.1.13
// Project: https://github.com/jquery/jquery-mousewheel
// Definitions by: Brian Surowiec <https://github.com/xt0rted/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
declare namespace JQueryMousewheel {
interface JQueryMousewheelEventObject extends JQueryEventObject {
deltaX: number;
deltaY: number;
deltaFactor: number;
deltaMode: number;
absDelta: number;
}
}
interface JQuery {
mousewheel(handler: (eventObject: JQueryMousewheel.JQueryMousewheelEventObject, ...args: any[]) => any): JQuery
unmousewheel(): JQuery;
}
+8
View File
@@ -43,6 +43,14 @@ server.on('browser_register', function (browser: any) {
console.log('A new browser was registered');
});
server.on('run_complete', (browsers, results) => {
results.disconnected = false;
results.error = false;
results.exitCode = 0;
results.failed = 9;
results.success = 10;
});
//var runner = require('karma').runner; => cannot use this syntax otherwise runner is of type any
karma.runner.run({port: 9876}, function(exitCode: number) {
console.log('Karma has exited with ' + exitCode);
+20 -5
View File
@@ -34,7 +34,7 @@ declare module 'karma' {
interface LauncherStatic {
generateId(): string;
//TODO: injector should be of type `di.Injector`
new(emitter: NodeJS.EventEmitter, injector: any): Launcher;
new (emitter: NodeJS.EventEmitter, injector: any): Launcher;
}
interface Launcher {
@@ -53,11 +53,19 @@ declare module 'karma' {
}
interface Runner {
run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void;
run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;
}
interface TestResults {
disconnected: boolean;
error: boolean;
exitCode: number;
failed: number;
success: number;
}
interface Server extends NodeJS.EventEmitter {
new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server;
new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server;
/**
* Start the server
*/
@@ -72,6 +80,13 @@ declare module 'karma' {
*/
refreshFiles(): Promise<any>;
on(event: string, listener: Function): this;
/**
* Listen to the 'run_complete' event.
*/
on(event: 'run_complete', listener: (browsers: any, results: TestResults ) => void): this;
///**
// * Backward-compatibility with karma-intellij bundled with WebStorm.
// * Deprecated since version 0.13, to be removed in 0.14
@@ -191,7 +206,7 @@ declare module 'karma' {
* @default []
* @description List of files/patterns to load in the browser.
*/
files?: (FilePattern|string)[];
files?: (FilePattern | string)[];
/**
* @default []
* @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...
@@ -257,7 +272,7 @@ declare module 'karma' {
* but your interactive debugging does not.
*
*/
preprocessors?: { [name: string]: string|string[] }
preprocessors?: { [name: string]: string | string[] }
/**
* @default 'http:'
* Possible Values:
+310
View File
@@ -0,0 +1,310 @@
/// <reference path="kik-browser.d.ts" />
if (kik.enabled) {
// running in kik
}
if (kik.send) {
// can send messages
}
kik.getUser(function (user) {
if (!user) {
// user denied access to their information
} else {
typeof user.username; // "string"
typeof user.fullName; // "string"
typeof user.firstName; // "string"
typeof user.lastName; // "string"
typeof user.pic; // "string"
typeof user.thumbnail; // "string"
}
});
if (kik.hasPermission()) {
// your webpage has permission
}
kik.getAnonymousUser(function (token) {
typeof token; // "string"
});
kik.sign("my data", function (signedData, username, host) {
if (!signedData) {
// failed to sign
// perhaps user denied permissions
} else {
// successfully signed
typeof signedData; // "string", signed data
typeof username; // "string", user who signed
typeof host; // "string", host of your webpage
// all of these fields must be passed to the
// verification service to be successful
}
});
kik.anonymousSign("my data", function (signedData, anonToken, host) {
if (!signedData) {
// failed to sign
} else {
// successfully signed
typeof signedData; // "string", signed data
typeof anonToken; // "string", anonymous user who signed
typeof host; // "string", host of your webpage
}
});
kik.send({
title : "Message title" ,
text : "Message body" ,
pic : "http://mysite.com/pic" , // optional
big : true , // optional
noForward : true , // optional
data : { some : "json" } // optional
});
kik.send("myFriend", {
title : "Message title" ,
text : "Message body" ,
});
if (kik.message) {
// your webpage was launched from a message
// kik.message is exactly what was provided in kik.send
// in this case: { some "json" }
}
kik.openConversation("kikteam");
kik.metrics.enableGoogleAnalytics("id", "mydomain.com");
kik.metrics.enableGoogleAnalytics();
kik.showProfile("kikteam");
kik.pickUsers(function (users) {
if (!users) {
// action was cancelled by user
} else {
users.forEach(function (user) {
typeof user.username; // "string"
typeof user.fullName; // "string"
typeof user.firstName; // "string"
typeof user.lastName; // "string"
typeof user.pic; // "string"
typeof user.thumbnail; // "string"
});
}
});
kik.pickUsers({
minResults : 2 , // number >= 0
maxResults : 4 // number > 0
}, function (users) {
// do something with data
});
kik.pickUsers({
preselected : [
{ username : "foo" /*, etc */ },
// any user object obtained from previous call to pickUsers
]
}, function (users) {
// do something with data
});
kik.pickUsers({
filterSelf: false
}, function (users) {
// do something with data
});
kik.photo.get(function (photos) {
if (!photos) {
// action cancelled by user
} else {
// photos is a list of data URLs
}
});
kik.photo.get({
quality : 0.7 , // number between 0-1
minResults : 2 , // number between 1-25
maxResults : 25 , // number between 1-25
maxHeight : 1280 , // number in pixels between 0-1280
maxWidth : 1280 , // number in pixels between 0-1280
}, function (photos) {
// do something with the photos
});
kik.photo.getFromCamera({
onSelect : function (numPhotos) {
// called immediately after the user has selected photos
// "numPhotos" is the number of photos selected by the user
// that many "onPhoto" events will be fired after this
// "onComplete" will fire after all "onPhoto" events are done
},
onPhoto : function (photo, index) {
// "photo" is a data URL representing a single image
// "photo" may be null if there was an error in processing
// this will be called once for each image when it is ready
// "index" is an integer relating to the order of selection
// event may not come in order so use index if you care
},
onComplete : function (photos) {
// "photos" is list of all photos from all photo events
// this event is identical to normal callback
},
onCancel : function () {
// the action was cancelled by the user
// no other events will be called
}
});
kik.photo.get({
quality : 0.7 , // number between 0-1
minResults : 2 , // number between 1-25
maxResults : 25 , // number between 1-25
maxHeight : 1280 , // number in pixels between 0-1280
maxWidth : 1280 , // number in pixels between 0-1280
}, function (photos) {
// do something with the photos
});
kik.photo.getFromCamera({
onSelect : function (numPhotos) {
// called immediately after the user has selected photos
// 'numPhotos' is the number of photos selected by the user
// that many 'onPhoto' events will be fired after this
// 'onComplete' will fire after all 'onPhoto' events are done
},
onPhoto : function (photo, index) {
// 'photo' is a data URL representing a single image
// 'photo' may be null if there was an error in processing
// this will be called once for each image when it is ready
// 'index' is an integer relating to the order of selection
// event may not come in order so use index if you care
},
onComplete : function (photos) {
// 'photos' is list of all photos from all photo events
// this event is identical to normal callback
},
onCancel : function () {
// the action was cancelled by the user
// no other events will be called
}
});
kik.photo.getFromGallery(function (photos) {
// do something with the photos
});
kik.photo.saveToGallery("url", function (status) {
if (status) {
// save succeeded
} else {
// save failed
}
});
kik.picker(
"http://othersite.com/",
{ arbitrary : "request data" },
function (response) {
// do something with the picked data!
}
);
if (kik.picker.reply) {
// webpage was launched in "picker mode"
// kik.picker.url === the url of the calling webpage
// kik.picker.data === { arbitrary : "request data" }
kik.picker.reply({ arbitrary : "response data" });
}
kik.ready(function () {
// expensive task that should not block loading
});
function handleBackButton () {
// called when back button is pressed
return false; // optionally cancel default behavior
}
kik.browser.back(handleBackButton); // handle back button
kik.browser.unbindBack(handleBackButton); // unbind from handling back button
kik.open("http://www.google.com/");
kik.open("https://pop.kik.com/");
kik.open("twitter://post");
kik.open("http://mysite.com/", true); // opens in popup mode
kik.open("https://thirdparty.com/auth/page/path", true);
kik.open("http://mysite.com/#response-data");
kik.linkData; // "response-data"
kik.on("linkData", function () {
kik.linkData; // "response-data"
});
if (kik.browser.background) {
// the webpage is in the background
}
kik.browser.on("background", function () {
// the webpage is now in the background
});
kik.browser.on("foreground", function () {
// the webpage has returned to the foreground
});
// lock the orientation in landscape mode
kik.browser.setOrientationLock("landscape");
// unlock the orientation
kik.browser.setOrientationLock("free");
kik.browser.statusBar(false); // hide status bar
kik.browser.statusBar(true); // show status bar
kik.formHelpers.show(); // show helpers
kik.formHelpers.hide(); // hide helpers
kik.formHelpers.isEnabled(); // check if enabled
// backlight will not turn off as long
// as your webpage is visible to the user
kik.browser.backlightTimeout(false);
// backlight will timeout as per OS rules
kik.browser.backlightTimeout(true);
function eventHandler () {
// do something when event occurs
}
// bind to event
kik.on("message", eventHandler);
// unbind from event
kik.off("message", eventHandler);
// bind to an event once (ignoring subsequent occurrences)
kik.once("message", eventHandler);
kik.trigger("message", {
title : "Fake message" ,
// object will be passed to all event listeners
});
let os = kik.utils.platform.os;
typeof os.name === "string"; // "ios", "android", "osx", "windows", etc
typeof os.version === "number"; // numeric version number
let browser = kik.utils.platform.browser;
typeof browser.name === "string"; // "chrome", "safari", "opera", etc
typeof browser.version === "number"; // numeric version number
let version = kik.utils.platform.version;
typeof browser.name === "string";
typeof browser.version === "number"; // numeric version number
+135
View File
@@ -0,0 +1,135 @@
// Type definitions for Kik Cards v2.3.6
// Project: https://dev.kik.com
// Definitions by: Joel Day <https://github.com/joelday/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Kik {
enabled: boolean;
message: KikMessage;
send(user: string, message: KikMessage): void;
send(message: KikMessage): void;
ready(callback: () => void): void;
hasPermission(): boolean;
open(url: string, popupMode?: boolean): void;
on(property: string, eventHandler: () => void): void;
off(property: string, eventHandler: () => void): void;
once(property: string, eventHandler: () => void): void;
trigger(property: string, data?: any): void;
linkData: string;
getUser(callback: (user: KikUser) => void): void;
getAnonymousUser(callback: (token: string) => void): void;
sign(data: string, callback: (signedData: string, username: string, host: string) => void): void;
anonymousSign(data: string, callback: (signedData: string, anonToken: string, host: string) => void): void;
openConversation(username: string): void;
showProfile(username: string): void;
pickUsers(options: KikPickUsersOptions, callback: (users: KikUser[]) => void): void;
pickUsers(callback: (users: KikUser[]) => void): void;
formHelpers: {
show(): void;
hide(): void;
isEnabled(): boolean;
};
metrics: {
enableGoogleAnalytics(): void;
enableGoogleAnalytics(trackingId: string, domain: string, oldApi?: boolean): void;
};
photo: {
get(options: KikGetOptions, callback: (photos: string[]) => void): void;
getFromCamera(callbacks: KikGetFromCameraCallbacks): void;
getFromCamera(options: KikGetFromCameraOptions, callbacks: KikGetFromCameraCallbacks): void;
getFromGallery(callback: (photos: string[]) => void): void;
getFromGallery(options: KikGetOptions, callback: (photos: string[]) => void): void;
saveToGallery(url: string, callback: (status: boolean) => void): void;
get(callback: (photos: string[]) => void): void;
};
picker: {
(url: string, data: any, callback: (response: any) => void): void;
reply: (data: any) => void;
};
browser: {
background: boolean;
back(callback: () => boolean | void): void;
unbindBack(callback: () => boolean | void): void;
on(property: string, callback: () => void): void;
off(property: string, callback: () => void): void;
once(property: string, callback: () => void): void;
trigger(property: string, data?: any): void;
getOrientationLock(): string;
setOrientationLock(lock: "free" | "landscape" | "portrait"): void;
setOrientationLock(lock: string): void;
statusBar(show: boolean): void;
backlightTimeout(timeout: boolean): void;
};
utils: {
platform: {
os: {
name: string;
version: string;
};
browser: {
name: string;
version: string;
};
version: {
name: string;
version: string;
};
};
};
}
interface KikUser {
username: string;
fullName: string;
firstName: string;
lastName: string;
pic: string;
thumbnail: string;
}
interface KikMessage {
title: string;
text: string;
pic?: string;
big?: boolean;
noForward?: boolean;
data?: any;
}
interface KikPickUsersOptions {
minResults?: number;
maxResults?: number;
preselected?: { username: string }[];
filtered?: string[];
filterSelf?: boolean;
}
interface KikGetOptions {
quality?: number;
minResults?: number;
maxResults?: number;
maxHeight?: number;
maxWidth?: number;
}
interface KikGetFromCameraOptions {
quality?: number;
maxHeight?: number;
maxWidth?: number;
}
interface KikGetFromCameraCallbacks {
onSelect: (numPhotos: number) => void;
onPhoto: (photo: string, index: number) => void;
onComplete: (photos: string[]) => void;
onCancel: () => void;
}
declare const kik: Kik;
+5 -4
View File
@@ -3,11 +3,11 @@
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path="../node/node.d.ts" />
declare module "knex" {
// import Promise = require("bluebird");
import Promise = require("bluebird");
import * as events from "events";
type Callback = Function;
@@ -299,8 +299,8 @@ declare module "knex" {
// Schema builder
//
interface SchemaBuilder {
createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): Promise<void>;
interface SchemaBuilder extends Promise<any> {
createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder;
renameTable(oldTableName: string, newTableName: string): Promise<void>;
dropTable(tableName: string): Promise<void>;
hasTable(tableName: string): Promise<boolean>;
@@ -339,6 +339,7 @@ declare module "knex" {
unique(columnNames: string[], indexName?: string) : TableBuilder;
foreign(column: string): ForeignConstraintBuilder;
foreign(columns: string[]): MultikeyForeignConstraintBuilder;
dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder;
}
interface CreateTableBuilder extends TableBuilder {
@@ -1,252 +0,0 @@
/// <reference path="knockout.deferred.updates.d.ts" />
// Turn *off* deferred updates for computed observables and subscriptions
ko.computed.deferUpdates = false;
var myComputed = ko.computed(() => { /* ... */ });
// Turn *on* deferred updates for this computed observable
myComputed.deferUpdates = true;
var myObservable = ko.observable();
var mySubscription = myObservable.subscribe((value) => { /* ... */ });
// Turn *on* deferred updates for this subscription
mySubscription.deferUpdates = true;
// Turn *off* deferred updates for this computed observable
myComputed.extend({ deferred: false });
//
// Examples
//
function nestedComputedNoPlugin() {
var vm: any = {
a: ko.observable(0),
b: ko.observable(0),
c: ko.observable(0),
d: ko.observable(0),
e: ko.observable(0),
f: ko.observable(0)
};
var startTime = new Date().getTime();
var updateArray = [];
function firstUpdate() {
var updateList = document.getElementById('updates');
while (updateList.firstChild) updateList.removeChild(updateList.firstChild);
}
function pushUpdate(name, value, color) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(name + ' ' + value + '; ' + (new Date().getTime() - startTime) + ' ms'));
li.style.color = color;
document.getElementById('updates').appendChild(li);
}
function lastUpdate() {
}
var updateCounter = 0, plusminus = 1;
vm.doUpdate = function () {
var u = updateCounter += plusminus;
startTime = new Date().getTime();
vm.a(u);
vm.b(u);
vm.c(u);
vm.d(u);
vm.e(u);
vm.f(u);
plusminus = !u ? 1 : (u == 9) ? -1 : plusminus;
};
vm.setThrottle = function (value) {
vm.A.throttleEvaluation = value;
vm._B.throttleEvaluation = value;
vm.C.throttleEvaluation = value;
vm.D.throttleEvaluation = value;
vm.E.throttleEvaluation = value;
vm.F.throttleEvaluation = value;
};
vm.runNormal = function () {
ko.computed.deferUpdates = false;
vm.setThrottle(undefined);
vm.doUpdate();
};
vm.runThrottle = function () {
ko.computed.deferUpdates = false;
vm.setThrottle(1);
vm.doUpdate();
};
vm.A = ko.computed(function () {
var result = '' + vm.a();
firstUpdate();
pushUpdate('A', result, 'green');
return result;
}, null, { deferEvaluation: true });
vm._B = ko.computed(function () {
var result = '' + vm.A() + vm.b();
pushUpdate('B', result, 'darkturquoise');
return result;
}, null, { deferEvaluation: true });
vm.C = ko.computed(function () {
var result = '' + vm._B() + vm.c();
pushUpdate('C', result, 'royalblue');
return result;
}, null, { deferEvaluation: true });
vm.D = ko.computed(function () {
var result = '' + vm.C() + vm.d();
pushUpdate('D', result, 'indigo');
return result;
}, null, { deferEvaluation: true });
vm.E = ko.computed(function () {
var result = '' + vm.D() + vm.e();
pushUpdate('E', result, 'firebrick');
return result;
}, null, { deferEvaluation: true });
vm.F = ko.computed(function () {
var f = vm.f(), result = '' + vm.E() + f;
pushUpdate('F', result, 'orangered');
if (result === '' + f + f + f + f + f + f) lastUpdate();
return result;
}, null, { deferEvaluation: true });
vm.A();
vm._B();
vm.C();
vm.D();
vm.E();
vm.F();
ko.applyBindings(vm);
};
function nestedComputedPlugin() {
var vm: any = {
a: ko.observable(0),
b: ko.observable(0),
c: ko.observable(0),
d: ko.observable(0),
e: ko.observable(0),
f: ko.observable(0)
};
var startTime = new Date().getTime();
var updateArray = [];
function firstUpdate() {
var updateList = document.getElementById('updates');
while (updateList.firstChild)
updateList.removeChild(updateList.firstChild);
}
function pushUpdate(name, value, color) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(name + ' ' + value + '; ' + (new Date().getTime() - startTime) + ' ms'));
li.style.color = color;
document.getElementById('updates').appendChild(li);
}
function lastUpdate() {
}
var updateCounter = 0, plusminus = 1;
vm.doUpdate = function () {
var u = updateCounter += plusminus;
startTime = new Date().getTime();
vm.a(u);
vm.b(u);
vm.c(u);
vm.d(u);
vm.e(u);
vm.f(u);
plusminus = !u ? 1 : (u == 9) ? -1 : plusminus;
};
vm.setThrottle = function (value) {
vm.A.throttleEvaluation = value;
vm._B.throttleEvaluation = value;
vm.C.throttleEvaluation = value;
vm.D.throttleEvaluation = value;
vm.E.throttleEvaluation = value;
vm.F.throttleEvaluation = value;
};
vm.runNormal = function () {
ko.computed.deferUpdates = false;
vm.setThrottle(undefined);
vm.doUpdate();
};
vm.runThrottle = function () {
ko.computed.deferUpdates = false;
vm.setThrottle(1);
vm.doUpdate();
};
vm.runDefer = function () {
ko.computed.deferUpdates = true;
vm.setThrottle(undefined);
vm.doUpdate();
};
vm.runWrappedDefer = ko.tasks.makeProcessedCallback(vm.runDefer);
vm.A = ko.computed(function () {
var result = '' + vm.a();
firstUpdate();
pushUpdate('A', result, 'green');
return result;
}, null, { deferEvaluation: true });
vm._B = ko.computed(function () {
var result = '' + vm.A() + vm.b();
pushUpdate('B', result, 'darkturquoise');
return result;
}, null, { deferEvaluation: true });
vm.C = ko.computed(function () {
var result = '' + vm._B() + vm.c();
pushUpdate('C', result, 'royalblue');
return result;
}, null, { deferEvaluation: true });
vm.D = ko.computed(function () {
var result = '' + vm.C() + vm.d();
pushUpdate('D', result, 'indigo');
return result;
}, null, { deferEvaluation: true });
vm.E = ko.computed(function () {
var result = '' + vm.D() + vm.e();
pushUpdate('E', result, 'firebrick');
return result;
}, null, { deferEvaluation: true });
vm.F = ko.computed(function () {
var f = vm.f(), result = '' + vm.E() + f;
pushUpdate('F', result, 'orangered');
if (result === '' + f + f + f + f + f + f) lastUpdate();
return result;
}, null, { deferEvaluation: true });
vm.A();
vm._B();
vm.C();
vm.D();
vm.E();
vm.F();
ko.applyBindings(vm);
}
@@ -1,46 +0,0 @@
// Type definitions for Knockout Deferred Updates
// Project: https://github.com/mbest/knockout-deferred-updates
// Definitions by: Sebastián Galiano <https://github.com/sgaliano/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../knockout/knockout.d.ts" />
interface KnockoutDeferredTasks {
processImmediate(evaluator: Function, object?: any, args?: any[]): any;
processDelayed(evaluator: Function, distinct?: boolean, options?: any[]): boolean;
makeProcessedCallback(evaluator: Function): void;
}
// Knockout global
interface KnockoutStatic {
tasks: KnockoutDeferredTasks;
processAllDeferredBindingUpdates(): void;
processAllDeferredUpdates(): void;
evaluateAsynchronously(evaluator: Function, timeout?: any): number;
ignoreDependencies(callback: Function, callbackTarget: any, callbackArgs?: any[]);
}
// Observables
interface KnockoutSubscribableFunctions<T> {
deferUpdates: boolean;
}
// Computed
interface KnockoutComputedStatic {
deferUpdates: boolean;
}
interface KnockoutSubscription {
deferUpdates: boolean;
}
// Utils
interface KnockoutUtils {
objectForEach(obj: any, action: Function): void;
objectMap(source: any, mapping: Function): any;
}
// Deferred extender
interface KnockoutExtenders {
deferred(target: any, value: boolean): any;
}
+81 -8
View File
@@ -6,22 +6,95 @@
/// <reference path="../knockout/knockout.d.ts" />
interface KnockoutValidationGroupingOptions {
/**
* indicates whether to walk the ViewModel (or object)
* recursively, or only walk first-level properties.
*/
deep?: boolean;
/**
* indicates whether the returned errors object
* is a ko.computed or a simple function
*/
observable?: boolean;
/**
* indicates whether changes to observableArrays inside
* the model should cause the validator to re-run
*/
live?: boolean;
}
interface KnockoutValidationValidateOptions {
throttle?: number;
}
interface KnockoutValidationConfiguration {
registerExtenders?: boolean;
messagesOnModified?: boolean;
messageTemplate?: string;
insertMessages?: boolean;
parseInputAttributes?: boolean;
writeInputAttributes?: boolean;
/**
* Allows HTML in validation messages
*/
allowHtmlMessages?: boolean;
/**
* Indicates whether css error classes are added only
* when properties are modified or at all times
* @type {[type]}
*/
decorateElementOnModified?: boolean;
/**
* Indicates whether to assign an error class to the <input> tag
* when your property is invalid
*/
decorateInputElement?: boolean;
/**
* If defined, the CSS class assigned to both <input> and validation message elements
*/
errorClass?: string;
/**
* The CSS class assigned to validation error <input> elements, must have decorateInputElement set to true
*/
errorElementClass?: string;
/**
* The CSS class assigned to validation error messages
*/
errorMessageClass?: string;
/**
* Shows tooltips using input 'title' attribute. False hides them
*/
errorsAsTitle?: boolean;
/**
* Shows the error when hovering the input field (decorateElement must be true)
*/
errorsAsTitleOnModified?: boolean;
grouping?: KnockoutValidationGroupingOptions;
/**
* If true validation will insert either a <span> element or the template
* specified by messageTemplate after any element (e.g. <input>)
* that uses a KO value binding with a validated field
*/
insertMessages?: boolean;
/**
* Indicates whether validation messages are triggered only
* when properties are modified or at all times
*/
messagesOnModified?: boolean;
/**
* The id of the <script type="text/html"></script>
* that you want to use for all your validation messages
*/
messageTemplate?: string;
/**
* Indicates whether to assign validation rules to your ViewModel
* using HTML5 validation attributes
*/
parseInputAttributes?: boolean;
/**
* Register custom validation rules defined via ko.validation.rules
*/
registerExtenders?: boolean;
validate?: KnockoutValidationValidateOptions;
/**
* Add HTML5 input validation attributes to form elements
* that ko observable's are bound to
*/
writeInputAttributes?: boolean;
}
interface KnockoutValidationUtils {
@@ -154,7 +227,7 @@ interface KnockoutSubscribableFunctions<T> {
}
declare module "knockout.validation" {
export = validation;
export = validation;
}
declare var validation: KnockoutValidationStatic
declare var validation: KnockoutValidationStatic
+20 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for Knockout v3.2.0
// Type definitions for Knockout v3.4.0
// Project: http://knockoutjs.com
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Igor Oleinikov <https://github.com/Igorbek/>, Clément Bourgeois <https://github.com/moonpyk/>
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Igor Oleinikov <https://github.com/Igorbek/>, Clément Bourgeois <https://github.com/moonpyk/>, Matt Brooks <https://github.com/EnableSoftware>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -387,6 +387,17 @@ interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine {
rewriteTemplate(template: any, rewriterCallback: Function, templateDocument: Document): void;
}
//////////////////////////////////
// tasks.js
//////////////////////////////////
interface KnockoutTasks {
scheduler: (callback: Function) => any;
schedule(task: Function): number;
cancel(handle: number): void;
runEarly(): void;
}
/////////////////////////////////
interface KnockoutStatic {
@@ -544,7 +555,13 @@ interface KnockoutStatic {
deferUpdates: boolean,
useOnlyNativeEvents: boolean
}
};
/////////////////////////////////
// tasks.js
/////////////////////////////////
tasks: KnockoutTasks;
}
interface KnockoutBindingProvider {
+27 -2
View File
@@ -570,8 +570,8 @@ function test_misc() {
$(element).datepicker("destroy");
});
this.observableFactory = function(): KnockoutObservable<number>{
if (true) {
this.observableFactory = function(flag = true): KnockoutObservable<number>{
if (flag) {
return ko.computed({
read:function(){
return 3;
@@ -655,3 +655,28 @@ function testUnwrapUnion() {
var num = ko.unwrap(possibleObs);
}
function test_tasks() {
// Schedule an empty task
ko.tasks.schedule(function() {
});
// Schedule a task with arguments and return type
let logSomethingTask = (message: string) => {
console.log("Log message");
return true;
};
let taskHandle = ko.tasks.schedule(logSomethingTask);
// Cancel a task
ko.tasks.cancel(taskHandle);
// Process the current microtask queue on demand
ko.tasks.runEarly();
// Redefine or augment how Knockout schedules the event to process and flush the queue
ko.tasks.scheduler = function (callback) {
setTimeout(callback, 0);
};
}
+11 -1
View File
@@ -28,8 +28,18 @@ interface KoLiteActivity {
getOpacity(options: { steps?: number; segments?: number; opacity?: number; }, i: number): number;
}
interface KoLiteActivityDefaultOptions {
activityClass?: string,
container?: string,
inactiveClass?: string
}
interface KoLiteActivityBindingHandler extends KnockoutBindingHandler {
defaultOptions: KoLiteActivityDefaultOptions
}
interface KnockoutBindingHandlers {
activity: KnockoutBindingHandler;
activity: KoLiteActivityBindingHandler;
}
interface JQuery {
+14
View File
@@ -2,6 +2,20 @@
/// <reference path="../knockout/knockout.d.ts" />
/// <reference path="kolite.d.ts" />
function test_activityDefaults() {
ko.bindingHandlers.activity.defaultOptions = {
activityClass: 'fa fa-spinner fa-spin',
container: 'i',
inactiveClass: ''
};
ko.bindingHandlers.activity.defaultOptions = {
activityClass: 'some Value'
};
ko.bindingHandlers.activity.defaultOptions = {
};
}
function test_asyncCommand() {
var saveCmd = ko.asyncCommand({
execute: function (complete) {
+1837 -1
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1434,7 +1434,7 @@ declare namespace __MaterialUI {
autoHideDuration?: number;
bodyStyle?: React.CSSProperties;
className?: string;
message: string;
message: string | JSX.Element;
onActionTouchTap?: React.TouchEventHandler;
/** @deprecated Use the open property to control the component instead */
onDismiss?: () => void; // DEPRECATED
+1 -1
View File
@@ -52,4 +52,4 @@ var todo = {
};
//initialize the application
m.module(document, todo);
m.mount(document, todo);
+782 -97
View File
@@ -3,175 +3,860 @@
// Definitions by: Leo Horie <https://github.com/lhorie>, Chris Bowdon <https://github.com/cbowdon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//Mithril type definitions for Typescript
// Mithril type definitions for Typescript
declare module _mithril {
interface MithrilStatic {
/**
* This is the module containing all the types/declarations/etc. for Mithril
*/
declare namespace Mithril {
interface ChildArray extends Array<Children> {}
type Children = Child | ChildArray;
type Child = string | VirtualElement | Component<Controller>;
<T extends MithrilController>(selector: string, attributes: MithrilAttributes, ...children: Array<string|MithrilVirtualElement|MithrilComponent<T>>): MithrilVirtualElement;
<T extends MithrilController>(selector: string, ...children: Array<string|MithrilVirtualElement|MithrilComponent<T>>): MithrilVirtualElement;
interface Static {
/**
* Creates a virtual element for use with m.render, m.mount, etc.
*
* @param selector A simple CSS selector. May include SVG tags. Nested
* selectors are not supported.
* @param attributes Attributes to add. Any DOM attribute may be used
* as an attribute, although innerHTML and the like may be overwritten
* silently.
* @param children Child elements, components, and text to add.
* @return A virtual element.
*
* @see m.render
* @see m.mount
* @see m.component
*/
(
selector: string,
...children: Children[]
): VirtualElement;
prop<T>(promise: MithrilPromise<T>) : MithrilPromiseProperty<T>;
prop<T>(value: T): MithrilProperty<T>;
prop(): MithrilProperty<Object>; // might be that this should be Property<any>
/**
* Creates a virtual element for use with m.render, m.mount, etc.
*
* @param selector A simple CSS selector. May include SVG tags. Nested
* selectors are not supported.
* @param attributes Attributes to add. Any DOM attribute may be used
* as an attribute, although innerHTML and the like may be overwritten
* silently.
* @param children Child elements, components, and text to add.
* @return A virtual element.
*
* @see m.render
* @see m.mount
* @see m.component
*/
(
selector: string,
attributes: Attributes,
...children: Children[]
): VirtualElement;
withAttr(property: string, callback: (value: any) => void): (e: MithrilEvent) => any;
/**
* Initializes a component for use with m.render, m.mount, etc.
*
* @param component A component.
* @param args Arguments to optionally pass to the component.
* @return A component.
*
* @see m.render
* @see m.mount
* @see m
*/
<T extends Controller>(
component: Component<T>,
...args: any[]
): Component<T>;
module<T extends MithrilController>(rootElement: Node, component: MithrilComponent<T>): T;
module<T extends MithrilController>(rootElement: Node): T;
mount<T extends MithrilController>(rootElement: Node, component: MithrilComponent<T>): T;
mount<T extends MithrilController>(rootElement: Node): T;
/**
* Creates a getter-setter function that wraps a Mithril promise. Useful
* for uniform data access, m.withAttr, etc.
*
* @param promise A thennable to initialize the property with. It may
* optionally be a Mithril promise.
* @return A getter-setter function wrapping the promise.
*
* @see m.withAttr
*/
prop<T>(promise: Thennable<T>) : Promise<T>;
component<T extends MithrilController>(component: MithrilComponent<T>, ...args: Array<any>): MithrilComponent<T>
trust(html: string): string;
/**
* Creates a getter-setter function that wraps a simple value. Useful
* for uniform data access, m.withAttr, etc.
*
* @param value A value to initialize the property with
* @return A getter-setter function wrapping the value.
*
* @see m.withAttr
*/
prop<T>(value: T): BasicProperty<T>;
render(rootElement: Element|HTMLDocument): void;
render(rootElement: Element|HTMLDocument, children: MithrilVirtualElement, forceRecreation?: boolean): void;
render(rootElement: Element|HTMLDocument, children: MithrilVirtualElement[], forceRecreation?: boolean): void;
/**
* Creates a getter-setter function that wraps a simple value. Useful
* for uniform data access, m.withAttr, etc.
*
* @return A getter-setter function wrapping the value.
*
* @see m.withAttr
*/
prop<T>(): BasicProperty<T>;
/**
* Returns a event handler that can be bound to an element, firing with
* the specified property.
*
* @param property The property to get from the event.
* @param callback The handler to use the value from the event.
* @return A function suitable for listening to an event.
*/
withAttr(
property: string,
callback: (value: any) => any,
callbackThis?: any
): (e: Event) => void;
/**
* @deprecated Use m.mount instead
*/
module<T extends Controller>(
rootElement: Node,
component: Component<T>
): T;
/**
* Mounts a component to a base DOM node.
*
* @param rootElement The base node.
* @param component The component to mount.
* @return An instance of the top-level component's controller
*/
mount<T extends Controller>(
rootElement: Node,
component: Component<T>
): T;
/**
* Initializes a component for use with m.render, m.mount, etc.
*
* @param selector A component.
* @param args Arguments to optionally pass to the component.
* @return A component.
*
* @see m.render
* @see m.mount
* @see m
*/
component<T extends Controller>(
component: Component<T>,
...args: any[]
): Component<T>;
/**
* Trust this string of HTML.
*
* @param html The HTML to trust
* @return A String object instance with an added internal flag to mark
* it as trusted.
*/
trust(html: string): TrustedString;
/**
* Render a virtual DOM tree.
*
* @param rootElement The base element/node to render the tree from.
* @param children One or more child nodes to add to the tree.
* @param forceRecreation If true, overwrite the entire tree without
* diffing against it.
*/
render(
rootElement: Element,
children: VirtualElement|VirtualElement[],
forceRecreation?: boolean
): void;
redraw: {
/**
* Force a redraw the active component. It redraws asynchronously by
* default to allow for simultaneous events to run before redrawing,
* such as the event combination keypress + input frequently used for
* input.
*
* @param force If true, redraw synchronously.
*/
(force?: boolean): void;
strategy: MithrilProperty<string>;
/**
* Gets/sets the current redraw strategy, which returns one of the
* following:
*
* "all" - recreates the DOM tree from scratch
* "diff" - recreates the DOM tree from scratch
* "none" - leaves the DOM tree intact
*
* This is useful for event handlers, which may want to cancel
* the next redraw if the event doesn't update the UI.
*
* @return The current strategy
*/
strategy: BasicProperty<"all" | "diff" | "none">;
}
route: {
<T extends MithrilController>(rootElement: HTMLDocument, defaultRoute: string, routes: MithrilRoutes<T>): void;
<T extends MithrilController>(rootElement: Element, defaultRoute: string, routes: MithrilRoutes<T>): void;
/**
* Enable routing, mounting a controller based on the route. It
* automatically mounts the components for you, starting with the one
* specified by the default route.
*
* @param rootElement The element to mount the active controller to.
* @param defaultRoute The route to start with.
* @param routes A key-value mapping of pathname to controller.
*/
(
rootElement: Element,
defaultRoute: string,
routes: Routes
): void;
(element: Element, isInitialized: boolean, context: Object, vdom: Object): void;
/**
* This allows m.route to be used as the `config` attribute for a
* virtual element, particularly useful for cases like this:
*
* ```ts
* // Note that the '#' is not required in `href`, thanks to the
* `config` setting.
* m("a[href='/dashboard/alicesmith']", {config: m.route});
* ```
*/
(
element: Element,
isInitialized: boolean,
context?: Context,
vdom?: VirtualElement
): void;
/**
* Programmatically redirect to another route.
*
* @param path The route to go to.
* @param params Parameters to pass as a query string.
* @param shouldReplaceHistory Whether to replace the current history
* instead of adding a new one.
*/
(path: string, params?: any, shouldReplaceHistory?: boolean): void;
/**
* Gets the current route.
*
* @return The current route.
*/
(): string;
/**
* Gets a route parameter.
*
* @param key The key to get.
* @return The value associated with the parameter key.
*/
param(key: string): string;
mode: string;
buildQueryString(data: Object): String
parseQueryString(data: String): Object
/**
* The current routing mode. This may be changed before calling
* m.route to change the part of the URL used to perform the routing.
*
* The value can be set to one of the following, defaulting to
* "hash":
*
* "search" - Uses the query string. This allows for named anchors to
* work on the page, but changes cause IE8 and lower to refresh the
* page.
*
* "hash" - Uses the hash. This is the only routing mode that does
* not cause page refreshes on any browser, but it does not support
* named anchors.
*
* "pathname" - Uses the URL pathname. This requires server-side
* setup to support bookmarking and page refreshes. It always causes
* page refreshes on IE8 and lower. Note that this requires that the
* application to be run from the root of the URL.
*/
mode: "search" | "hash" | "pathname";
/**
* Serialize an object into a query string.
*
* @param data The data to serialize.
* @return The serialized string.
*/
buildQueryString(data: Object): string;
/**
* Parse a query string into an object.
*
* @param data The data to parse.
* @return The parsed object data.
*/
parseQueryString(data: string): Object;
}
request<T>(options: MithrilXHROptions): MithrilPromise<T>;
/**
* Send an XHR request to a server. Note that the `url` option is
* required.
*
* @param options The options to use for the request.
* @return A promise to the returned data, or void if not applicable.
*
* @see XHROptions for the available options.
*/
request(options: XHROptions): Promise<any>
/**
* Send a JSONP request to a server. Note that the `url` option is
* required.
*
* @param options The options to use
* @return A promise to the returned data.
*
* @see JSONPOptions for the available options.
*/
request(options: JSONPOptions): Promise<any>;
deferred: {
/**
* Create a Mithril deferred object. It behaves synchronously if
* possible, an intentional deviation from Promises/A+. Note that
* deferreds are completely separate from the redrawing system, and
* never trigger a redraw on their own.
*
* @return A new Mithril deferred instance.
*
* @see m.deferred.onerror for the error callback called for Error
* subclasses
*/
<T>(): Deferred<T>;
/**
* A callback for all uncaught native Error subclasses in deferreds.
* This defaults to synchronously rethrowing all errors, a deviation
* from Promises/A+, but the behavior is configurable. To restore
* Promises/A+-compatible behavior. simply set this to a no-op.
*/
onerror(e: Error): void;
<T>(): MithrilDeferred<T>;
}
sync<T>(promises: MithrilPromise<T>[]): MithrilPromise<T[]>;
/**
* Takes a list of promises or thennables and returns a Mithril promise
* that resolves once all in the list are resolved, or rejects if any of
* them reject.
*
* @param promises A list of promises to try to resolve.
* @return A promise that resolves to all the promises if all resolve, or
* rejects with the error contained in the first rejection.
*/
sync<T>(promises: Thennable<T>[]): Promise<T[]>;
/**
* Use this and endComputation if your views aren't redrawing after
* calls to third-party libraries. For integrating asynchronous code,
* this should be called before any asynchronous work is done. For
* synchronous code, this should be called at the beginning of the
* problematic segment. Note that these calls must be balanced, much like
* braces and parentheses. This is mostly used internally. Prefer
* m.redraw where possible, especially when making repeated calls.
*
* @see endComputation
* @see m.render
*/
startComputation(): void;
/**
* Use startComputation and this if your views aren't redrawing after
* calls to third-party libraries. For integrating asynchronous code,
* this should be called after all asynchronous work completes. For
* synchronous code, this should be called at the end of the problematic
* segment. Note that these calls must be balanced, much like braces and
* parentheses. This is mostly used internally. Prefer m.redraw where
* possible, especially when making repeated calls.
*
* @see startComputation
* @see m.render
*/
endComputation(): void;
// For test suite
deps: {
(mockWindow: Window): Window;
factory: Object;
}
/**
* This overwrites the internal version of window used by Mithril.
* It's mostly useful for testing, and is also used internally by
* Mithril to test itself. By default Mithril uses `window` for the
* dependency.
*
* @param mockWindow The mock to use for the window.
* @return The mock that was passed in.
*/
deps(mockWindow: Window): Window;
}
export interface MithrilVirtualElement {
key?: number;
tag?: string;
attrs?: MithrilAttributes;
children?: any[];
interface TrustedString extends String {
/** @private Implementation detail. Don't depend on it. */
$trusted: boolean;
}
// Configuration function for an element
interface MithrilElementConfig {
(element: Element, isInitialized: boolean, context?: any, vdom?: MithrilVirtualElement): void;
/**
* The interface for a virtual element. It's best to consider this immutable
* for most use cases.
*
* @see m
*/
interface VirtualElement {
/**
* The tag name of this element.
*/
tag: string;
/**
* The attributes of this element.
*/
attrs: Attributes;
/**
* The children of this element.
*/
children: Children[];
}
// Attributes on a virtual element
interface MithrilAttributes {
title?: string;
/**
* An event passed by Mithril to unload event handlers.
*/
interface Event {
/**
* Prevent the default behavior of scrolling the page and updating the
* URL on next route change.
*/
preventDefault(): void;
}
/**
* A context object for configuration functions.
*
* @see ElementConfig
*/
interface Context {
/**
* A function to call when the node is unloaded. Useful for cleanup.
*/
onunload?(): any;
/**
* Set true if the backing DOM node needs to be retained between route
* changes if possible. Set false if this node needs to be recreated
* every single time, regardless of how "different" it is.
*/
retain?: boolean;
}
/**
* This represents a callback function for a virtual element's config
* attribute. It's a low-level function useful for extra cleanup after
* removal from the tree, storing instances of third-party classes that
* need to be associated with the DOM, etc.
*
* @see Attributes
* @see Context
*/
interface ElementConfig {
/**
* A callback function for a virtual element's config attribute.
*
* @param element The associated DOM element.
* @param isInitialized Whether this is the first call for the virtual
* element or not.
* @param context The associated context for this element.
* @param vdom The associated virtual element.
*/
(
element: Element,
isInitialized: boolean,
context: Context,
vdom: VirtualElement
): void;
}
/**
* This represents the attributes available for configuring virtual elements,
* beyond the applicable DOM attributes.
*
* @see m
*/
interface Attributes {
/**
* The class name(s) for this virtual element, as a space-separated list.
*/
className?: string;
/**
* The class name(s) for this virtual element, as a space-separated list.
*/
class?: string;
config?: MithrilElementConfig;
/**
* A custom, low-level configuration in case this element needs special
* cleanup after removal from the tree.
*
* @see ElementConfig
*/
config?: ElementConfig;
/**
* A key to optionally associate with this element.
*/
key?: string | number;
/**
* Any other virtual element properties, including attributes and event
* handlers.
*/
[property: string]: any;
}
// Defines the subset of Event that Mithril needs
interface MithrilEvent {
currentTarget: Element;
}
interface MithrilController {
/**
* The basis of a Mithril controller instance.
*/
interface Controller {
/**
* An optional handler to call when the associated virtual element is
* destroyed.
*
* @param evt An associated event.
*/
onunload?(evt: Event): any;
}
interface MithrilControllerFunction extends MithrilController {
(): any;
/**
* This represents a controller function.
*
* @see ControllerConstructor
*/
interface ControllerFunction<T extends Controller> {
(...args: any[]): T;
}
interface MithrilView<T extends MithrilController> {
(ctrl: T): string|MithrilVirtualElement;
/**
* This represents a controller constructor.
*
* @see ControllerFunction
*/
interface ControllerConstructor<T extends Controller> {
new (...args: any[]): T;
}
interface MithrilComponent<T extends MithrilController> {
controller: MithrilControllerFunction|{ new(): T };
view: MithrilView<T>;
/**
* This represents a Mithril component.
*
* @see m
* @see m.component
*/
interface Component<T extends Controller> {
/**
* The component's controller.
*
* @see m.component
*/
controller: ControllerFunction<T> | ControllerConstructor<T>;
/**
* Creates a view out of virtual elements.
*
* @see m.component
*/
view(ctrl?: T, ...args: any[]): VirtualElement;
}
interface MithrilProperty<T> {
/**
* This is the base interface for property getter-setters
*
* @see m.prop
*/
interface Property<T> {
/**
* Gets the contained value.
*
* @return The contained value.
*/
(): T;
/**
* Sets the contained value.
*
* @param value The new value to set.
* @return The newly set value.
*/
(value: T): T;
}
/**
* This represents a non-promise getter-setter functions.
*
* @see m.prop which returns objects that implement this interface.
*/
interface BasicProperty<T> extends Property<T> {
/**
* Makes this serializable to JSON.
*/
toJSON(): T;
}
interface MithrilPromiseProperty<T> extends MithrilPromise<T> {
(): T;
(value: T): T;
toJSON(): T;
/**
* This represents a key-value mapping linking routes to components.
*/
interface Routes {
/**
* The key represents the route. The value represents the corresponding
* component.
*/
[key: string]: Component<Controller>;
}
interface MithrilRoutes<T extends MithrilController> {
[key: string]: MithrilComponent<T>;
}
interface MithrilDeferred<T> {
/**
* This represents a Mithril deferred object.
*/
interface Deferred<T> {
/**
* Resolve this deferred's promise with a value.
*
* @param value The value to resolve the promise with.
*/
resolve(value?: T): void;
reject(value?: any): void;
promise: MithrilPromise<T>;
/**
* Reject this deferred with an error.
*
* @param value The reason for rejecting the promise.
*/
reject(reason?: any): void;
/**
* The backing promise.
*
* @see Promise
*/
promise: Promise<T>;
}
interface MithrilSuccessCallback<T, U> {
(value: T): U;
(value: T): MithrilPromise<U>;
/**
* This represents a thennable success callback.
*/
interface SuccessCallback<T, U> {
(value: T): U | Thennable<U>;
}
interface MithrilErrorCallback<U> {
(value: Error): U;
(value: string): U;
/**
* This represents a thennable error callback.
*/
interface ErrorCallback<T> {
(value: Error): T | Thennable<T>;
}
interface MithrilPromise<T> {
(): T;
(value: T): T;
then<U>(success: (value: T) => U): MithrilPromise<U>;
then<U>(success: (value: T) => MithrilPromise<U>): MithrilPromise<U>;
then<U,V>(success: (value: T) => U, error: (value: Error) => V): MithrilPromise<U>|MithrilPromise<V>;
then<U,V>(success: (value: T) => MithrilPromise<U>, error: (value: Error) => V): MithrilPromise<U>|MithrilPromise<V>;
/**
* This represents a thennable.
*/
interface Thennable<T> {
then<U>(success: SuccessCallback<T, U>): Thennable<U>;
then<U, V>(success: SuccessCallback<T, U>, error: ErrorCallback<V>): Thennable<U | V>;
catch?(error: ErrorCallback<T>): Thennable<T>;
catch?<U>(error: ErrorCallback<U>): Thennable<T | U>;
}
interface MithrilXHROptions {
method?: string;
url: string;
user?: string;
password?: string;
/**
* This represents a Mithril promise object.
*/
interface Promise<T> extends Thennable<T>, Property<T | Promise<T>> {
/**
* Chain this promise with a simple success callback, propogating
* rejections.
*
* @param success The callback to call when the promise is resolved.
* @return The chained promise.
*/
then<U>(success: SuccessCallback<T, U>): Promise<U>;
/**
* Chain this promise with a success callback and error callback, without
* propogating rejections.
*
* @param success The callback to call when the promise is resolved.
* @param error The callback to call when the promise is rejected.
* @return The chained promise.
*/
then<U, V>(success: SuccessCallback<T, U>, error: ErrorCallback<V>): Promise<U | V>;
/**
* Chain this promise with a single error callback, without propogating
* rejections.
*
* @param error The callback to call when the promise is rejected.
* @return The chained promise.
*/
catch<U>(error: ErrorCallback<U>): Promise<T | U>;
}
/**
* These are the common options shared across normal and JSONP requests.
*
* @see m.request
*/
interface RequestOptions {
/**
* The data to be sent. It's automatically serialized in the right format
* depending on the method (with exception of HTML5 FormData), and put in
* the appropriate section of the request.
*/
data?: any;
/**
* Whether to run it in the background, i.e. true if it doesn't affect
* template rendering.
*/
background?: boolean;
/**
* Set an initial value while the request is working, to populate the
* promise getter-setter.
*/
initialValue?: any;
/**
* An optional preprocessor function to unwrap a successful response, in
* case the response contains metadata wrapping the data.
*
* @param data The data to unwrap.
* @return The unwrapped result.
*/
unwrapSuccess?(data: any): any;
/**
* An optional preprocessor function to unwrap an unsuccessful response,
* in case the response contains metadata wrapping the data.
*
* @param data The data to unwrap.
* @return The unwrapped result.
*/
unwrapError?(data: any): any;
/**
* An optional function to serialize the data. This defaults to
* `JSON.stringify`.
*
* @param dataToSerialize The data to serialize.
* @return The serialized form as a string.
*/
serialize?(dataToSerialize: any): string;
/**
* An optional function to deserialize the data. This defaults to
* `JSON.parse`.
*
* @param dataToSerialize The data to parse.
* @return The parsed form.
*/
deserialize?(dataToDeserialize: string): any;
extract?(xhr: XMLHttpRequest, options: MithrilXHROptions): string;
type?(data: Object): void;
config?(xhr: XMLHttpRequest, options: MithrilXHROptions): XMLHttpRequest;
dataType?: string;
/**
* An optional function to extract the data from a raw XMLHttpRequest,
* useful if the relevant data is in a response header or the status
* field.
*
* @param xhr The associated XMLHttpRequest.
* @param options The options passed to this request.
* @return string The serialized format.
*/
extract?(xhr: XMLHttpRequest, options: this): string;
/**
* The parsed data, or its children if it's an array, will be passed to
* this class constructor if it's given, to parse it into classes.
*
* @param data The data to parse.
* @return The new instance for the list.
*/
type?: new (data: any) => any;
/**
* The URL to send the request to.
*/
url: string;
}
/**
* This represents the available options for configuring m.request for JSONP
* requests.
*
* @see m.request
*/
interface JSONPOptions extends RequestOptions {
/**
* For JSONP requests, this must be the string "jsonp". Otherwise, it's
* ignored.
*/
dataType: "jsonp";
/**
* The querystring key for the JSONP request callback. This is useful for
* APIs that don't use common conventions, such as
* `www.example.com/?jsonpCallback=doSomething`. It defaults to
* `callback`.
*/
callbackKey?: string;
/**
* The data to send with the request. This is automatically serialized
* to a querystring.
*/
data?: Object;
}
/**
* This represents the available options for configuring m.request for
* standard AJAX requests.
*
* @see m.request
*/
interface XHROptions extends RequestOptions {
/**
* This represents the HTTP method used, defaulting to "GET".
*/
method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS";
/**
* The username for HTTP authentication.
*/
user?: string;
/**
* The password for HTTP authentication.
*/
password?: string;
/**
* An optional function to run between `open` and `send`, useful for
* adding request headers or using XHR2 features such as the `upload`
* property. It is even possible to override the XHR altogether with a
* similar object, such as an XDomainRequest instance.
*
* @param xhr The associated XMLHttpRequest.
* @param options The options passed to this request.
* @return The new XMLHttpRequest, or nothing if the same one is kept.
*/
config?(xhr: XMLHttpRequest, options: this): any;
/**
* The data to send with the request.
*/
data?: Object;
}
}
declare var Mithril: _mithril.MithrilStatic;
declare var m: _mithril.MithrilStatic;
declare const m: Mithril.Static;
declare module "mithril" {
export = m;
+116 -45
View File
@@ -164,8 +164,8 @@ declare module "mongodb" {
// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser
addUser(username: string, password: string, callback: MongoCallback<any>): void;
addUser(username: string, password: string, options?: { w?: number | string, wtimeout?: number, j?: boolean, customData?: Object, roles?: Object[] }): Promise<any>;
addUser(username: string, password: string, options: { w?: number | string, wtimeout?: number, j?: boolean, customData?: Object, roles?: Object[] }, callback: MongoCallback<any>): void;
addUser(username: string, password: string, options?: DbAddUserOptions): Promise<any>;
addUser(username: string, password: string, options: DbAddUserOptions, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#admin
admin(): Admin;
// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#authenticate
@@ -184,7 +184,7 @@ declare module "mongodb" {
collections(): Promise<Collection[]>;
collections(callback: MongoCallback<Collection[]>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#command
command(command: Object, callback?: MongoCallback<any>): void;
command(command: Object, callback: MongoCallback<any>): void;
command(command: Object, options?: { readPreference: ReadPreference | string }): Promise<any>;
command(command: Object, options: { readPreference: ReadPreference | string }, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection
@@ -199,8 +199,8 @@ declare module "mongodb" {
db(dbName: string): Db;
db(dbName: string, options: { noListener?: boolean, returnNonCachedInstance?: boolean }): Db;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropCollection
dropCollection(name: string): Promise<any>;
dropCollection(name: string, callback: MongoCallback<any>): void;
dropCollection(name: string): Promise<boolean>;
dropCollection(name: string, callback: MongoCallback<boolean>): void;
// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropDatabase
dropDatabase(): Promise<any>;
dropDatabase(callback: MongoCallback<any>): void;
@@ -219,7 +219,7 @@ declare module "mongodb" {
indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise<any>;
indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#listCollections
listCollections(filter: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor;
listCollections(filter: { name?: string }, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#logout
logout(callback: MongoCallback<any>): void;
logout(options?: { dbName?: string }): Promise<any>;
@@ -231,7 +231,7 @@ declare module "mongodb" {
removeUser(username: string, callback: MongoCallback<any>): void;
removeUser(username: string, options?: { w?: number | string, wtimeout?: number, j?: boolean }): Promise<any>;
removeUser(username: string, options: { w?: number | string, wtimeout?: number, j?: boolean }, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#renameCollection
// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#renameCollection
renameCollection(fromCollection: string, toCollection: string, callback: MongoCallback<Collection>): void;
renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise<Collection>;
renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback<Collection>): void;
@@ -241,6 +241,8 @@ declare module "mongodb" {
stats(options: { scale?: number }, callback: MongoCallback<any>): void;
}
// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html
export class Server extends EventEmitter {
constructor(host: string, port: number, options?: ServerOptions);
@@ -254,13 +256,22 @@ declare module "mongodb" {
connections(): Array<any>;
}
// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html
export class Mongos extends EventEmitter {
constructor(servers: Array<Server>, options?: MongosOptions);
connections(): Array<any>;
}
// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser
export interface DbAddUserOptions {
w?: string | number;
wtimeout?: number;
j?: boolean;
customData?: Object;
roles?: Object[];
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection
export interface CollectionCreateOptions {
@@ -333,42 +344,42 @@ declare module "mongodb" {
authenticate(username: string, password: string, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#buildInfo
buildInfo(): Promise<any>;
buildInfo(callback: MongoCallback<any>): void
buildInfo(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#command
command(command: Object, callback: MongoCallback<any>): void;
command(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise<any>;
command(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#listDatabases
listDatabases(): Promise<any>;
listDatabases(callback: MongoCallback<any>): void
listDatabases(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#logout
logout(): Promise<any>;
logout(callback: MongoCallback<any>): void
logout(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#ping
ping(): Promise<any>;
ping(callback: MongoCallback<any>): void
ping(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingInfo
profilingInfo(): Promise<any>;
profilingInfo(callback: MongoCallback<any>): void
profilingInfo(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingLevel
profilingLevel(): Promise<any>;
profilingLevel(callback: MongoCallback<any>): void
profilingLevel(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser
removeUser(username: string, callback: MongoCallback<any>): void;
removeUser(username: string, options?: FSyncOptions): Promise<any>;
removeUser(username: string, options: FSyncOptions, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#replSetGetStatus
replSetGetStatus(): Promise<any>;
replSetGetStatus(callback: MongoCallback<any>): void
replSetGetStatus(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverInfo
serverInfo(): Promise<any>;
serverInfo(callback: MongoCallback<any>): void
serverInfo(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverStatus
serverStatus(): Promise<any>;
serverStatus(callback: MongoCallback<any>): void
serverStatus(callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#setProfilingLevel
setProfilingLevel(level: string): Promise<any>;
setProfilingLevel(level: string, callback: MongoCallback<any>): void
setProfilingLevel(level: string, callback: MongoCallback<any>): void;
// http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#validateCollection
validateCollection(collectionNme: string, callback: MongoCallback<any>): void;
validateCollection(collectionNme: string, options?: Object): Promise<any>;
@@ -564,12 +575,12 @@ declare module "mongodb" {
// Get current index hint for collection.
hint: any;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate
aggregate(pipeline: Object[], callback: MongoCallback<any>): void | AggregationCursor;
aggregate(pipeline: Object[], options: CollectionAggrigationOptions, callback: MongoCallback<any>): void | AggregationCursor;
aggregate(pipeline: Object[], callback: MongoCallback<any>): AggregationCursor;
aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback<any>): AggregationCursor;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite
bulkWrite(operations: Object[], callback: MongoCallback<BulkWriteOpResultObject>): void
bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise<BulkWriteOpResultObject>
bulkWrite(operations: Object[], options: CollectionBluckWriteOptions, callback: MongoCallback<BulkWriteOpResultObject>): void
bulkWrite(operations: Object[], callback: MongoCallback<BulkWriteOpResultObject>): void;
bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise<BulkWriteOpResultObject>;
bulkWrite(operations: Object[], options: CollectionBluckWriteOptions, callback: MongoCallback<BulkWriteOpResultObject>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#count
count(query: Object, callback: MongoCallback<number>): void;
count(query: Object, options?: MongoCountPreferences): Promise<number>;
@@ -590,9 +601,9 @@ declare module "mongodb" {
deleteOne(filter: Object, options?: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }): Promise<DeleteWriteOpResultObject>;
deleteOne(filter: Object, options: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }, callback: MongoCallback<DeleteWriteOpResultObject>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#distinct
distinct(key: string, query: Object, callback: MongoCallback<any>): void
distinct(key: string, query: Object, callback: MongoCallback<any>): void;
distinct(key: string, query: Object, options?: { readPreference?: ReadPreference | string }): Promise<any>;
distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string }, callback: MongoCallback<any>): void
distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string }, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#drop
drop(): Promise<any>;
drop(callback: MongoCallback<any>): void;
@@ -604,7 +615,16 @@ declare module "mongodb" {
dropIndexes(): Promise<any>;
dropIndexes(callback?: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find
find(query: Object): Cursor;
find(query?: Object): Cursor;
/** @deprecated */
find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne
/** @deprecated use find().limit(1).next(function(err, doc){}) */
findOne(filter: Object, callback: MongoCallback<any>): void;
/** @deprecated use find().limit(1).next(function(err, doc){}) */
findOne(filter: Object, options?: FindOneOptions): Promise<any>;
/** @deprecated use find().limit(1).next(function(err, doc){}) */
findOne(filter: Object, options: FindOneOptions, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete
findOneAndDelete(filter: Object, callback: MongoCallback<FindAndModifyWriteOpResultObject>): void;
findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise<FindAndModifyWriteOpResultObject>;
@@ -640,17 +660,24 @@ declare module "mongodb" {
indexInformation(options?: { full: boolean }): Promise<any>;
indexInformation(options: { full: boolean }, callback: MongoCallback<any>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp
initializeOrderedBulkOp(options: CollectionOptions): OrderedBulkOperation;
initializeOrderedBulkOp(options?: CollectionOptions): OrderedBulkOperation;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp
initializeUnorderedBulkOp(options: CollectionOptions): UnorderedBulkOperation;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany
insertMany(docs: Object[], callback: MongoCallback<InsertWriteOpResult>): void
insertMany(docs: Object[], options?: CollectionInsertManyOptions): Promise<InsertWriteOpResult>;
insertMany(docs: Object[], options: CollectionInsertManyOptions, callback: MongoCallback<InsertWriteOpResult>): void
initializeUnorderedBulkOp(options?: CollectionOptions): UnorderedBulkOperation;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne
insertOne(docs: Object, callback: MongoCallback<InsertOneWriteOpResult>): void
/** @deprecated Use insertOne, insertMany or bulkWrite */
insert(docs: Object, callback: MongoCallback<InsertOneWriteOpResult>): void;
/** @deprecated Use insertOne, insertMany or bulkWrite */
insert(docs: Object, options?: CollectionInsertOneOptions): Promise<InsertOneWriteOpResult>;
/** @deprecated Use insertOne, insertMany or bulkWrite */
insert(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback<InsertOneWriteOpResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany
insertMany(docs: Object[], callback: MongoCallback<InsertWriteOpResult>): void;
insertMany(docs: Object[], options?: CollectionInsertManyOptions): Promise<InsertWriteOpResult>;
insertMany(docs: Object[], options: CollectionInsertManyOptions, callback: MongoCallback<InsertWriteOpResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne
insertOne(docs: Object, callback: MongoCallback<InsertOneWriteOpResult>): void;
insertOne(docs: Object, options?: CollectionInsertOneOptions): Promise<InsertOneWriteOpResult>;
insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback<InsertOneWriteOpResult>): void
insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback<InsertOneWriteOpResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#isCapped
isCapped(): Promise<any>;
isCapped(callback: MongoCallback<any>): void;
@@ -678,10 +705,22 @@ declare module "mongodb" {
replaceOne(filter: Object, doc: Object, callback: MongoCallback<UpdateWriteOpResult>): void;
replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise<UpdateWriteOpResult>;
replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback<UpdateWriteOpResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#save
/** @deprecated Use insertOne, insertMany, updateOne or updateMany */
save(doc: Object, callback: MongoCallback<WriteOpResult>): void;
save(doc: Object, options?: CollectionOptions): Promise<WriteOpResult>;
save(doc: Object, options: CollectionOptions, callback: MongoCallback<WriteOpResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#stats
stats(callback: MongoCallback<CollStats>): void;
stats(options?: { scale: number }): Promise<CollStats>;
stats(options: { scale: number }, callback: MongoCallback<CollStats>): void;
// http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#update
/** @deprecated use updateOne, updateMany or bulkWrite */
update(filter: Object, update: Object, callback: MongoCallback<WriteOpResult>): void;
/** @deprecated use updateOne, updateMany or bulkWrite */
update(filter: Object, update: Object, options?: ReplaceOneOptions & { multi?: boolean }): Promise<WriteOpResult>;
/** @deprecated use updateOne, updateMany or bulkWrite */
update(filter: Object, update: Object, options: ReplaceOneOptions & { multi?: boolean }, callback: MongoCallback<WriteOpResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateMany
updateMany(filter: Object, update: Object, callback: MongoCallback<UpdateWriteOpResult>): void;
updateMany(filter: Object, update: Object, options?: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean; }): Promise<UpdateWriteOpResult>;
@@ -693,6 +732,7 @@ declare module "mongodb" {
}
// Documentation: http://docs.mongodb.org/manual/reference/command/collStats/
//TODO complete this
export interface CollStats {
// Namespace.
ns: string;
@@ -724,10 +764,11 @@ declare module "mongodb" {
maxSize: boolean;
wiredTiger: any;
indexDetails: any;
ok: number;
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate
export interface CollectionAggrigationOptions {
export interface CollectionAggregationOptions {
readPreference?: ReadPreference | string;
// Return the query as cursor, on 2.6 > it returns as a real cursor
// on pre 2.6 it returns as an emulated cursor.
@@ -875,7 +916,7 @@ declare module "mongodb" {
length: number;
//http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute
execute(callback: MongoCallback<BulkWriteResult>): void;
execute(options: FSyncOptions): Promise<BulkWriteResult>;
execute(options?: FSyncOptions): Promise<BulkWriteResult>;
execute(options: FSyncOptions, callback: MongoCallback<BulkWriteResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find
find(selector: Object): FindOperatorsOrdered;
@@ -885,7 +926,7 @@ declare module "mongodb" {
//http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html
export interface BulkWriteResult {
ok: boolean;
ok: number;
nInserted: number;
nUpdated: number;
nUpserted: number;
@@ -936,7 +977,7 @@ declare module "mongodb" {
export interface UnorderedBulkOperation {
//http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute
execute(callback: MongoCallback<BulkWriteResult>): void;
execute(options: FSyncOptions): Promise<BulkWriteResult>;
execute(options?: FSyncOptions): Promise<BulkWriteResult>;
execute(options: FSyncOptions, callback: MongoCallback<BulkWriteResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find
find(selector: Object): FindOperatorsUnordered;
@@ -955,6 +996,30 @@ declare module "mongodb" {
upsert(): FindOperatorsUnordered;
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne
export interface FindOneOptions {
limit?: number,
sort?: Array<any> | Object,
fields?: Object,
skip?: number,
hint?: Object,
explain?: boolean,
snapshot?: boolean,
timeout?: boolean,
tailable?: boolean,
batchSize?: number,
returnKey?: boolean,
maxScan?: number,
min?: number,
max?: number,
showDiskLoc?: boolean,
comment?: string,
raw?: boolean,
readPreference?: ReadPreference | string,
partial?: boolean,
maxTimeMs?: number
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~insertWriteOpResult
export interface InsertWriteOpResult {
insertedCount: number;
@@ -1031,7 +1096,13 @@ declare module "mongodb" {
bypassDocumentValidation?: boolean
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~WriteOpResult
export interface WriteOpResult {
ops: Array<any>;
connection: any;
result: any;
}
//http://mongodb.github.io/node-mongodb-native/2.1/api/external-Readable.html
export interface Readable {
pause(): void;
@@ -1177,7 +1248,7 @@ declare module "mongodb" {
close(): Promise<AggregationCursorResult>;
close(callback: MongoCallback<AggregationCursorResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#each
each(callback: MongoCallback<AggregationCursorResult>): void
each(callback: MongoCallback<AggregationCursorResult>): void;
// http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#explain
explain(): Promise<AggregationCursorResult>;
explain(callback: MongoCallback<AggregationCursorResult>): void;
@@ -1219,8 +1290,8 @@ declare module "mongodb" {
// http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort
sort(document: Object): AggregationCursor;
// http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray
toArray(): Promise<Object[]>;
toArray(callback: MongoCallback<Object[]>): void;
toArray(): Promise<any[]>;
toArray(callback: MongoCallback<any[]>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe
unpipe(destination?: Writable): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift
@@ -1241,7 +1312,7 @@ declare module "mongodb" {
close(): Promise<AggregationCursorResult>;
close(callback: MongoCallback<AggregationCursorResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#each
each(callback: MongoCallback<AggregationCursorResult>): void
each(callback: MongoCallback<AggregationCursorResult>): void;
// http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#isClosed
isClosed(): boolean;
// http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#maxTimeMS
@@ -1264,8 +1335,8 @@ declare module "mongodb" {
// http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference
setReadPreference(readPreference: string | ReadPreference): CommandCursor;
// http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray
toArray(): Promise<Object[]>;
toArray(callback: MongoCallback<Object[]>): void;
toArray(): Promise<any[]>;
toArray(callback: MongoCallback<any[]>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe
unpipe(destination?: Writable): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift
+5
View File
@@ -25,6 +25,11 @@ Mousetrap.bindGlobal('up up down down left right left right b a enter', function
console.log('konami code');
});
// Test that union types are accepted.
const unionTypeKeys: string | string[] = ['a', 'b', 'c'];
Mousetrap.bindGlobal(unionTypeKeys, function() { console.log('Union type test') });
Mousetrap.bindGlobal(['ctrl+s', 'meta+s'], (e, combo) => {
if (e.preventDefault) {
e.preventDefault();
+1 -2
View File
@@ -6,6 +6,5 @@
/// <reference path="./mousetrap.d.ts" />
interface MousetrapStatic {
bindGlobal(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
bindGlobal(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
bindGlobal(keyArray: string|string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
}
+4
View File
@@ -51,6 +51,10 @@ instance.bind('mod+s', function(){ console.log('Instance Saved'); });
// Test that the factory method works as well.
Mousetrap(element).bind('mod+s', function(){ console.log('Factory Saved'); });
// Test that union types are accepted.
const unionTypeKeys: string | string[] = ['a', 'b', 'c'];
Mousetrap(element).bind(unionTypeKeys, function() { console.log('Union type test') });
// Test that Mousetrap can be loaded as an external module.
// Assume that if the externally-loaded module can be assigned to a variable with the type of global Mousetrap,
// then everything is working correctly.
+4 -8
View File
@@ -11,20 +11,16 @@ interface MousetrapStatic {
(el: Element): MousetrapInstance;
new (el: Element): MousetrapInstance;
stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => boolean;
bind(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
bind(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
unbind(keys: string, action?: string): void;
unbind(keyArray: string[], action?: string): void;
bind(keys: string|string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
unbind(keys: string|string[], action?: string): void;
trigger(keys: string, action?: string): void;
reset(): void;
}
interface MousetrapInstance {
stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => boolean;
bind(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
bind(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
unbind(keys: string, action?: string): void;
unbind(keyArray: string[], action?: string): void;
bind(keys: string|string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
unbind(keys: string|string[], action?: string): void;
trigger(keys: string, action?: string): void;
reset(): void;
}
+29
View File
@@ -148,6 +148,35 @@ function bufferTests() {
var result1 = Buffer.concat([utf8Buffer, base64Buffer]);
var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999);
// Class Method: Buffer.from(array)
{
const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
}
// Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
{
const arr: Uint16Array = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
let buf: Buffer;
buf = Buffer.from(arr.buffer);
buf = Buffer.from(arr.buffer, 1);
buf = Buffer.from(arr.buffer, 0, 1);
}
// Class Method: Buffer.from(buffer)
{
const buf1: Buffer = Buffer.from('buffer');
const buf2: Buffer = Buffer.from(buf1);
}
// Class Method: Buffer.from(str[, encoding])
{
const buf1: Buffer = Buffer.from('this is a tést');
const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex');
}
// Test that TS 1.6 works with the 'as Buffer' annotation
// on isBuffer.
var a: Buffer | number;
+32 -1
View File
@@ -111,7 +111,7 @@ declare var Buffer: {
/**
* Produces a Buffer backed by the same allocated memory as
* the given {ArrayBuffer}.
*
*
*
* @param arrayBuffer The ArrayBuffer with which to share memory.
*/
@@ -129,6 +129,37 @@ declare var Buffer: {
*/
new (buffer: Buffer): Buffer;
prototype: Buffer;
/**
* Allocates a new Buffer using an {array} of octets.
*
* @param array
*/
from(array: any[]): Buffer;
/**
* When passed a reference to the .buffer property of a TypedArray instance,
* the newly created Buffer will share the same allocated memory as the TypedArray.
* The optional {byteOffset} and {length} arguments specify a memory range
* within the {arrayBuffer} that will be shared by the Buffer.
*
* @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
* @param byteOffset
* @param length
*/
from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer;
/**
* Copies the passed {buffer} data onto a new Buffer instance.
*
* @param buffer
*/
from(buffer: Buffer): Buffer;
/**
* Creates a new Buffer containing the given JavaScript string {str}.
* If provided, the {encoding} parameter identifies the character encoding.
* If not provided, {encoding} defaults to 'utf8'.
*
* @param str
*/
from(str: string, encoding?: string): Buffer;
/**
* Returns true if {obj} is a Buffer
*
+1 -1
View File
@@ -105,7 +105,7 @@ declare namespace Normalizr {
*/
mergeIntoEntity?: (stored: any, normalized: any, entityKey: string) => any;
}): {
entites: any;
entities: any;
result: any;
};
}
@@ -9,13 +9,38 @@ function test() {
sound: true,
vibrate: true,
clearNotifications: false,
forceShow: true
forceShow: true,
topics: ['foo', 'bar']
},
ios: {
badge: true,
sound: true,
alert: true,
clearBadge: true
clearBadge: true,
senderID: '123456789',
gcmSandbox: true,
categories: {
"invite": {
yes: {
callback: "app.accept", title: "Accept", foreground: true, destructive: false
},
no: {
callback: "app.reject", title: "Reject", foreground: true, destructive: false
},
maybe: {
callback: "app.maybe", title: "Maybe", foreground: true, destructive: false
}
},
"delete": {
yes: {
callback: "app.doDelete", title: "Delete", foreground: true, destructive: true
},
no: {
callback: "app.cancel", title: "Cancel", foreground: true, destructive: false
}
}
},
topics: ['foo', 'bar']
},
windows: {}
};
@@ -39,7 +64,7 @@ function test() {
console.log('did unregister');
}, () => {
console.log('did not unregister');
});
}, ['foo','bar']);
/*from init*/
push = PushNotification.init(options);
@@ -59,12 +84,13 @@ function test() {
/*the rest of the additional fields are not 'canon'*/
console.log(data.additionalData);
console.log(data.additionalData.foreground);
console.log(data.additionalData.coldstart);
push.finish(() => {
console.log('did finish');
}, () => {
console.log('did not finish');
});
}, 'push-1');
};
let errorHandler = (e: Error) => {
+46 -2
View File
@@ -52,8 +52,9 @@ declare namespace PhonegapPluginPush {
* so you will need to re-register them if you want them to function again without an application reload.
* @param successHandler
* @param errorHandler
* @param topics
*/
unregister(successHandler: () => any, errorHandler?: () => any): void
unregister(successHandler: () => any, errorHandler?: () => any, topics?: string[]): void
/*TODO according to js source code, "errorHandler" is optional, but is "count" also optional? I can't read objetive-C code (can anyone at all? I wonder...)*/
/**
@@ -81,8 +82,9 @@ declare namespace PhonegapPluginPush {
* successHandler gets called when background push processing is successfully completed.
* @param successHandler
* @param errorHandler
* @param id
*/
finish(successHandler: () => any, errorHandler: () => any): void
finish(successHandler?: () => any, errorHandler?: () => any, id?: string): void
}
/**
@@ -122,6 +124,10 @@ declare namespace PhonegapPluginPush {
* If true will always show a notification, even when the app is on the foreground. Default is false.
*/
forceShow?: boolean
/**
* If the array contains one or more strings each string will be used to subscribe to a GcmPubSub topic.
*/
topics?: string[]
}
/**
@@ -156,6 +162,23 @@ declare namespace PhonegapPluginPush {
* If true|"true" the badge will be cleared on app startup. Default is false|"false".
*/
clearBadge?: boolean | string
/**
* The data required in order to enable Action Buttons for iOS.
* Action Buttons on iOS - https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#action-buttons-1
*/
categories?: CategoryArray
/**
* Maps to the project number in the Google Developer Console. Setting this uses GCM for notifications instead of native
*/
senderID?: string
/**
* Whether to use prod or sandbox GCM setting. Defaults to false.
*/
gcmSandbox?: boolean
/**
* If the array contains one or more strings each string will be used to subscribe to a GcmPubSub topic. Note: only usable in conjunction with senderID
*/
topics?: string[]
}
/**
@@ -166,6 +189,23 @@ declare namespace PhonegapPluginPush {
}
}
interface CategoryArray {
[name: string]: CategoryAction
}
interface CategoryAction {
yes?: CategoryActionData
no?: CategoryActionData
maybe?: CategoryActionData
}
interface CategoryActionData {
callback: string
title: string
foreground: boolean
destructive: boolean
}
interface RegistrationEventResponse {
/**
* The registration ID provided by the 3rd party remote push service.
@@ -216,6 +256,10 @@ declare namespace PhonegapPluginPush {
* Whether the notification was received while the app was in the foreground
*/
foreground?: boolean
/**
* Will be true if the application is started by clicking on the push notification, false if the app is already started. (Android/iOS only)
*/
coldstart?: boolean
collapse_key?: string
from?: string
notId?: string
+11
View File
@@ -71,3 +71,14 @@ new Pikaday({field: $('#datepicker')[0]});
yearRange: [2000, 2020]
});
})();
(() => {
new Pikaday(
{
field: document.getElementById('datepicker'),
firstDay: 1,
minDate: new Date('2000-01-01'),
maxDate: new Date('2020-12-31'),
showDaysInNextAndPreviousMonths: true
});
})();
+5
View File
@@ -241,6 +241,11 @@ declare namespace Pikaday {
* Render the month after the year in the title. Default: false.
*/
showMonthAfterYear?: boolean;
/**
* Render days of the calendar grid that fall in the next or previous months to the current month instead of rendering an empty table cell. Default: false.
*/
showDaysInNextAndPreviousMonths?: boolean;
/**
* Number of visible calendars.
+2 -14
View File
@@ -1,4 +1,4 @@
// Type definitions for Postal v1.0.6
// Type definitions for Postal v1.0.8
// Project: https://github.com/postaljs/postal.js
// Definitions by: Lokesh Peta <https://github.com/lokeshpeta/>, Paul Jolly <https://github.com/myitcv>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -61,19 +61,9 @@ interface IChannelDefinition<T> {
channel: string;
}
interface ISourceArg {
topic: string;
channel?: string;
}
interface IDestinationArg {
topic: string | ((topic: string) => string);
channel?: string;
}
interface IPostal {
subscriptions: {};
wiretaps: ICallback<any>[];
wireTaps: ICallback<any>[];
addWireTap(callback: ICallback<any>): () => void;
@@ -83,8 +73,6 @@ interface IPostal {
getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition<any>[];
getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition<any>) => boolean): ISubscriptionDefinition<any>[];
linkChannels(source: ISourceArg | ISourceArg[], destination: IDestinationArg | IDestinationArg[]): void;
publish(envelope: IEnvelope<any>): void;
reset(): void;
+2
View File
@@ -207,11 +207,13 @@ interface PouchApi {
interface PouchOptions {
name?: string;
adapter?: string;
skip_setup?: boolean;
}
interface PouchDB extends PouchApi {
new (name: string, opts: PouchOptions, callback: (err: PouchError, res: PouchDB) => void): PouchDB;
new (name: string, callback: (err: PouchError, res: PouchDB) => void): PouchDB;
new (name: string, opts: PouchOptions): PouchDB;
new (name: string): PouchDB;
destroy(name: string, callback: (err: PouchError) => void): void;
}
@@ -0,0 +1,95 @@
///<reference path="../react-native/react-native.d.ts" />
import * as React from 'react-native'
import {
Animated,
View,
} from 'react-native';
function TestAnimatedAPI() {
// Value
const v1 = new Animated.Value(0);
const v2 = new Animated.Value(0);
v1.setValue(0.1);
v1.addListener(e => {
let n: number = e.value;
});
const v200 = v1.interpolate({
inputRange: [0, 1],
outputRange: [0, 200],
});
// ValueXY
const position = new Animated.ValueXY({ x: 0, y: 0 });
// Animation functions
const spring1 = Animated.spring(v1, {
toValue: 0.5,
tension: 10,
});
const springXY = Animated.spring(position, {
toValue: {
x: 1,
y: 2,
}
});
spring1.start();
spring1.stop();
Animated.parallel([
Animated.spring(v1, { toValue: 1 }),
Animated.spring(v2, { toValue: 1 }),
], {
stopTogether: true,
});
Animated.decay(v1, {
velocity: 2,
});
Animated.timing(v1, {
toValue: 1,
duration: 100,
delay: 100,
easing: v => v,
});
Animated.add(v1, v2);
Animated.multiply(v1, v2);
Animated.modulo(v1, 2);
Animated.delay(100);
Animated.sequence([
spring1,
springXY,
]);
Animated.stagger(100, [
spring1,
springXY,
]);
return (
<View>
<Animated.View
style={[
position.getLayout(),
{
opacity: v1,
}]}>
</Animated.View>
<Animated.Image
style={position.getTranslateTransform()}
>
</Animated.Image>
</View>
);
}
+12 -1
View File
@@ -29,6 +29,7 @@ import {
AppStateIOS,
ViewPagerAndroid,
Dimensions,
BackAndroid,
} from 'react-native';
function testDimensions() {
@@ -47,6 +48,8 @@ function testDimensions() {
} = Dimensions.get("screen");
}
BackAndroid.addEventListener("hardwareBackPress", () => {
});
var styles = StyleSheet.create(
{
@@ -72,11 +75,19 @@ var styles = StyleSheet.create(
class Welcome extends React.Component<any,any> {
testNativeMethods() {
this.setNativeProps({});
const { rootView } = this.refs;
rootView.measure((x, y, width, height) => {
});
}
render() {
return (
<View style={styles.container}>
<View ref="rootView" style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native
</Text>
+423 -25
View File
@@ -22,7 +22,7 @@
import React = __React;
//react-native "extends" react
declare namespace __React {
declare module "react-native" {
/**
@@ -121,6 +121,109 @@ declare namespace __React {
// @see lib.es6.d.ts
export var Promise: PromiseConstructor;
module NativeMethodsMixin {
type MeasureOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
pageX: number,
pageY: number
) => void
type MeasureInWindowOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number
) => void
type MeasureLayoutOnSuccessCallback = (
left: number,
top: number,
width: number,
height: number
) => void
}
/**
* @see https://github.com/facebook/react-native/blob/master/Libraries/ReactIOS/NativeMethodsMixin.js
*/
export class Component<P, S> extends React.Component<P, S> {
/**
* Determines the location on screen, width, and height of the given view and
* returns the values via an async callback. If successful, the callback will
* be called with the following arguments:
*
* - x
* - y
* - width
* - height
* - pageX
* - pageY
*
* Note that these measurements are not available until after the rendering
* has been completed in native. If you need the measurements as soon as
* possible, consider using the [`onLayout`
* prop](docs/view.html#onlayout) instead.
*/
measure(callback: NativeMethodsMixin.MeasureOnSuccessCallback): void;
/**
* Determines the location of the given view in the window and returns the
* values via an async callback. If the React root view is embedded in
* another native view, this will give you the absolute coordinates. If
* successful, the callback will be called with the following
* arguments:
*
* - x
* - y
* - width
* - height
*
* Note that these measurements are not available until after the rendering
* has been completed in native.
*/
measureInWindow(callback: NativeMethodsMixin.MeasureInWindowOnSuccessCallback): void;
/**
* Like [`measure()`](#measure), but measures the view relative an ancestor,
* specified as `relativeToNativeNode`. This means that the returned x, y
* are relative to the origin x, y of the ancestor view.
*
* As always, to obtain a native node handle for a component, you can use
* `React.findNodeHandle(component)`.
*/
measureLayout(
relativeToNativeNode: number,
onSuccess: NativeMethodsMixin.MeasureLayoutOnSuccessCallback,
onFail: () => void /* currently unused */
): void;
/**
* This function sends props straight to native. They will not participate in
* future diff process - this means that if you do not include them in the
* next render, they will remain active (see [Direct
* Manipulation](docs/direct-manipulation.html)).
*/
setNativeProps(nativeProps: Object): void;
/**
* Requests focus for the given input or view. The exact behavior triggered
* will depend on the platform and type of view.
*/
focus(): void;
/**
* Removes focus from an input or view. This is the opposite of `focus()`.
*/
blur(): void;
refs: {
[key: string]: Component<any, any>
};
}
//TODO: BGR: Replace with ComponentClass ?
// node_modules/react-tools/src/classic/class/ReactClass.js
export interface ReactClass<D, P, S> {
@@ -219,7 +322,6 @@ declare namespace __React {
* //FIXME: need to find documentation on which compoenent is a native (i.e. non composite component)
*/
export interface NativeComponent {
setNativeProps: ( props: Object ) => void
}
/**
@@ -2080,7 +2182,7 @@ declare namespace __React {
}
export interface Route {
component?: ComponentClass<ViewProperties>
component?: React.ComponentClass<ViewProperties>
id?: string
title?: string
passProps?: Object;
@@ -2519,7 +2621,7 @@ declare namespace __React {
* @see https://facebook.github.io/react-native/docs/dimensions.html#content
*/
export interface Dimensions {
get( what: "window" | "screen" ): React.ScaledSize;
get( what: "window" | "screen" ): ScaledSize;
}
export interface InteractionManagerStatic {
@@ -3351,6 +3453,312 @@ declare namespace __React {
vibrate(): void
}
export module Animated {
// Most (all?) functions where AnimatedValue is used any subclass of Animated can be used as well.
type AnimatedValue = Animated;
type AnimatedValueXY = ValueXY;
type Base = Animated;
class Animated {
// Internal class, no public API.
}
class AnimatedWithChildren extends Animated {
// Internal class, no public API.
}
class AnimatedInterpolation extends AnimatedWithChildren {
interpolate(config: InterpolationConfigType): AnimatedInterpolation;
}
type ExtrapolateType = 'extend' | 'identity' | 'clamp';
type InterpolationConfigType = {
inputRange: number[];
outputRange: (number[] | string[]);
easing?: ((input: number) => number);
extrapolate?: ExtrapolateType;
extrapolateLeft?: ExtrapolateType;
extrapolateRight?: ExtrapolateType;
};
type ValueListenerCallback = (state: {value: number}) => void;
/**
* Standard value for driving animations. One `Animated.Value` can drive
* multiple properties in a synchronized fashion, but can only be driven by one
* mechanism at a time. Using a new mechanism (e.g. starting a new animation,
* or calling `setValue`) will stop any previous ones.
*/
export class Value extends AnimatedWithChildren {
constructor(value: number);
setValue(value: number): void;
/**
* Sets an offset that is applied on top of whatever value is set, whether via
* `setValue`, an animation, or `Animated.event`. Useful for compensating
* things like the start of a pan gesture.
*/
setOffset(offset: number): void;
/**
* Merges the offset value into the base value and resets the offset to zero.
* The final output of the value is unchanged.
*/
flattenOffset(): void;
/**
* Adds an asynchronous listener to the value so you can observe updates from
* animations. This is useful because there is no way to
* synchronously read the value because it might be driven natively.
*/
addListener(callback: ValueListenerCallback): string;
removeListener(id: string): void;
removeAllListeners(): void;
/**
* Stops any running animation or tracking. `callback` is invoked with the
* final value after stopping the animation, which is useful for updating
* state to match the animation position with layout.
*/
stopAnimation(callback?: (value: number) => void): void;
/**
* Interpolates the value before updating the property, e.g. mapping 0-1 to
* 0-10.
*/
interpolate(config: InterpolationConfigType): AnimatedInterpolation;
}
type ValueXYListenerCallback = (value: {x: number; y: number}) => void;
/**
* 2D Value for driving 2D animations, such as pan gestures. Almost identical
* API to normal `Animated.Value`, but multiplexed. Contains two regular
* `Animated.Value`s under the hood.
*/
export class ValueXY extends AnimatedWithChildren {
x: AnimatedValue;
y: AnimatedValue;
constructor(valueIn?: {x: number | AnimatedValue; y: number | AnimatedValue});
setValue(value: {x: number; y: number}): void;
setOffset(offset: {x: number; y: number}): void;
flattenOffset(): void
stopAnimation(callback?: () => number): void;
addListener(callback: ValueXYListenerCallback): string;
removeListener(id: string): void;
/**
* Converts `{x, y}` into `{left, top}` for use in style, e.g.
*
*```javascript
* style={this.state.anim.getLayout()}
*```
*/
getLayout(): { left: AnimatedValue, top: AnimatedValue };
/**
* Converts `{x, y}` into a useable translation transform, e.g.
*
*```javascript
* style={{
* transform: this.state.anim.getTranslateTransform()
* }}
*```
*/
getTranslateTransform(): {[key: string]: AnimatedValue}[];
}
type EndResult = {finished: boolean};
type EndCallback = (result: EndResult) => void;
interface CompositeAnimation {
start: (callback?: EndCallback) => void;
stop: () => void;
}
interface AnimationConfig {
isInteraction?: boolean;
useNativeDriver?: boolean;
}
/**
* Animates a value from an initial velocity to zero based on a decay
* coefficient.
*/
export function decay(
value: AnimatedValue | AnimatedValueXY,
config: DecayAnimationConfig
): CompositeAnimation;
interface DecayAnimationConfig extends AnimationConfig {
velocity: number | {x: number, y: number};
deceleration?: number;
}
/**
* Animates a value along a timed easing curve. The `Easing` module has tons
* of pre-defined curves, or you can use your own function.
*/
export var timing: (
value: AnimatedValue | AnimatedValueXY,
config: TimingAnimationConfig
) => CompositeAnimation;
interface TimingAnimationConfig extends AnimationConfig {
toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY;
easing?: (value: number) => number;
duration?: number;
delay?: number;
}
interface SpringAnimationConfig extends AnimationConfig {
toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY;
overshootClamping?: boolean;
restDisplacementThreshold?: number;
restSpeedThreshold?: number;
velocity?: number | {x: number, y: number};
bounciness?: number;
speed?: number;
tension?: number;
friction?: number;
}
/**
* Creates a new Animated value composed from two Animated values added
* together.
*/
export function add(
a: Animated,
b: Animated
): AnimatedAddition;
class AnimatedAddition extends AnimatedInterpolation {}
/**
* Creates a new Animated value composed from two Animated values multiplied
* together.
*/
export function multiply(
a: Animated,
b: Animated
): AnimatedMultiplication;
class AnimatedMultiplication extends AnimatedInterpolation {}
/**
* Creates a new Animated value that is the (non-negative) modulo of the
* provided Animated value
*/
export function modulo(
a: Animated,
modulus: number
): AnimatedModulo;
class AnimatedModulo extends AnimatedInterpolation {}
/**
* Starts an animation after the given delay.
*/
export function delay(time: number): CompositeAnimation;
/**
* Starts an array of animations in order, waiting for each to complete
* before starting the next. If the current running animation is stopped, no
* following animations will be started.
*/
export function sequence(
animations: Array<CompositeAnimation>
): CompositeAnimation;
/**
* Array of animations may run in parallel (overlap), but are started in
* sequence with successive delays. Nice for doing trailing effects.
*/
export function stagger(
time: number,
animations: Array<CompositeAnimation>
): CompositeAnimation
/**
* Spring animation based on Rebound and Origami. Tracks velocity state to
* create fluid motions as the `toValue` updates, and can be chained together.
*/
export var spring: (
value: AnimatedValue | AnimatedValueXY,
config: SpringAnimationConfig
) => CompositeAnimation;
type ParallelConfig = {
stopTogether?: boolean; // If one is stopped, stop all. default: true
}
/**
* Starts an array of animations all at the same time. By default, if one
* of the animations is stopped, they will all be stopped. You can override
* this with the `stopTogether` flag.
*/
var parallel: (
animations: Array<CompositeAnimation>,
config?: ParallelConfig
) => CompositeAnimation;
type Mapping = {[key: string]: Mapping} | AnimatedValue;
interface EventConfig {
listener?: Function
}
/**
* Takes an array of mappings and extracts values from each arg accordingly,
* then calls `setValue` on the mapped outputs. e.g.
*
*```javascript
* onScroll={Animated.event(
* [{nativeEvent: {contentOffset: {x: this._scrollX}}}]
* {listener}, // Optional async listener
* )
* ...
* onPanResponderMove: Animated.event([
* null, // raw event arg ignored
* {dx: this._panX}, // gestureState arg
* ]),
*```
*/
var event: (
argMapping: Mapping[],
config?: EventConfig
) => (...args: any[]) => void;
/**
* Animated variants of the basic native views. Accepts Animated.Value for
* props and style.
*/
export var View: any;
export var Image: any;
export var Text: any;
}
export namespace BackAndroid {
type EVENT_NAME = "hardwareBackPress";
export function exitApp(): void;
export function addEventListener(event: EVENT_NAME, fn: Function): void;
export function removeEventListener(event: EVENT_NAME, fn: Function): void;
}
//////////////////////////////////////////////////////////////////////////
//
// R E - E X P O R T S
@@ -3489,19 +3897,6 @@ declare namespace __React {
export function __spread( target: any, ...sources: any[] ): any;
export interface GlobalStatic {
/**
* Accepts a function as its only argument and calls that function before the next repaint.
* It is an essential building block for animations that underlies all of the JavaScript-based animation APIs.
* In general, you shouldn't need to call this yourself - the animation API's will manage frame updates for you.
* @see https://facebook.github.io/react-native/docs/animations.html#requestanimationframe
*/
requestAnimationFrame( fn: () => void ) : void;
}
//
// Add-Ons
//
@@ -3518,16 +3913,19 @@ declare namespace __React {
export var TestModule: TestModuleStatic
export type TestModule = TestModuleStatic
}
}
declare module "react-native" {
import ReactNative = __React
export = ReactNative
declare interface ReactNativeGlobalStatic {
/**
* Accepts a function as its only argument and calls that function before the next repaint.
* It is an essential building block for animations that underlies all of the JavaScript-based animation APIs.
* In general, you shouldn't need to call this yourself - the animation API's will manage frame updates for you.
* @see https://facebook.github.io/react-native/docs/animations.html#requestanimationframe
*/
requestAnimationFrame( fn: () => void ) : void;
}
declare var global: __React.GlobalStatic
declare function require( name: string ): any
declare var global: ReactNativeGlobalStatic;
declare function require( name: string ): any;
+6 -1
View File
@@ -80,7 +80,12 @@ declare module "react-redux" {
* Defaults to true.
* @default true
*/
pure: boolean;
pure?: boolean;
/**
* If true, stores a ref to the wrapped component instance and makes it available via
* getWrappedInstance() method. Defaults to false.
*/
withRef?: boolean;
}
export interface ProviderProps {
+1
View File
@@ -250,6 +250,7 @@ declare namespace ReactRouter {
location?: H.Location | string
parseQueryString?: ParseQueryString
stringifyQuery?: StringifyQuery
basename?: string
}
interface MatchState extends RouterState {
history: History
+4 -4
View File
@@ -5,16 +5,16 @@
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as Select from "react-select";
import Select, { Option } from "react-select";
class SelectTest extends React.Component<React.Props<{}>, {}> {
render() {
const options: ReactSelect.Option[] = [{ label: "Foo", value: "bar" }];
const options: Option[] = [{ label: "Foo", value: "bar" }];
const onChange = (value: any) => console.log(value);
const onOpen = () => { return; };
const onClose = () => { return; };
const optionRenderer = (option: ReactSelect.Option) => <span>{option.label}</span>
const optionRenderer = (option: Option) => <span>{option.label}</span>
return <div>
<Select
name="test-select"
@@ -46,7 +46,7 @@ class SelectAsyncTest extends React.Component<React.Props<{}>, {}> {
callback(null, options);
}, 500);
};
const options: ReactSelect.Option[] = [{ label: "Foo", value: "bar" }];
const options: Option[] = [{ label: "Foo", value: "bar" }];
const onChange = (value: any) => console.log(value);
return <div>
<Select.Async
+4 -1
View File
@@ -302,5 +302,8 @@ declare namespace ReactSelect {
declare module "react-select" {
const select: ReactSelect.ReactSelectClass;
export = select;
interface Option extends ReactSelect.Option {}
export default select;
export { Option };
}
@@ -0,0 +1,24 @@
/// <reference path="../react/react.d.ts" />
/// <reference path="./react-split-pane.d.ts"/>
import * as React from "react";
import * as SplitPane from "react-split-pane";
class SplitPaneTest extends React.Component<React.Props<{}>, {}> {
render() {
return (
<SplitPane
allowResize={true}
className="pane"
defaultSize={30}
maxSize={50}
minSize={20}
split="vertical"
>
<div />
<div />
</SplitPane>
);
}
}
+41
View File
@@ -0,0 +1,41 @@
// Type definitions for react-split-pane v0.1.38
// Project: https://github.com/tomkp/react-split-pane
// Definitions by: Roger Chen <https://github.com/rcchen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts"/>
declare namespace ReactSplitPane {
interface ReactSplitPaneProps {
allowResize?: boolean;
className?: string;
/**
* Either a number (in pixels) or string (percentage)
*/
defaultSize?: number | string;
/**
* Either a number (in pixels) or string (percentage)
*/
maxSize?: number | string;
/**
* Either a number (in pixels) or string (percentage)
*/
minSize?: number | string;
onChange?: Function;
onDragFinished?: Function;
onDragStarted?: Function;
primary?: string;
/**
* Either a number (in pixels) or string (percentage)
*/
size?: number | string;
split?: string;
}
interface ReactSplitPaneClass extends __React.ComponentClass<ReactSplitPaneProps> { }
}
declare module "react-split-pane" {
var split: ReactSplitPane.ReactSplitPaneClass;
export = split;
}
+17 -3
View File
@@ -6,7 +6,22 @@
/// <reference path="react.d.ts" />
declare namespace __React {
interface SyntheticEventData {
interface OptionalEventProperties {
bubbles?: boolean;
cancelable?: boolean;
currentTarget?: EventTarget;
defaultPrevented?: boolean;
eventPhase?: number;
isTrusted?: boolean;
nativeEvent?: Event;
preventDefault?(): void;
stopPropagation?(): void;
target?: EventTarget;
timeStamp?: Date;
type?: string;
}
interface SyntheticEventData extends OptionalEventProperties {
altKey?: boolean;
button?: number;
buttons?: number;
@@ -41,8 +56,7 @@ declare namespace __React {
}
interface EventSimulator {
(element: Element, eventData?: SyntheticEventData): void;
(component: Component<any, any>, eventData?: SyntheticEventData): void;
(element: Element | Component<any, any>, eventData?: SyntheticEventData): void;
}
interface MockedComponentClass {
+2 -1
View File
@@ -418,9 +418,10 @@ React.createClass({
// TestUtils addon
// --------------------------------------------------------------------------
var node: Element;
React.addons.TestUtils.Simulate.click(node);
React.addons.TestUtils.Simulate.change(node);
React.addons.TestUtils.Simulate.keyDown(node, { key: "Enter" });
React.addons.TestUtils.Simulate.keyDown(node, { key: "Enter", cancelable: false });
var renderer: React.ShallowRenderer =
React.addons.TestUtils.createRenderer();
+1 -1
View File
@@ -553,7 +553,7 @@ var node: Element = TestUtils.renderIntoDocument(React.DOM.div());
TestUtils.Simulate.click(node);
TestUtils.Simulate.change(node);
TestUtils.Simulate.keyDown(node, { key: "Enter" });
TestUtils.Simulate.keyDown(node, { key: "Enter", cancelable: false });
var renderer: React.ShallowRenderer =
TestUtils.createRenderer();
+20
View File
@@ -0,0 +1,20 @@
/// <reference path="./redux-bootstrap.d.ts" />
import bootstrap from "redux-bootstrap";
let routes: JSX.Element = null;
let result = bootstrap({
container: "root",
initialState: {},
middlewares: [],
reducers: {
reposReducer: (previousState: any, action: any) => { return null; },
usersReducer: (previousState: any, action: any) => { return null; }
},
routes: routes
});
console.log(result.store);
console.log(result.history);
console.log(result.root);
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for react-bootstrap v1.0.0
// Project: https://github.com/remojansen/redux-bootstrap
// Definitions by: Remo H. Jansen <https://github.com/remojansen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../redux/redux.d.ts" />
/// <reference path="../react/react.d.ts" />
/// <reference path="../react-router-redux/react-router-redux.d.ts" />
declare module "redux-bootstrap" {
interface BoostrapOptions {
routes: JSX.Element;
reducers: ReducersOption;
middlewares?: Redux.Middleware[];
initialState?: any;
container?: string;
}
interface BootstrapResult {
store: Redux.Store;
history: ReactRouterRedux.ReactRouterReduxHistory;
root: JSX.Element;
}
interface ReducersOption {
[index: string]: Redux.Reducer;
}
export default function bootstrap(options: BoostrapOptions): BootstrapResult;
}
+20 -14
View File
@@ -4,7 +4,7 @@ import restify = require("restify");
var server = restify.createServer({
formatters: {
'application/foo': function formatFoo(req, res, body) {
'application/foo': function formatFoo(req: restify.Request, res: restify.Response, body: any) {
if (body instanceof Error)
return body.stack;
@@ -37,7 +37,7 @@ server.use((req, res, next)=>{});
server.use([(req, res, next)=>{}]);
server.use((req, res, next)=>{}, (req, res, next)=>{});
function send(req, res, next) {
function send(req: restify.Request, res: restify.Response, next: restify.Next) {
req.header('key', 'val');
req.header('key') === 'val';
@@ -77,7 +77,7 @@ function send(req, res, next) {
res.code === 50;
res.contentLength === 50;
res.charSet === 'test';
res.charSet('test');
res.contentType === 'test';
res.headers;
res.id === 'test';
@@ -249,7 +249,15 @@ server.on('after', restify.auditLogger({
log: ()=>{}
}));
restify.defaultResponseHeaders = function(data) {
server.on('after', (req: restify.Request, res: restify.Response, route: restify.Route, err: any) => {
route.spec.method === 'GET';
route.spec.name === 'routeName';
route.spec.path === '/some/path';
route.spec.versions === ['v1'];
restify.auditLogger({ log: ()=>{} })(req, res, route, err);
});
restify.defaultResponseHeaders = function(data: any) {
this.header('Server', 'helloworld');
};
@@ -276,18 +284,16 @@ client = restify.createStringClient({
version: ""
});
client.get("test", send);
client.head('test', send);
client.post('path', {}, send);
client.put('path', {}, send);
client.del('path', send);
client.head('test', function(err: any, req: restify.Request, res: restify.Response) { });
client.put('path', {}, function(err: any, req: restify.Request, res: restify.Response, obj: any) { });
client.del('path', function(err: any, req: restify.Request, res: restify.Response) { });
client.post('/foo', { hello: 'world' }, function(err, req, res, obj) {
client.post('/foo', { hello: 'world' }, function(err: any, req: restify.Request, res: restify.Response, obj: any) {
console.log('%d -> %j', res.statusCode, res.headers);
console.log('%j', obj);
});
client.get('/foo/bar', function(err, req, res, data) {
client.get('/foo/bar', function(err: any, req: restify.Request, res: restify.Response, data: string) {
console.log('%s', data);
});
@@ -295,13 +301,13 @@ var client2 = restify.createClient({
url: 'http://127.0.0.1'
});
client2.get('/str/mcavage', function(err, req) {
client2.get('/str/mcavage', function(err: any, req: any) {
req.on('result', function(err, res) {
req.on('result', function(err: any, res: any) {
res.body = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
res.on('data', function(chunk: string) {
res.body += chunk;
});
+8 -1
View File
@@ -73,11 +73,18 @@ declare module "restify" {
id: string;
}
interface RouteSpec {
method: string;
name: string;
path: string;
versions: string[];
}
interface Route {
name: string;
method: string;
path: RoutePathRegex;
spec: Object;
spec: RouteSpec;
types: string[];
versions: string[];
}
+7 -7
View File
@@ -91,13 +91,13 @@ interface Select2JQueryEventObject extends JQueryEventObject {
}
interface Select2SelectionObject {
loading: boolean,
disabled: boolean,
element: HTMLOptionElement,
id: string,
selected: boolean,
text: string,
title: string,
loading: boolean;
disabled: boolean;
element: HTMLOptionElement;
id: string;
selected: boolean;
text: string;
title: string;
}
interface JQuery {
+2 -1
View File
@@ -11,6 +11,7 @@ app.use(serveStatic('/3', {
dotfiles: 'ignore',
etag: true,
extensions: ['html'],
fallthrough: true,
index: true,
lastModified: true,
maxAge: 0,
@@ -24,4 +25,4 @@ serveStatic.mime.define({
'application/babylon': ['babylon'],
'application/babylonmeshdata': ['babylonmeshdata'],
'application/fx': ['fx']
});
});
+7 -1
View File
@@ -44,7 +44,13 @@ declare module "serve-static" {
* The default value is false.
*/
extensions?: string[];
/**
* Let client errors fall-through as unhandled requests, otherwise forward a client error.
* The default value is false.
*/
fallthrough?: boolean;
/**
* By default this module will send "index.html" files in response to a request on a directory.
* To disable this set false or to supply a new index pass a string or an array in preferred order.
+5
View File
@@ -0,0 +1,5 @@
/// <reference path="./slackify-html.d.ts" />
import slackify = require("slackify-html");
var text = slackify('this <a href="http://github.com">link</a> is <b>important</b>');
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for slackify-html v1.0.1
// Project: https://github.com/mrq-cz/slackify-html
// Definitions by: Scott Rippee <https://github.com/hypexr>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "slackify-html" {
function slackify(html : string) : string;
export = slackify;
}
+6 -2
View File
@@ -1395,9 +1395,13 @@ declare namespace Slick {
export interface OnSortEventArgs<T extends SlickData> extends GridEventArgs<T> {
multiColumnSort: boolean;
sortCol?: SortColumn<T>;
sortCols?: SortColumn<T>[];
// Single column returned
sortCol?: Column<T>;
sortAsc: boolean;
// Multiple columns returned
sortCols?: SortColumn<T>[];
}
export interface OnScrollEventArgs<T extends SlickData> extends GridEventArgs<T> {
+22
View File
@@ -0,0 +1,22 @@
/// <reference path="survey-knockout.d.ts" />
function createFromCodeTests() {
var survey = new Survey.SurveyModel();
var page = survey.addNewPage("Page 1");
page.addNewQuestion("text", "question1");
page.addNewQuestion("comment", "question2");
page = survey.addNewPage("Page 2");
page.addNewQuestion("matrix", "question3");
page.addNewQuestion("matrixdropdown", "question4");
return survey;
}
function createFromJSONTests() {
var survey = new Survey.SurveyModel({
pages: [{
"name": "page1",
"questions": [{ "type": "text", "name": "textQuestion", "isRequired": "true" }, { "type": "checkbox", "name": "checkboxQuestion", "isRequired": "true", "choices": ["red", "white"] }]
}]
});
survey.setValue("textQuestion", "newValue");
return survey;
}
File diff suppressed because it is too large Load Diff
+8 -7
View File
@@ -2477,8 +2477,9 @@ declare namespace THREE {
export interface MeshStandardMaterialParameters extends MaterialParameters {
color?: number|string;
roughtness?: number;
roughness?: number;
metalness?: number;
map?: Texture;
lighhtMap?: Texture;
lightMapIntensity?: number;
aoMap?: Texture;
@@ -2493,7 +2494,7 @@ declare namespace THREE {
displacementMap?: Texture;
displacementScale?: number;
displacementBias?: number;
roughtnessMap?: Texture;
roughnessMap?: Texture;
metalMap?: Texture;
alphaMap?: Texture;
envMap?: Texture;
@@ -2514,7 +2515,7 @@ declare namespace THREE {
constructor(parameters?: MeshStandardMaterialParameters);
color: Color;
roughtness: number;
roughness: number;
metalness: number;
map: Texture;
lighhtMap: Texture;
@@ -2531,7 +2532,7 @@ declare namespace THREE {
displacementMap: Texture;
displacementScale: number;
displacementBias: number;
roughtnessMap: Texture;
roughnessMap: Texture;
metalMap: Texture;
alphaMap: Texture;
envMap: Texture;
@@ -5082,8 +5083,8 @@ declare namespace THREE {
points_vert: string;
premultiplied_alpha_fragment: string;
project_vertex: string;
roughtnessmap_fragment: string;
roughtnessmap_pars_fragment: string;
roughnessmap_fragment: string;
roughnessmap_pars_fragment: string;
shadowmap_pars_fragment: string;
shadowmap_pars_vertex: string;
shadowmap_vertex: string;
@@ -5167,7 +5168,7 @@ declare namespace THREE {
displacementScale: IUniform;
displacementBias: IUniform;
};
roughtnessmap: { roughtnessMap: IUniform };
roughnessmap: { roughnessMap: IUniform };
metalnessmap: { metalnessMap: IUniform };
fog: {
fogDensity: IUniform;
+6
View File
@@ -0,0 +1,6 @@
/// <reference path="./torrent-stream.d.ts" />
import * as torrentStream from "torrent-stream";
let engine: TorrentStream.TorrentEngine = torrentStream("magnet");
console.log(engine.swarm.downloaded)
+62
View File
@@ -0,0 +1,62 @@
// Type definitions for torrent-stream
// Project: https://npmjs.com/package/torrent-stream
// Definitions by: Xavier Stouder <https://github.com/xstoudi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare namespace TorrentStream {
interface TorrentEngine {
files: TorrentFile[];
destroy(callback: () => void): void;
connect(peer: string): void;
disconnect(peer: string): void;
block(peer: string): void;
remove(keepPieces: boolean, callback: () => void): void;
listen(port: number, callback: () => void): void;
swarm: Swarm;
// Events
on(event: "ready" | "torrent" | "idle", callback: Function): void;
on(event: "download", callback: (pieceIndex: number) => void): void;
on(event: "upload", callback: (pieceIndex: number, offset: number, length: number) => void): void;
on(event: string,callback: Function): void;
}
interface TorrentEngineOptions {
connections?: number; // Max amount of peers to be connected to.
uploads?: number; // Number of upload slots.
tmp?: string; // Root folder for the files storage. Default folder under /tmp/torrent-stream/{infoHash}.
path?: string; // Path where to save the files. Overrides 'tmp'.
verify?: boolean; // Verify previously stored data before starting.
dht?: boolean; // Whether or not to use DHT to initialize the swarm.
tracker?: boolean; // Whether or not to use trackers from torrent file or magnet link.
trackers?: string[]; // Allows to declare additional custom trackers to use.
storage?: any; // Use a custom storage backend rather than the default disk-backed one.
}
interface Swarm {
downloaded: number;
}
interface TorrentFile {
name: string;
path: string;
length: number;
select(): void;
deselect(): void;
createReadStream(options?: ReadStreamOptions): any;
}
interface ReadStreamOptions {
start: number;
end: number;
}
}
declare module "torrent-stream" {
function s(magnet: string | Buffer, options?: TorrentStream.TorrentEngineOptions): TorrentStream.TorrentEngine;
namespace s {
// Here
}
export = s;
}
+18 -18
View File
@@ -167,8 +167,8 @@ declare namespace Vex {
}
namespace Annotation {
const enum Justify {LEFT, CENTER, RIGHT, CENTER_STEM}
const enum VerticalJustify {TOP, CENTER, BOTTOM, CENTER_STEM}
const enum Justify {LEFT = 1, CENTER, RIGHT, CENTER_STEM}
const enum VerticalJustify {TOP = 1, CENTER, BOTTOM, CENTER_STEM}
const CATEGORY : string;
}
@@ -194,7 +194,7 @@ declare namespace Vex {
}
namespace Barline {
const enum type {SINGLE, DOUBLE, END, REPEAT_BEGIN, REPEAT_END, REPEAT_BOTH, NONE}
const enum type {SINGLE = 1, DOUBLE, END, REPEAT_BEGIN, REPEAT_END, REPEAT_BOTH, NONE}
}
class Barline extends StaveModifier {
@@ -365,7 +365,7 @@ declare namespace Vex {
}
namespace Curve {
const enum Position {NEAR_HEAD, NEAR_TOP}
const enum Position {NEAR_HEAD = 1, NEAR_TOP}
}
class Dot extends Modifier {
@@ -553,7 +553,7 @@ declare namespace Vex {
}
namespace Modifier {
const enum Position {LEFT, RIGHT, ABOVE, BELOW}
const enum Position {LEFT = 1, RIGHT, ABOVE, BELOW}
const CATEGORY : string
}
@@ -717,7 +717,7 @@ declare namespace Vex {
}
namespace PedalMarking {
const enum Styles {TEXT, BRACKET, MIXED}
const enum Styles {TEXT = 1, BRACKET, MIXED}
const GLYPHS : {[name : string] : {code : string, x_shift : number, y_shift : number}};
}
@@ -774,8 +774,8 @@ declare namespace Vex {
}
namespace Renderer {
const enum Backends {CANVAS, RAPHAEL, SVG, VML}
const enum LineEndType {NONE, UP, DOWN}
const enum Backends {CANVAS = 1, RAPHAEL, SVG, VML}
const enum LineEndType {NONE = 1, UP, DOWN}
}
class Repetition extends StaveModifier {
@@ -790,7 +790,7 @@ declare namespace Vex {
}
namespace Repetition {
const enum type { NONE, CODA_LEFT, CODA_RIGHT, SEGNO_LEFT, SEGNO_RIGHT, DC, DC_AL_CODA, DC_AL_FINE, DS, DS_AL_CODA, DS_AL_FINE, FINE }
const enum type { NONE = 1, CODA_LEFT, CODA_RIGHT, SEGNO_LEFT, SEGNO_RIGHT, DC, DC_AL_CODA, DC_AL_FINE, DS, DS_AL_CODA, DS_AL_FINE, FINE }
}
class Stave {
@@ -859,7 +859,7 @@ declare namespace Vex {
}
namespace StaveConnector {
const enum type { SINGLE_RIGHT, SINGLE_LEFT, SINGLE, DOUBLE, BRACE, BRACKET, BOLD_DOUBLE_LEFT, BOLD_DOUBLE_RIGHT, THIN_DOUBLE }
const enum type { SINGLE_RIGHT = 0, SINGLE_LEFT = 1, SINGLE = 1, DOUBLE = 2, BRACE = 3, BRACKET = 4, BOLD_DOUBLE_LEFT = 5, BOLD_DOUBLE_RIGHT = 6, THIN_DOUBLE = 7 }
}
class StaveHairpin {
@@ -874,7 +874,7 @@ declare namespace Vex {
}
namespace StaveHairpin {
const enum type { CRESC, DECRESC }
const enum type { CRESC = 1, DECRESC }
}
class StaveLine {
@@ -892,8 +892,8 @@ declare namespace Vex {
}
namespace StaveLine {
const enum TextVerticalPosition { TOP, BOTTOM }
const enum TextJustification { LEFT, CENTER, RIGHT }
const enum TextVerticalPosition { TOP = 1, BOTTOM }
const enum TextJustification { LEFT = 1, CENTER, RIGHT }
}
class StaveModifier {
@@ -1105,7 +1105,7 @@ declare namespace Vex {
}
namespace Stroke {
const enum Type {BRUSH_DOWN, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP}
const enum Type {BRUSH_DOWN = 1, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP}
const CATEGORY : string;
}
@@ -1212,7 +1212,7 @@ declare namespace Vex {
}
namespace TextBracket {
const enum Positions {TOP, BOTTOM}
const enum Positions {TOP = 1, BOTTOM = -1}
}
class TextDynamics extends Note {
@@ -1232,7 +1232,7 @@ declare namespace Vex {
}
namespace TextNote {
const enum Justification {LEFT, CENTER, RIGHT}
const enum Justification {LEFT = 1, CENTER, RIGHT}
const GLYPHS : {[name : string] : {code : string, point : number, x_shift : number, y_shift : number}}
}
@@ -1390,7 +1390,7 @@ declare namespace Vex {
}
namespace Voice {
const enum Mode {STRICT, SOFT, FULL}
const enum Mode {STRICT = 1, SOFT, FULL}
}
class VoiceGroup {
@@ -1407,7 +1407,7 @@ declare namespace Vex {
}
namespace Volta {
const enum type {NONE, BEGIN, MID, END, BEGIN_END}
const enum type {NONE = 1, BEGIN, MID, END, BEGIN_END}
}
}
}
+1
View File
@@ -21,6 +21,7 @@ declare var w2ui: W2UI.W2UI
declare namespace W2UI {
interface W2Event {
onComplete: () => void;
target: string;
}

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