Merge pull request #3 from borisyankov/master

Merge borisyankov/DefinitelyTyped into Asana/DefinitelyTyped
This commit is contained in:
Vincent Siao
2014-12-02 21:38:03 -08:00
267 changed files with 51343 additions and 2365 deletions
+2
View File
@@ -33,3 +33,5 @@ _infrastructure/tests/build
!rx.js
node_modules
.sublimets
+2
View File
@@ -2,5 +2,7 @@ language: node_js
node_js:
- "0.10"
sudo: false
notifications:
email: false
+680 -439
View File
File diff suppressed because it is too large Load Diff
+13
View File
@@ -0,0 +1,13 @@
/// <reference path="headroom.d.ts" />
new Headroom(document.getElementById('siteHead'));
new Headroom(document.getElementsByClassName('siteHead')[0]);
new Headroom(document.getElementsByClassName('siteHead')[0], {
tolerance: 34
});
new Headroom(document.getElementsByClassName('siteHead')[0], {
offset: 500
});
+28
View File
@@ -0,0 +1,28 @@
// Type definitions for headroom.js v0.7.0
// Project: http://wicky.nillia.ms/headroom.js/
// Definitions by: Jakub Olek <https://github.com/hakubo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface HeadroomOptions {
offset?: number;
tolerance?: any;
classes?: {
initial?: string;
pinned?: string;
unpinned?: string;
top?: string;
notTop?: string;
};
scroller?: Element;
onPin?: () => void;
onUnPin?: () => void;
onTop?: () => void;
onNotTop?: () => void;
}
declare class Headroom {
constructor(element: Node, options?: HeadroomOptions);
constructor(element: Element, options?: HeadroomOptions);
init: () => void;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
/// <reference path="adm-zip.d.ts" />
import AdmZip = require("adm-zip");
// reading archives
var zip = new AdmZip("./my_file.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function (zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.getData().toString('utf8'));
}
});
// outputs the content of some_folder/my_file.txt
console.log(zip.readAsText("some_folder/my_file.txt"));
// extracts the specified file to the specified location
zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*overwrite*/true)
// extracts everything
zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true);
// creating archives
var zip = new AdmZip();
// add file directly
zip.addFile("test.txt", new Buffer("inner content of the file"), "entry comment goes here");
// add local file
zip.addLocalFile("/home/me/some_picture.png");
// get everything as a buffer
var willSendthis = zip.toBuffer();
// or write everything to disk
zip.writeZip(/*target file name*/"/home/me/files.zip");
+300
View File
@@ -0,0 +1,300 @@
// Type definitions for adm-zip v0.4.4
// Project: https://github.com/cthackers/adm-zip
// Definitions by: John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module AdmZip {
class ZipFile {
/**
* Create a new, empty archive.
*/
constructor();
/**
* Read an existing archive.
*/
constructor(fileName: string);
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry String with the full path of the entry
* @return Buffer or Null in case of error
*/
readFile(entry: string): Buffer;
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry ZipEntry object
* @return Buffer or Null in case of error
*/
readFile(entry: IZipEntry): Buffer;
/**
* Asynchronous readFile
* @param entry String with the full path of the entry
* @param callback Called with a Buffer or Null in case of error
*/
readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void;
/**
* Asynchronous readFile
* @param entry ZipEntry object
* @param callback Called with a Buffer or Null in case of error
* @return Buffer or Null in case of error
*/
readFileAsync(entry: IZipEntry, callback: (data: Buffer, err: string) => any): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: string, encoding?: string): string;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry ZipEntry object
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: IZipEntry, encoding?: string): string;
/**
* Asynchronous readAsText
* @param entry String with the full path of the entry
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void;
/**
* Asynchronous readAsText
* @param entry ZipEntry object
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: IZipEntry, callback: (data: string) => any, encoding?: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry String with the full path of the entry
*/
deleteFile(entry: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry A ZipEntry object.
*/
deleteFile(entry: IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
* @param comment Content of the comment.
*/
addZipComment(comment: string): void;
/**
* Returns the zip comment
* @return The zip comment.
*/
getZipComment(): string;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry String with the full path of the entry
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: string, comment: string): void;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry ZipEntry object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry String with the full path of the entry.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: string): string;
/**
* Returns the comment of the specified entry
* @param entry ZipEntry object.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry String with the full path of the entry.
* @param content The entry's new contents.
*/
updateFile(entry: string, content: Buffer): void;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry ZipEntry object.
* @param content The entry's new contents.
*/
updateFile(entry: IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
* @param zipPath Path to a directory in the archive. Defaults to the empty
* string.
*/
addLocalFile(localPath: string, zipPath?: string): void;
/**
* Adds a local directory and all its nested files and directories to the
* archive.
* @param localPath Path to a folder on disk.
* @param zipPath Path to a folder in the archive. Defaults to an empty
* string.
*/
addLocalFolder(localPath: string, zipPath?: string): void;
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null
* buffer should be provided.
* @param entryName Entry path
* @param content Content to add to the entry; must be a 0-length buffer
* for a directory.
* @param comment Comment to add to the entry.
* @param attr Attribute to add to the entry.
*/
addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void;
/**
* Returns an array of ZipEntry objects representing the files and folders
* inside the archive
*/
getEntries(): IZipEntry[];
/**
* Returns a ZipEntry object representing the file or folder specified by
* ``name``.
* @param name Name of the file or folder to retrieve.
* @return ZipEntry The entry corresponding to the name.
*/
getEntry(name: string): IZipEntry;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry String with the full path of the entry
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*
* @return Boolean
*/
extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry ZipEntry object
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* @return Boolean
*/
extractEntryTo(entryPath: IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*/
extractAllTo(targetPath: string, overwrite?: boolean): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no ``targetFileName`` is provided, it will
* overwrite the opened zip
* @param targetFileName
*/
writeZip(targetPath?: string): void;
/**
* Returns the content of the entire zip file as a Buffer object
* @return Buffer
*/
toBuffer(): Buffer;
}
/**
* The ZipEntry is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
header: Buffer;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer) => void): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
}
}
declare module "adm-zip" {
import zipFile = AdmZip.ZipFile;
export = zipFile;
}
+7 -3
View File
@@ -17,7 +17,7 @@ myApp.config((
var concat: ng.ui.IUrlMatcher = matcher.concat('/test');
var str: string = matcher.format({ id:'bob', q:'yes' });
var arr: string[] = matcher.parameters();
$urlRouterProvider
.when('/test', '/list')
.when('/test', '/list')
@@ -34,7 +34,11 @@ myApp.config((
$stateProvider
.state('state1', {
url: "/state1",
templateUrl: "partials/state1.html"
templateUrl: "partials/state1.html",
params: {
param1: "defaultValue",
param2: undefined
}
})
.state('state1.list', {
url: "/list",
@@ -135,7 +139,7 @@ myApp.service("urlLocatorTest", UrlLocatorTestService);
module UiViewScrollProviderTests {
var app = angular.module("uiViewScrollProviderTests", ["ui.router"]);
app.config(['$uiViewScrollProvider', function($uiViewScrollProvider: ng.ui.IUiViewScrollProvider) {
// This prevents unwanted scrolling to the active nested state view.
// Use this when you have nested states, but you don't want the browser to scroll down the page
+3 -3
View File
@@ -17,7 +17,7 @@ declare module ng.ui {
controllerProvider?: any;
resolve?: {};
url?: string;
params?: any[];
params?: any;
views?: {};
abstract?: boolean;
onEnter?: any;
@@ -108,10 +108,10 @@ declare module ng.ui {
*/
sync(): void;
}
interface IUiViewScrollProvider {
/*
* Reverts back to using the core $anchorScroll service for scrolling
* Reverts back to using the core $anchorScroll service for scrolling
* based on the url anchor.
*/
useAnchorScroll(): void;
+152 -39
View File
@@ -3,53 +3,166 @@
var myapp = angular.module("myapp", ["firebase"]);
interface AngularFireScope extends ng.IScope {
items: AngularFire;
remoteItems: RemoteItems;
}
interface RemoteItems {
bar: string;
data: any;
}
var url = "https://myapp.firebaseio.com";
myapp.controller("MyController", ["$scope", "$firebase",
function($scope: AngularFireScope, $firebase: AngularFireService) {
$scope.items = $firebase(new Firebase(url));
$scope.items.$add({ foo: "bar" });
$scope.items.$remove("foo");
$scope.items.$remove();
$scope.items.$save();
var child = $scope.items.$child("foo");
child.$remove();
$scope.items.$set({ bar: "baz" });
var keys = $scope.items.$getIndex();
keys.forEach(function(key, i) {
console.log(i, (<any>$scope.items)[key]);
});
$scope.items.$on("loaded", function() {
console.log("Initial data received!");
});
$scope.items.$on("change", function() {
console.log("A remote change was applied locally!");
});
$scope.items.$off('loaded');
function stopSync() {
$scope.items.$off();
myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$FirebaseArray',
function ($scope: AngularFireScope, $firebase: AngularFireService, $FirebaseObject: AngularFireObjectService, $FirebaseArray: AngularFireArrayService) {
var ref = new Firebase(url);
var sync = $firebase(ref);
// AngularFire
{
sync.$asArray();
sync.$asObject();
sync.$ref();
sync.$remove();
sync.$push({ foo: "foo data" });
sync.$set("foo", 1);
sync.$set({ foo: 2 });
sync.$update({ foo: 3 });
sync.$update("foo", { bar: 1 });
// Increment the message count by 1
sync.$transaction('count', function (currentCount) {
if (!currentCount) return 1; // Initial value for counter.
if (currentCount < 0) return; // Return undefined to abort transaction.
return currentCount + 1; // Increment the count by 1.
}).then(function (snapshot) {
if (!snapshot) {
// Handle aborted transaction.
} else {
// Do something.
console.log(snapshot.val());
}
}, function (err) {
// Handle the error condition.
console.log(err.stack);
});
}
// AngularFireObject
{
var obj = sync.$asObject();
// $id
if (obj.$id !== ref.name()) throw "error";
// $loaded()
obj.$loaded().then((data) => {
if (data !== obj) throw "error";
// $priority
obj.$priority;
// $value, $save()
obj.$value = "foobar";
obj.$save();
});
// $inst()
if (obj.$inst() !== sync) throw "error";
// $bindTo()
obj.$bindTo($scope, "data").then(function () {
console.log($scope.data);
$scope.data.foo = "baz"; // will be saved to Firebase
sync.$set({ foo: "baz" }); // this would update Firebase and $scope.data
});
// $watch()
var unwatch = obj.$watch(function () {
console.log("data changed!");
});
unwatch();
// $destroy()
obj.$destroy();
// $extendFactory()
var NewFactory = $FirebaseObject.$extendFactory({
getMyFavoriteColor: function () {
return this.favoriteColor + ", no green!"; // obscure Monty Python reference
}
});
var customObj = $firebase(ref, { objectFactory: NewFactory }).$asObject();
}
// AngularFireArray
{
var list = sync.$asArray();
// $inst()
if (list.$inst() !== sync) throw "error";
// $add()
list.$add({ foo: "foo value" });
// $keyAt()
var key = list.$keyAt(0);
// $indexFor()
var index = list.$indexFor(key);
// $getRecord()
var item = list.$getRecord(key);
// $save()
item["bar"] = "bar value";
list.$save(item);
// $remove()
list.$remove(item);
// $loaded()
list.$loaded().then(data => {
if (data !== list) throw "error";
});
// $watch()
var unwatch = list.$watch((event, key, prevChild) => {
switch (event) {
case "child_added":
console.log(key + " added");
break;
case "child_changed":
console.log(key + " changed");
break;
case "child_moved":
console.log(key + " moved");
break;
case "child_removed":
console.log(key + " removed");
break;
default:
throw "error";
}
});
unwatch();
// $destroy()
list.$destroy();
// $extendFactory()
var ArrayWithSum = $FirebaseArray.$extendFactory({
sum: function () {
var total = 0;
angular.forEach(this.$list, function (rec) {
total += rec.x;
});
return total;
}
});
var list = $firebase(ref, { arrayFactory: ArrayWithSum }).$asArray();
list.$loaded().then(function () {
console.log("List has " + (<any>list).sum() + " items");
});
}
$scope.items.$bind($scope, "remoteItems");
$scope.remoteItems.bar = "foo";
$scope.items.$bind($scope, "remote").then(function(unbind) {
unbind();
$scope.remoteItems.bar = "foo";
});
}
]);
var foo: AngularFireObject = {
$priority: 0
};
interface AngularFireAuthScope extends ng.IScope {
loginObj: AngularFireAuth;
}
+55 -14
View File
@@ -1,4 +1,4 @@
// Type definitions for AngularFire 0.6.0
// Type definitions for AngularFire 0.8.2
// Project: http://angularfire.com
// Definitions by: Dénes Harmath <http://github.com/thSoft>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -7,24 +7,65 @@
/// <reference path="../firebase/firebase.d.ts"/>
interface AngularFireService {
(firebase: Firebase): AngularFire;
(firebase: Firebase, config?: any): AngularFire;
}
interface AngularFire {
$add(value: any): void;
$remove(key?: string): void;
$save(key?: string): void;
$child(key: string): AngularFire;
$set(value: any): void;
$getIndex(): string[];
$on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void;
$off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void;
$bind($scope: ng.IScope, modelName: string): ng.IPromise<any>;
$asArray(): AngularFireArray;
$asObject(): AngularFireObject;
$ref(): Firebase;
$push(data: any): ng.IPromise<Firebase>;
$set(key: string, data: any): ng.IPromise<Firebase>;
$set(data: any): ng.IPromise<Firebase>;
$remove(key?: string): ng.IPromise<Firebase>;
$update(key: string, data: Object): ng.IPromise<Firebase>;
$update(data: any): ng.IPromise<Firebase>;
$transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<FirebaseDataSnapshot>;
$transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<FirebaseDataSnapshot>;
}
interface AngularFireObject {
$priority: number;
interface AngularFireObject extends AngularFireSimpleObject {
$id: string;
$priority: number;
$value: any;
$save(): ng.IPromise<Firebase>;
$loaded(resolve?: (x: AngularFireObject) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
$loaded(resolve?: (x: AngularFireObject) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
$loaded(resolve?: (x: AngularFireObject) => void, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
$inst(): AngularFire;
$bindTo(scope: ng.IScope, varName: string): ng.IPromise<any>;
$watch(callback: Function, context?: any): Function;
$destroy(): void;
}
interface AngularFireObjectService {
$extendFactory(ChildClass: Object, methods?: Object): Object;
}
interface AngularFireArray extends Array<AngularFireSimpleObject> {
$add(newData: any): ng.IPromise<Firebase>;
$save(recordOrIndex: any): ng.IPromise<Firebase>;
$remove(recordOrIndex: any): ng.IPromise<Firebase>;
$getRecord(key: string): AngularFireSimpleObject;
$keyAt(recordOrIndex: any): string;
$indexFor(key: string): number;
$loaded(resolve?: (x: AngularFireArray) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
$loaded(resolve?: (x: AngularFireArray) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
$loaded(resolve?: (x: AngularFireArray) => void, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
$inst(): AngularFire;
$watch(cb: (event: string, key: string, prevChild: string) => void, context?: any): Function;
$destroy(): void;
}
interface AngularFireArrayService {
$extendFactory(ChildClass: Object, methods?: Object): Object;
}
interface AngularFireSimpleObject {
$id: string;
$priority: number;
$value: any;
[key: string]: any;
}
interface AngularFireAuthService {
(firebase: Firebase): AngularFireAuth;
@@ -34,7 +75,7 @@ interface AngularFireAuth {
$getCurrentUser(): ng.IPromise<any>;
$login(provider: string, options?: Object): ng.IPromise<any>;
$logout(): void;
$createUser(email: string, password: string, noLogin?: boolean): ng.IPromise<any>;
$createUser(email: string, password: string): ng.IPromise<any>;
$changePassword(email: string, oldPassword: string, newPassword: string): ng.IPromise<any>;
$removeUser(email: string, password: string): ng.IPromise<any>;
$sendPasswordResetEmail(email: string): ng.IPromise<any>;
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular JS 1.2+ (ngAnimate module)
// Type definitions for Angular JS 1.3 (ngAnimate module)
// Project: http://angularjs.org
// Definitions by: Michel Salib <https://github.com/michelsalib>, Adi Dahiya <https://github.com/adidahiya>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+4 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular JS 1.2 (ngCookies module)
// Type definitions for Angular JS 1.3 (ngCookies module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -15,7 +15,9 @@ declare module ng.cookies {
// CookieService
// see http://docs.angularjs.org/api/ngCookies.$cookies
///////////////////////////////////////////////////////////////////////////
interface ICookiesService {}
interface ICookiesService {
[index: string]: any;
}
///////////////////////////////////////////////////////////////////////////
// CookieStoreService
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular JS 1.2 (ngMock, ngMockE2E module)
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+20 -10
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular JS 1.2 (ngResource module)
// Type definitions for Angular JS 1.3 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Michael Jess <http://github.com/miffels>
// Definitions: https://github.com/daptiv/DefinitelyTyped
@@ -11,6 +11,16 @@
///////////////////////////////////////////////////////////////////////////////
declare module ng.resource {
/**
* Currently supported options for the $resource factory options argument.
*/
interface IResourceOptions {
/**
* If true then the trailing slashes from any calculated URL will be stripped (defaults to true)
*/
stripTrailingSlashes?: boolean;
}
///////////////////////////////////////////////////////////////////////////
// ResourceService
// see http://docs.angularjs.org/api/ngResource.$resource
@@ -20,17 +30,17 @@ declare module ng.resource {
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass<IResource<any>>;
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): U;
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass<T>;
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<T>;
}
// Just a reference to facilitate describing new actions
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular JS 1.2 (ngRoute module)
// Type definitions for Angular JS 1.3 (ngRoute module)
// Project: http://angularjs.org
// Definitions by: Jonathan Park <https://github.com/park9140>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular JS 1.2 (ngSanitize module)
// Type definitions for Angular JS 1.3 (ngSanitize module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular Scenario Testing
// Type definitions for Angular Scenario Testing 1.3 (ngScenario module)
// Project: http://angularjs.org
// Definitions by: RomanoLindano <https://github.com/RomanoLindano>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+42 -1
View File
@@ -83,7 +83,7 @@ angular.module('http-auth-interceptor', [])
}
}];
$httpProvider.responseInterceptors.push(interceptor);
$httpProvider.interceptors.push(interceptor);
}]);
@@ -326,6 +326,47 @@ class SampleDirective2 implements ng.IDirective {
angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance);
angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpolate', '$q', ($interpolate: ng.IInterpolateService, $q: ng.IQService) => {
return {
restrict: 'A',
link: (scope: ng.IScope, el: ng.IAugmentedJQuery, attr: ng.IAttributes) => {
$interpolate(attr['test'])(scope);
$interpolate('', true)(scope);
$interpolate('', true, 'html')(scope);
$interpolate('', true, 'html', true)(scope);
var defer = $q.defer();
defer.reject();
defer.resolve();
defer.promise.then(function(d) {
return d;
}).then(function(): any {
return null;
}, function(): any {
return null;
})
.catch((): any => {
return null;
})
.finally((): any => {
return null;
});
var promise = new $q((resolve) => {
resolve();
});
promise = new $q((resolve, reject) => {
reject();
resolve(true);
});
promise = new $q<boolean>((resolver, reject) => {
resolver(true);
reject(false);
});
}
};
}]);
// test from https://docs.angularjs.org/guide/directive
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
+102 -32
View File
@@ -13,6 +13,11 @@ interface Function {
$inject?: string[];
}
// Support AMD require
declare module 'angular' {
export = angular;
}
///////////////////////////////////////////////////////////////////////////////
// ng module (angular.js)
///////////////////////////////////////////////////////////////////////////////
@@ -32,6 +37,10 @@ declare module ng {
$get: any;
}
interface IAngularBootstrapConfig {
strictDi?: boolean;
}
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// see http://docs.angularjs.org/api
@@ -46,8 +55,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: string, modules?: string): auto.IInjectorService;
bootstrap(element: string, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -55,8 +66,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: string, modules?: Function): auto.IInjectorService;
bootstrap(element: string, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -64,8 +77,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: string, modules?: string[]): auto.IInjectorService;
bootstrap(element: string, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -73,8 +88,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: JQuery, modules?: string): auto.IInjectorService;
bootstrap(element: JQuery, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -82,8 +99,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: JQuery, modules?: Function): auto.IInjectorService;
bootstrap(element: JQuery, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -91,8 +110,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: JQuery, modules?: string[]): auto.IInjectorService;
bootstrap(element: JQuery, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -100,8 +121,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: Element, modules?: string): auto.IInjectorService;
bootstrap(element: Element, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -109,8 +132,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: Element, modules?: Function): auto.IInjectorService;
bootstrap(element: Element, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -118,8 +143,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: Element, modules?: string[]): auto.IInjectorService;
bootstrap(element: Element, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -127,8 +154,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: Document, modules?: string): auto.IInjectorService;
bootstrap(element: Document, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -136,8 +165,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: Document, modules?: Function): auto.IInjectorService;
bootstrap(element: Document, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Use this function to manually start up angular application.
*
@@ -145,8 +176,10 @@ declare module ng {
* @param modules An array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: Document, modules?: string[]): auto.IInjectorService;
bootstrap(element: Document, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Creates a deep copy of source, which should be an object or an array.
@@ -230,6 +263,7 @@ declare module ng {
configFn?: Function): IModule;
noop(...args: any[]): void;
reloadWithDebugInfo(): void;
toJson(obj: any, pretty?: boolean): string;
uppercase(str: string): string;
version: {
@@ -412,6 +446,7 @@ declare module ng {
$commitViewValue(): void;
$rollbackViewValue(): void;
$setSubmitted(): void;
$setUntouched(): void;
}
///////////////////////////////////////////////////////////////////////////
@@ -423,13 +458,13 @@ declare module ng {
$setValidity(validationErrorKey: string, isValid: boolean): void;
// Documentation states viewValue and modelValue to be a string but other
// types do work and it's common to use them.
$setViewValue(value: any): void;
$setViewValue(value: any, trigger?: string): void;
$setPristine(): void;
$validate(): void;
$setTouched(): void;
$setUntouched(): void;
$rollbackViewValue(): void;
$commitViewValue(revalidate?: boolean): void;
$commitViewValue(): void;
$isEmpty(value: any): boolean;
$viewValue: any;
@@ -448,6 +483,7 @@ declare module ng {
$validators: IModelValidators;
$asyncValidators: IAsyncModelValidators;
$pending: any;
$pristine: boolean;
$dirty: boolean;
$valid: boolean;
@@ -479,23 +515,31 @@ declare module ng {
* see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope
*/
interface IRootScopeService {
[index: string]: any;
$apply(): any;
$apply(exp: string): any;
$apply(exp: (scope: IScope) => any): any;
$applyAsync(): any;
$applyAsync(exp: string): any;
$applyAsync(exp: (scope: IScope) => any): any;
$broadcast(name: string, ...args: any[]): IAngularEvent;
$destroy(): void;
$digest(): void;
$emit(name: string, ...args: any[]): IAngularEvent;
$eval(expression?: string, args?: Object): any;
$eval(expression?: (scope: IScope) => any, args?: Object): any;
$eval(): any;
$eval(expression: string, locals?: Object): any;
$eval(expression: (scope: IScope) => any, locals?: Object): any;
$evalAsync(expression?: string): void;
$evalAsync(expression?: (scope: IScope) => any): void;
$evalAsync(): void;
$evalAsync(expression: string): void;
$evalAsync(expression: (scope: IScope) => any): void;
// Defaults to false by the implementation checking strategy
$new(isolate?: boolean): IScope;
$new(isolate?: boolean, parent?: IScope): IScope;
/**
* Listens on events of a given type. See $emit for discussion of event life cycle.
@@ -519,10 +563,7 @@ declare module ng {
$watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$parent: IScope;
$root: IRootScopeService;
this: IRootScopeService;
$id: number;
// Hidden members
@@ -530,9 +571,7 @@ declare module ng {
$$phase: any;
}
interface IScope extends IRootScopeService {
[index: string]: any;
}
interface IScope extends IRootScopeService { }
interface IAngularEvent {
/**
@@ -700,8 +739,8 @@ declare module ng {
}
interface ILogProvider {
debugEnabled(enabled: boolean): ILogProvider;
debugEnabled(): boolean;
debugEnabled(enabled: boolean): ILogProvider;
}
// We define this as separete interface so we can reopen it later for
@@ -809,6 +848,8 @@ declare module ng {
*/
search(search: string, paramValue: boolean): ILocationService;
state(): any;
state(state: any): ILocationService;
url(): string;
url(url: string): ILocationService;
}
@@ -844,12 +885,20 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface IRootElementService extends JQuery {}
interface IQResolveReject<T> {
(): void;
(value: T): void;
}
/**
* $q - service in module ng
* A promise/deferred implementation inspired by Kris Kowal's Q.
* See http://docs.angularjs.org/api/ng/service/$q
*/
interface IQService {
new (resolver: (resolve: IQResolveReject<any>) => any): IPromise<any>;
new (resolver: (resolve: IQResolveReject<any>, reject: IQResolveReject<any>) => any): IPromise<any>;
new <T>(resolver: (resolve: IQResolveReject<T>, reject: IQResolveReject<any>) => any): IPromise<T>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
@@ -877,7 +926,7 @@ declare module ng {
*
* @param reason Constant, message, exception or an object representing the rejection reason.
*/
reject(reason?: any): IPromise<void>;
reject(reason?: any): IPromise<any>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
@@ -952,6 +1001,7 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface IAnchorScrollService {
(): void;
yOffset: any;
}
interface IAnchorScrollProvider extends IServiceProvider {
@@ -1011,6 +1061,8 @@ declare module ng {
imgSrcSanitizationWhitelist(): RegExp;
imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider;
debugInfoEnabled(enabled?: boolean): any;
}
interface ICloneAttachFunction {
@@ -1045,6 +1097,7 @@ declare module ng {
interface IControllerProvider extends IServiceProvider {
register(name: string, controllerConstructor: Function): void;
register(name: string, dependencyAnnotatedConstructor: any[]): void;
allowGlobals(): void;
}
/**
@@ -1224,10 +1277,22 @@ declare module ng {
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg<any>) => any): IPromise<TResult>;
}
interface IHttpProviderDefaults {
xsrfCookieName?: string;
xsrfHeaderName?: string;
headers?: {
common?: any;
post?: any;
put?: any;
patch?: any;
}
}
interface IHttpProvider extends IServiceProvider {
defaults: IRequestConfig;
defaults: IHttpProviderDefaults;
interceptors: any[];
responseInterceptors: any[];
useApplyAsync(): boolean;
useApplyAsync(value: boolean): IHttpProvider;
}
///////////////////////////////////////////////////////////////////////////
@@ -1246,7 +1311,7 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$interpolateProvider
///////////////////////////////////////////////////////////////////////////
interface IInterpolateService {
(text: string, mustHaveExpression?: boolean): IInterpolationFunction;
(text: string, mustHaveExpression?: boolean, trustedContext?: string, allOrNothing?: boolean): IInterpolationFunction;
endSymbol(): string;
startSymbol(): string;
}
@@ -1342,6 +1407,11 @@ declare module ng {
* @return A promise whose value is the template content.
*/
(tpl: string, ignoreRequestError?: boolean): IPromise<string>;
/**
* total amount of pending template requests being downloaded.
* @type {number}
*/
totalPendingRequests: number;
}
///////////////////////////////////////////////////////////////////////////
@@ -1361,7 +1431,7 @@ declare module ng {
instanceAttributes: IAttributes,
controller: any,
transclude: ITranscludeFunction
): void;
): void;
}
interface IDirectivePrePost {
@@ -1374,7 +1444,7 @@ declare module ng {
templateElement: IAugmentedJQuery,
templateAttributes: IAttributes,
transclude: ITranscludeFunction
): IDirectivePrePost;
): IDirectivePrePost;
}
interface IDirective {
+7
View File
@@ -410,6 +410,13 @@ declare module ng {
cancel(promise: IPromise<any>): boolean;
}
/**
* The animation object which contains callback functions for each event that is expected to be animated.
*/
interface IAnimateCallbackObject {
eventFn(element: Node, doneFn: () => void): Function;
}
///////////////////////////////////////////////////////////////////////////
// FilterService
// see http://docs.angularjs.org/api/ng.$filter
+110
View File
@@ -0,0 +1,110 @@
// Type definitions for Angular JS 1.2 (ngAnimate module)
// Project: http://angularjs.org
// Definitions by: Michel Salib <https://github.com/michelsalib>, Adi Dahiya <https://github.com/adidahiya>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular-1.2.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngAnimate module (angular-animate.js)
///////////////////////////////////////////////////////////////////////////////
declare module ng.animate {
///////////////////////////////////////////////////////////////////////////
// AnimateService
// see https://code.angularjs.org/1.2.26/docs/api/ngAnimate/service/$animate
///////////////////////////////////////////////////////////////////////////
interface IAnimateService extends ng.IAnimateService {
/**
* Globally enables / disables animations.
*
* @param value If provided then set the animation on or off.
* @param element If provided then the element will be used to represent the enable/disable operation.
* @returns current animation state
*/
enabled(value?: boolean, element?: JQuery): boolean;
/**
* Appends the element to the parentElement element that resides in the document and then runs the enter animation.
*
* @param element the element that will be the focus of the enter animation
* @param parentElement the parent element of the element that will be the focus of the enter animation
* @param afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation
* @param doneCallback the callback function that will be called once the animation is complete
*/
enter(element: JQuery, parentElement: JQuery, afterElement?: JQuery, doneCallback?: () => void): void;
/**
* Runs the leave animation operation and, upon completion, removes the element from the DOM.
*
* @param element the element that will be the focus of the leave animation
* @param doneCallback the callback function that will be called once the animation is complete
*/
leave(element: JQuery, doneCallback?: () => void): void;
/**
* Fires the move DOM operation. Just before the animation starts, the animate service will either append
* it into the parentElement container or add the element directly after the afterElement element if present.
* Then the move animation will be run.
*
* @param element the element that will be the focus of the move animation
* @param parentElement the parent element of the element that will be the focus of the move animation
* @param afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation
* @param doneCallback the callback function that will be called once the animation is complete
*/
move(element: JQuery, parentElement: JQuery, afterElement?: JQuery, doneCallback?: () => void): void;
/**
* Triggers a custom animation event based off the className variable and then attaches the className
* value to the element as a CSS class.
*
* @param element the element that will be animated
* @param className the CSS class that will be added to the element and then animated
* @param doneCallback the callback function that will be called once the animation is complete
*/
addClass(element: JQuery, className: string, doneCallback?: () => void): void;
/**
* Triggers a custom animation event based off the className variable and then removes the CSS class
* provided by the className value from the element.
*
* @param element the element that will be animated
* @param className the CSS class that will be animated and then removed from the element
* @param doneCallback the callback function that will be called once the animation is complete
*/
removeClass(element: JQuery, className: string, doneCallback?: () => void): void;
/**
* Adds and/or removes the given CSS classes to and from the element. Once complete, the done() callback
* will be fired (if provided).
*
* @param element the element which will have its CSS classes changed removed from it
* @param add the CSS classes which will be added to the element
* @param remove the CSS class which will be removed from the element CSS classes have been set on the element
* @param doneCallback done the callback function (if provided) that will be fired after the CSS classes have been set on the element
*/
setClass(element: JQuery, add: string, remove: string, doneCallback?: () => void): void;
}
///////////////////////////////////////////////////////////////////////////
// AngularProvider
// see https://code.angularjs.org/1.2.26/docs/api/ngAnimate/provider/$animateProvider
///////////////////////////////////////////////////////////////////////////
interface IAnimateProvider {
/**
* Registers a new injectable animation factory function.
*
* @param name The name of the animation.
* @param factory The factory function that will be executed to return the animation object.
*/
register(name: string, factory: () => ng.IAnimateCallbackObject): void;
/**
* Gets and/or sets the CSS class expression that is checked when performing an animation.
*
* @param expression The className expression which will be checked against all animations.
* @returns The current CSS className expression value. If null then there is no expression value.
*/
classNameFilter(expression?: RegExp): RegExp;
}
}
+43
View File
@@ -0,0 +1,43 @@
// Type definitions for Angular JS 1.2 (ngCookies module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular-1.2.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngCookies module (angular-cookies.js)
///////////////////////////////////////////////////////////////////////////////
declare module ng.cookies {
///////////////////////////////////////////////////////////////////////////
// CookieService
// see https://code.angularjs.org/1.2.26/docs/api/ngCookies/service/$cookies
///////////////////////////////////////////////////////////////////////////
interface ICookiesService {}
///////////////////////////////////////////////////////////////////////////
// CookieStoreService
// see https://code.angularjs.org/1.2.26/docs/api/ngCookies/service/$cookieStore
///////////////////////////////////////////////////////////////////////////
interface ICookieStoreService {
/**
* Returns the value of given cookie key
* @param key Id to use for lookup
*/
get(key: string): any;
/**
* Sets a value for given cookie key
* @param key Id for the value
* @param value Value to be stored
*/
put(key: string, value: any): void;
/**
* Remove given cookie
* @param key Id of the key-value pair to delete
*/
remove(key: string): void;
}
}
+305
View File
@@ -0,0 +1,305 @@
/// <reference path="angular-mocks-1.2.d.ts" />
///////////////////////////////////////
// IAngularStatic
///////////////////////////////////////
var angular: ng.IAngularStatic;
var mock: ng.IMockStatic;
mock = angular.mock;
///////////////////////////////////////
// IMockStatic
///////////////////////////////////////
var date: Date;
mock.dump({ key: 'value' });
mock.inject(
function () { return 1; },
function () { return 2; }
);
mock.inject(
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }]);
// This overload is not documented on the website, but flows from
// how the injector works.
mock.inject(
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }],
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 2; }]);
mock.module('module1', 'module2');
mock.module(
function () { return 1; },
function () { return 2; }
);
mock.module({ module1: function () { return 1; } });
date = mock.TzDate(-7, '2013-1-1T15:00:00Z');
date = mock.TzDate(-8, 12345678);
///////////////////////////////////////
// IExceptionHandlerProvider
///////////////////////////////////////
var exceptionHandlerProvider: ng.IExceptionHandlerProvider;
exceptionHandlerProvider.mode('log');
///////////////////////////////////////
// ITimeoutService
///////////////////////////////////////
var timeoutService: ng.ITimeoutService;
timeoutService.flush();
timeoutService.flush(1234);
timeoutService.flushNext();
timeoutService.flushNext(1234);
timeoutService.verifyNoPendingTasks();
////////////////////////////////////////
// IIntervalService
////////////////////////////////////////
var intervalService: ng.IIntervalService;
var intervalServiceTimeActuallyAdvanced: number;
intervalServiceTimeActuallyAdvanced = intervalService.flush();
intervalServiceTimeActuallyAdvanced = intervalService.flush(1234);
///////////////////////////////////////
// ILogService, ILogCall
///////////////////////////////////////
var logService: ng.ILogService;
var logCall: ng.ILogCall;
var logs: string[];
logService.assertEmpty();
logService.reset();
logCall = logService.debug;
logCall = logService.error;
logCall = logService.info;
logCall = logService.log;
logCall = logService.warn;
logs = logCall.logs;
///////////////////////////////////////
// IHttpBackendService
///////////////////////////////////////
var httpBackendService: ng.IHttpBackendService;
var requestHandler: ng.mock.IRequestHandler;
httpBackendService.flush();
httpBackendService.flush(1234);
httpBackendService.resetExpectations();
httpBackendService.verifyNoOutstandingExpectation();
httpBackendService.verifyNoOutstandingRequest();
requestHandler = httpBackendService.expect('GET', 'http://test.local');
requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data');
requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/);
requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/);
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data');
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/);
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expectDELETE('http://test.local');
requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectGET('http://test.local');
requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectHEAD('http://test.local');
requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectJSONP('http://test.local');
requestHandler = httpBackendService.expectJSONP(/test.local/);
requestHandler = httpBackendService.expectPATCH('http://test.local');
requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data');
requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/);
requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/);
requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data');
requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/);
requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local');
requestHandler = httpBackendService.expectPOST('http://test.local', 'response data');
requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', /response data/);
requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/);
requestHandler = httpBackendService.expectPOST(/test.local/, 'response data');
requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, /response data/);
requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local');
requestHandler = httpBackendService.expectPUT('http://test.local', 'response data');
requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', /response data/);
requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/);
requestHandler = httpBackendService.expectPUT(/test.local/, 'response data');
requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, /response data/);
requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local');
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data');
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/);
requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/);
requestHandler = httpBackendService.when('GET', /test.local/, 'response data');
requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, /response data/);
requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.whenDELETE('http://test.local');
requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenGET('http://test.local');
requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenHEAD('http://test.local');
requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenJSONP('http://test.local');
requestHandler = httpBackendService.whenJSONP(/test.local/);
requestHandler = httpBackendService.whenPATCH('http://test.local');
requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data');
requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/);
requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/);
requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data');
requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/);
requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local');
requestHandler = httpBackendService.whenPOST('http://test.local', 'response data');
requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', /response data/);
requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/);
requestHandler = httpBackendService.whenPOST(/test.local/, 'response data');
requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, /response data/);
requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local');
requestHandler = httpBackendService.whenPUT('http://test.local', 'response data');
requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', /response data/);
requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/);
requestHandler = httpBackendService.whenPUT(/test.local/, 'response data');
requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, /response data/);
requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' });
///////////////////////////////////////
// IRequestHandler
///////////////////////////////////////
requestHandler.passThrough();
requestHandler.respond(function () { });
requestHandler.respond({ key: 'value' });
requestHandler.respond({ key: 'value' }, { header: 'value' });
requestHandler.respond(404);
requestHandler.respond(404, { key: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' });
+226
View File
@@ -0,0 +1,226 @@
// Type definitions for Angular JS 1.2 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular-1.2.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
declare var module: (...modules: any[]) => any;
declare var inject: (...fns: Function[]) => any;
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
declare module ng {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// We reopen it to add the MockStatic definition
///////////////////////////////////////////////////////////////////////////
interface IAngularStatic {
mock: IMockStatic;
}
interface IMockStatic {
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/function/angular.mock.dump
dump(obj: any): string;
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/function/angular.mock.inject
inject(...fns: Function[]): any;
inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/function/angular.mock.module
module(...modules: any[]): any;
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
TzDate(offset: number, timestamp: string): Date;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/service/$exceptionHandler
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/provider/$exceptionHandlerProvider
///////////////////////////////////////////////////////////////////////////
interface IExceptionHandlerProvider extends IServiceProvider {
mode(mode: string): void;
}
///////////////////////////////////////////////////////////////////////////
// TimeoutService
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/service/$timeout
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
flush(delay?: number): void;
flushNext(expectedDelay?: number): void;
verifyNoPendingTasks(): void;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/service/$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
flush(millis?: number): number;
}
///////////////////////////////////////////////////////////////////////////
// LogService
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/service/$log
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ILogService {
assertEmpty(): void;
reset(): void;
}
interface ILogCall {
logs: string[];
}
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see https://code.angularjs.org/1.2.26/docs/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
flush(count?: number): void;
resetExpectations(): void;
verifyNoOutstandingExpectation(): void;
verifyNoOutstandingRequest(): void;
expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
expectDELETE(url: string, headers?: Object): mock.IRequestHandler;
expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler;
expectGET(url: string, headers?: Object): mock.IRequestHandler;
expectGET(url: RegExp, headers?: Object): mock.IRequestHandler;
expectHEAD(url: string, headers?: Object): mock.IRequestHandler;
expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler;
expectJSONP(url: string): mock.IRequestHandler;
expectJSONP(url: RegExp): mock.IRequestHandler;
expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenDELETE(url: string, headers?: Object): mock.IRequestHandler;
whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler;
whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenGET(url: string, headers?: Object): mock.IRequestHandler;
whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenGET(url: RegExp, headers?: Object): mock.IRequestHandler;
whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenHEAD(url: string, headers?: Object): mock.IRequestHandler;
whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler;
whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenJSONP(url: string): mock.IRequestHandler;
whenJSONP(url: RegExp): mock.IRequestHandler;
whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
respond(func: Function): void;
respond(status: number, data?: any, headers?: any): void;
respond(data: any, headers?: any): void;
// Available wehn ngMockE2E is loaded
passThrough(): void;
}
}
}
@@ -0,0 +1,138 @@
/// <reference path="angular-resource-1.2.d.ts" />
interface IMyResource extends ng.resource.IResource<IMyResource> { };
interface IMyResourceClass extends ng.resource.IResourceClass<IMyResource> { };
///////////////////////////////////////
// IActionDescriptor
///////////////////////////////////////
var actionDescriptor: ng.resource.IActionDescriptor;
actionDescriptor.headers = { header: 'value' };
actionDescriptor.isArray = true;
actionDescriptor.method = 'method action';
actionDescriptor.params = { key: 'value' };
///////////////////////////////////////
// IResourceClass
///////////////////////////////////////
var resourceClass: IMyResourceClass;
var resource: IMyResource;
var resourceArray: ng.resource.IResourceArray<IMyResource>;
resource = resourceClass.delete();
resource = resourceClass.delete({ key: 'value' });
resource = resourceClass.delete({ key: 'value' }, function () { });
resource = resourceClass.delete(function () { });
resource = resourceClass.delete(function () { }, function () { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resource.$promise.then(function(data: IMyResource) {});
resource = resourceClass.get();
resource = resourceClass.get({ key: 'value' });
resource = resourceClass.get({ key: 'value' }, function () { });
resource = resourceClass.get(function () { });
resource = resourceClass.get(function () { }, function () { });
resource = resourceClass.get({ key: 'value' }, { key: 'value' });
resource = resourceClass.get({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.get({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resourceArray = resourceClass.query();
resourceArray = resourceClass.query({ key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, function () { });
resourceArray = resourceClass.query(function () { });
resourceArray = resourceClass.query(function () { }, function () { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resourceArray.push(resource);
resourceArray.$promise.then(function(data: ng.resource.IResourceArray<IMyResource>) {});
resource = resourceClass.remove();
resource = resourceClass.remove({ key: 'value' });
resource = resourceClass.remove({ key: 'value' }, function () { });
resource = resourceClass.remove(function () { });
resource = resourceClass.remove(function () { }, function () { });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resource = resourceClass.save();
resource = resourceClass.save({ key: 'value' });
resource = resourceClass.save({ key: 'value' }, function () { });
resource = resourceClass.save(function () { });
resource = resourceClass.save(function () { }, function () { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { }, function () { });
///////////////////////////////////////
// IResource
///////////////////////////////////////
var promise : ng.IPromise<IMyResource>;
var arrayPromise : ng.IPromise<IMyResource[]>;
promise = resource.$delete();
promise = resource.$delete({ key: 'value' });
promise = resource.$delete({ key: 'value' }, function () { });
promise = resource.$delete(function () { });
promise = resource.$delete(function () { }, function () { });
promise = resource.$delete({ key: 'value' }, function () { }, function () { });
promise.then(function(data: IMyResource) {});
promise = resource.$get();
promise = resource.$get({ key: 'value' });
promise = resource.$get({ key: 'value' }, function () { });
promise = resource.$get(function () { });
promise = resource.$get(function () { }, function () { });
promise = resource.$get({ key: 'value' }, function () { }, function () { });
arrayPromise = resourceArray[0].$query();
arrayPromise = resourceArray[0].$query({ key: 'value' });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { });
arrayPromise = resourceArray[0].$query(function () { });
arrayPromise = resourceArray[0].$query(function () { }, function () { });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { }, function () { });
arrayPromise.then(function(data: ng.resource.IResourceArray<IMyResource>) {});
promise = resource.$remove();
promise = resource.$remove({ key: 'value' });
promise = resource.$remove({ key: 'value' }, function () { });
promise = resource.$remove(function () { });
promise = resource.$remove(function () { }, function () { });
promise = resource.$remove({ key: 'value' }, function () { }, function () { });
promise = resource.$save();
promise = resource.$save({ key: 'value' });
promise = resource.$save({ key: 'value' }, function () { });
promise = resource.$save(function () { });
promise = resource.$save(function () { }, function () { });
promise = resource.$save({ key: 'value' }, function () { }, function () { });
///////////////////////////////////////
// IResourceService
///////////////////////////////////////
var resourceService: ng.resource.IResourceService;
resourceClass = resourceService<IMyResource, IMyResourceClass>('test');
resourceClass = resourceService<IMyResource>('test');
resourceClass = resourceService('test');
///////////////////////////////////////
// IModule
///////////////////////////////////////
var mod: ng.IModule;
var resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction<IMyResource>;
var resourceService: ng.resource.IResourceService;
resourceClass = resourceServiceFactoryFunction<IMyResourceClass>(resourceService);
resourceServiceFactoryFunction = function (resourceService: ng.resource.IResourceService) { return <any>resourceClass; };
mod = mod.factory('factory name', resourceServiceFactoryFunction);
///////////////////////////////////////
// IResource
///////////////////////////////////////
+152
View File
@@ -0,0 +1,152 @@
// Type definitions for Angular JS 1.2 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Michael Jess <http://github.com/miffels>
// Definitions: https://github.com/daptiv/DefinitelyTyped
/// <reference path="angular-1.2.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngResource module (angular-resource.js)
///////////////////////////////////////////////////////////////////////////////
declare module ng.resource {
///////////////////////////////////////////////////////////////////////////
// ResourceService
// see https://code.angularjs.org/1.2.26/docs/api/ngResource/service/$resource
// Most of the following definitions were achieved by analyzing the
// actual implementation, since the documentation doesn't seem to cover
// that deeply.
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass<T>;
}
// Just a reference to facilitate describing new actions
interface IActionDescriptor {
method: string;
isArray?: boolean;
params?: any;
headers?: any;
}
// Baseclass for everyresource with default actions.
// If you define your new actions for the resource, you will need
// to extend this interface and typecast the ResourceClass to it.
//
// In case of passing the first argument as anything but a function,
// it's gonna be considered data if the action method is POST, PUT or
// PATCH (in other words, methods with body). Otherwise, it's going
// to be considered as parameters to the request.
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465
//
// Only those methods with an HTTP body do have 'data' as first parameter:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463
// More specifically, those methods are POST, PUT and PATCH:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432
//
// Also, static calls always return the IResource (or IResourceArray) retrieved
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549
interface IResourceClass<T> {
new(dataOrParams? : any) : T;
get(): T;
get(params: Object): T;
get(success: Function, error?: Function): T;
get(params: Object, success: Function, error?: Function): T;
get(params: Object, data: Object, success?: Function, error?: Function): T;
query(): IResourceArray<T>;
query(params: Object): IResourceArray<T>;
query(success: Function, error?: Function): IResourceArray<T>;
query(params: Object, success: Function, error?: Function): IResourceArray<T>;
query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
save(): T;
save(data: Object): T;
save(success: Function, error?: Function): T;
save(data: Object, success: Function, error?: Function): T;
save(params: Object, data: Object, success?: Function, error?: Function): T;
remove(): T;
remove(params: Object): T;
remove(success: Function, error?: Function): T;
remove(params: Object, success: Function, error?: Function): T;
remove(params: Object, data: Object, success?: Function, error?: Function): T;
delete(): T;
delete(params: Object): T;
delete(success: Function, error?: Function): T;
delete(params: Object, success: Function, error?: Function): T;
delete(params: Object, data: Object, success?: Function, error?: Function): T;
}
// Instance calls always return the the promise of the request which retrieved the object
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546
interface IResource<T> {
$get(): ng.IPromise<T>;
$get(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$get(success: Function, error?: Function): ng.IPromise<T>;
$query(): ng.IPromise<IResourceArray<T>>;
$query(params?: Object, success?: Function, error?: Function): ng.IPromise<IResourceArray<T>>;
$query(success: Function, error?: Function): ng.IPromise<IResourceArray<T>>;
$save(): ng.IPromise<T>;
$save(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$save(success: Function, error?: Function): ng.IPromise<T>;
$remove(): ng.IPromise<T>;
$remove(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$remove(success: Function, error?: Function): ng.IPromise<T>;
$delete(): ng.IPromise<T>;
$delete(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$delete(success: Function, error?: Function): ng.IPromise<T>;
/** the promise of the original server interaction that created this instance. **/
$promise : ng.IPromise<T>;
$resolved : boolean;
}
/**
* Really just a regular Array object with $promise and $resolve attached to it
*/
interface IResourceArray<T> extends Array<T> {
/** the promise of the original server interaction that created this collection. **/
$promise : ng.IPromise<IResourceArray<T>>;
$resolved : boolean;
}
/** when creating a resource factory via IModule.factory */
interface IResourceServiceFactoryFunction<T> {
($resource: ng.resource.IResourceService): IResourceClass<T>;
<U extends IResourceClass<T>>($resource: ng.resource.IResourceService): U;
}
}
/** extensions to base ng based on using angular-resource */
declare module ng {
interface IModule {
/** creating a resource service factory */
factory(name: string, resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction<any>): IModule;
}
}
interface Array<T>
{
/** the promise of the original server interaction that created this collection. **/
$promise : ng.IPromise<Array<T>>;
$resolved : boolean;
}
@@ -0,0 +1,17 @@
/// <reference path="angular-route-1.2.d.ts" />
/**
* @license HTTP Auth Interceptor Module for AngularJS
* (c) 2013 Jonathan Park @ Daptiv Solutions Inc
* License: MIT
*/
declare var $routeProvider: ng.route.IRouteProvider;
$routeProvider
.when('/projects/:projectId/dashboard',{
controller: '',
templateUrl: '',
caseInsensitiveMatch: true,
reloadOnSearch: false
})
.otherwise({redirectTo: '/'});
+145
View File
@@ -0,0 +1,145 @@
// Type definitions for Angular JS 1.2 (ngRoute module)
// Project: http://angularjs.org
// Definitions by: Jonathan Park <https://github.com/park9140>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular-1.2.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngRoute module (angular-route.js)
///////////////////////////////////////////////////////////////////////////////
declare module ng.route {
///////////////////////////////////////////////////////////////////////////
// RouteParamsService
// see https://code.angularjs.org/1.2.26/docs/api/ngRoute/service/$routeParams
///////////////////////////////////////////////////////////////////////////
interface IRouteParamsService {
[key: string]: any;
}
///////////////////////////////////////////////////////////////////////////
// RouteService
// see https://code.angularjs.org/1.2.26/docs/api/ngRoute/service/$route
// see https://code.angularjs.org/1.2.26/docs/api/ngRoute/provider/$routeProvider
///////////////////////////////////////////////////////////////////////////
interface IRouteService {
/**
* Causes $route service to reload the current route even if $location hasn't changed.
* As a result of that, ngView creates new scope, reinstantiates the controller.
*/
reload(): void;
/**
* Object with all route configuration Objects as its properties.
*/
routes: any;
// May not always be available. For instance, current will not be available
// to a controller that was not initialized as a result of a route maching.
current?: ICurrentRoute;
}
/**
* see https://code.angularjs.org/1.2.26/docs/api/ngRoute/provider/$routeProvider#when for API documentation
*/
interface IRoute {
/**
* {(string|function()=}
* Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
*/
controller?: any;
/**
* A controller alias name. If present the controller will be published to scope under the controllerAs name.
*/
controllerAs?: string;
/**
* Undocumented?
*/
name?: string;
/**
* {string=|function()=}
* Html template as a string or a function that returns an html template as a string which should be used by ngView or ngInclude directives. This property takes precedence over templateUrl.
*
* If template is a function, it will be called with the following parameters:
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
template?: string;
/**
* {string=|function()=}
* Path or function that returns a path to an html template that should be used by ngView.
*
* If templateUrl is a function, it will be called with the following parameters:
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
templateUrl?: any;
/**
* {Object.<string, function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:
*
* - key - {string}: a name of a dependency to be injected into the controller.
* - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.
*/
resolve?: {[key: string]: any};
/**
* {(string|function())=}
* Value to update $location path with and trigger route redirection.
*
* If redirectTo is a function, it will be called with the following parameters:
*
* - {Object.<string>} - route parameters extracted from the current $location.path() by applying the current route templateUrl.
* - {string} - current $location.path()
* - {Object} - current $location.search()
* - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search().
*/
redirectTo?: any;
/**
* Reload route when only $location.search() or $location.hash() changes.
*
* This option defaults to true. If the option is set to false and url in the browser changes, then $routeUpdate event is broadcasted on the root scope.
*/
reloadOnSearch?: boolean;
/**
* Match routes without being case sensitive
*
* This option defaults to false. If the option is set to true, then the particular route can be matched without being case sensitive
*/
caseInsensitiveMatch?: boolean;
}
// see https://code.angularjs.org/1.2.26/docs/api/ngRoute/service/$route#current
interface ICurrentRoute extends IRoute {
locals: {
$scope: IScope;
$template: string;
};
params: any;
}
interface IRouteProvider extends IServiceProvider {
/**
* Sets route definition that will be used on route change when no other route definition is matched.
*
* @params Mapping information to be assigned to $route.current.
*/
otherwise(params: IRoute): IRouteProvider;
/**
* Adds a new route definition to the $route service.
*
* @param path Route path (matched against $location.path). If $location.path contains redundant trailing slash or is missing one, the route will still match and the $location.path will be updated to add or drop the trailing slash to exactly match the route definition.
*
* - path can contain named groups starting with a colon: e.g. :name. All characters up to the next slash are matched and stored in $routeParams under the given name when the route matches.
* - path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.
* - path can contain optional named groups with a question mark: e.g.:name?.
*
* For example, routes like /color/:color/largecode/:largecode*\/edit will match /color/brown/largecode/code/with/slashes/edit and extract: color: brown and largecode: code/with/slashes.
*
* @param route Mapping information to be assigned to $route.current on route match.
*/
when(path: string, route: IRoute): IRouteProvider;
}
}
@@ -0,0 +1,10 @@
/// <reference path="angular-sanitize-1.2.d.ts" />
var shouldBeString: string;
declare var $sanitizeService: ng.sanitize.ISanitizeService;
shouldBeString = $sanitizeService(shouldBeString);
declare var $linky: ng.sanitize.filter.ILinky;
shouldBeString = $linky(shouldBeString);
shouldBeString = $linky(shouldBeString, shouldBeString);
+35
View File
@@ -0,0 +1,35 @@
// Type definitions for Angular JS 1.2 (ngSanitize module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular-1.2.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngSanitize module (angular-sanitize.js)
///////////////////////////////////////////////////////////////////////////////
declare module ng.sanitize {
///////////////////////////////////////////////////////////////////////////
// SanitizeService
// see https://code.angularjs.org/1.2.26/docs/api/ngSanitize/service/$sanitize
///////////////////////////////////////////////////////////////////////////
interface ISanitizeService {
(html: string): string;
}
///////////////////////////////////////////////////////////////////////////
// Filters included with the ngSanitize
// see https://code.angularjs.org/1.2.26/docs/api/ngSanitize/filter
///////////////////////////////////////////////////////////////////////////
export module filter {
// Finds links in text input and turns them into html links.
// Supports http/https/ftp/mailto and plain email address links.
// see https://code.angularjs.org/1.2.26/docs/api/ngSanitize/filter/linky
interface ILinky {
(text: string, target?: string): string;
}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular Scenario Testing
// Type definitions for Angular Scenario Testing 1.0 (ngScenario module)
// Project: [http://angularjs.org]
// Definitions by: [RomanoLindano]
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+166
View File
@@ -0,0 +1,166 @@
// Type definitions for Angular Scenario Testing 1.2 (ngScenario module)
// Project: http://angularjs.org
// Definitions by: RomanoLindano <https://github.com/RomanoLindano>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../../jquery/jquery.d.ts" />
declare module ng {
export interface IAngularStatic {
scenario: any;
}
}
declare module angularScenario {
export interface RunFunction {
(functionToRun: any): any;
}
export interface RunFunctionWithDescription {
(description: string, functionToRun: any): any;
}
export interface PauseFunction {
(): any;
}
export interface SleepFunction {
(seconds: number): any;
}
export interface Future {
}
export interface testWindow {
href(): Future;
path(): Future;
search(): Future;
hash(): Future;
}
export interface testLocation {
url(): Future;
path(): Future;
search(): Future;
hash(): Future;
}
export interface Browser {
navigateTo(url: string): void;
navigateTo(urlDescription: string, urlFunction: () => string): void;
reload(): void;
window(): testWindow;
location(): testLocation;
}
export interface Matchers {
toEqual(value: any): void;
toBe(value: any): void;
toBeDefined(): void;
toBeTruthy(): void;
toBeFalsy(): void;
toMatch(regularExpression: any): void;
toBeNull(): void;
toContain(value: any): void;
toBeLessThan(value: any): void;
toBeGreaterThan(value: any): void;
}
export interface CustomMatchers extends Matchers {
}
export interface Expect extends CustomMatchers {
not(): angularScenario.CustomMatchers;
}
export interface UsingFunction {
(selector: string, selectorDescription?: string): void;
}
export interface BindingFunction {
(bracketBindingExpression: string): Future;
}
export interface Input {
enter(value: any): any;
check(): any;
select(radioButtonValue: any): any;
val(): Future;
}
export interface Repeater {
count(): Future;
row(index: number): Future;
column(ngBindingExpression: string): Future;
}
export interface Select {
option(value: any): any;
option(...listOfValues: any[]): any;
}
export interface Element {
count(): Future;
click(): any;
dblclick(): any;
mouseover(): any;
mousedown(): any;
mouseup(): any;
query(callback: (selectedDOMElements: JQuery, callbackWhenDone: (objNull: any, futureValue: any) => any) => any): any;
val(): Future;
text(): Future;
html(): Future;
height(): Future;
innerHeight(): Future;
outerHeight(): Future;
width(): Future;
innerWidth(): Future;
outerWidth(): Future;
position(): Future;
scrollLeft(): Future;
scrollTop(): Future;
offset(): Future;
val(value: any): void;
text(value: any): void;
html(value: any): void;
height(value: any): void;
innerHeight(value: any): void;
outerHeight(value: any): void;
width(value: any): void;
innerWidth(value: any): void;
outerWidth(value: any): void;
position(value: any): void;
scrollLeft(value: any): void;
scrollTop(value: any): void;
offset(value: any): void;
attr(key: any): Future;
prop(key: any): Future;
css(key: any): Future;
attr(key: any, value: any): void;
prop(key: any, value: any): void;
css(key: any, value: any): void;
}
}
declare var describe: angularScenario.RunFunctionWithDescription;
declare var ddescribe: angularScenario.RunFunctionWithDescription;
declare var xdescribe: angularScenario.RunFunctionWithDescription;
declare var beforeEach: angularScenario.RunFunction;
declare var afterEach: angularScenario.RunFunction;
declare var it: angularScenario.RunFunctionWithDescription;
declare var iit: angularScenario.RunFunctionWithDescription;
declare var xit: angularScenario.RunFunctionWithDescription;
declare var pause: angularScenario.PauseFunction;
declare var sleep: angularScenario.SleepFunction;
declare function browser(): angularScenario.Browser;
declare function expect(expectation: angularScenario.Future): angularScenario.Expect;
declare var using: angularScenario.UsingFunction;
declare var binding: angularScenario.BindingFunction;
declare function input(ngModelBinding: string): angularScenario.Input;
declare function repeater(selector: string, repeaterDescription?: string): angularScenario.Repeater;
declare function select(ngModelBinding: string): angularScenario.Select;
declare function element(selector: string, elementDescription?: string): angularScenario.Element;
declare var angular: ng.IAngularStatic;
+1
View File
@@ -57,6 +57,7 @@ declare module assert {
// export = assert;
// }
// move to power-assert.d.ts. do not use this definition file.
declare module "power-assert" {
export = assert;
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for assertion-error 1.0 0
// Type definitions for assertion-error 1.0.0
// Project: https://github.com/chaijs/assertion-error
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+49 -46
View File
@@ -3,12 +3,14 @@
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AsyncMultipleResultsCallback<T> { (err: Error, results: T[]): any; }
interface AsyncSingleResultCallback<T> { (err: Error, result: T): void; }
interface AsyncTimesCallback<T> { (n: number, callback: AsyncMultipleResultsCallback<T>): void; }
interface ErrorCallback { (err?: Error): void; }
interface AsyncResultsCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncTimesCallback<T> { (n: number, callback: AsyncResultsCallback<T>): void; }
interface AsyncIterator<T, R> { (item: T, callback: AsyncSingleResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncSingleResultCallback<R>): void; }
interface AsyncIterator<T> { (item: T, 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 AsyncWorker<T> { (task: T, callback: Function): void; }
@@ -17,10 +19,10 @@ interface AsyncQueue<T> {
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, callback?: AsyncMultipleResultsCallback<T>): void;
push(task: T[], callback?: AsyncMultipleResultsCallback<T>): void;
unshift(task: T, callback?: AsyncMultipleResultsCallback<T>): void;
unshift(task: T[], callback?: AsyncMultipleResultsCallback<T>): void;
push(task: T, callback?: AsyncResultsCallback<T>): void;
push(task: T[], callback?: AsyncResultsCallback<T>): void;
unshift(task: T, callback?: AsyncResultsCallback<T>): void;
unshift(task: T[], callback?: AsyncResultsCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
@@ -36,8 +38,8 @@ interface AsyncPriorityQueue<T> {
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, priority: number, callback?: AsyncMultipleResultsCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncMultipleResultsCallback<T>): void;
push(task: T, priority: number, callback?: AsyncResultsCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncResultsCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
@@ -51,47 +53,48 @@ interface AsyncPriorityQueue<T> {
interface Async {
// Collections
each<T,R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
eachSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
eachLimit<T, R>(arr: T[], limit: number, iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
map<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
select<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
filterSeries<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
selectSeries<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
reject<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
rejectSeries<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
detectSeries<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
sortBy<T, V>(arr: T[], iterator: AsyncIterator<T, V>, callback: AsyncMultipleResultsCallback<T>): any;
some<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
any<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
every<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncIterator<T, R[]>, callback: AsyncMultipleResultsCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R[]>, callback: AsyncMultipleResultsCallback<R>): any;
each<T>(arr: T[], iterator: AsyncIterator<T>, callback: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: ErrorCallback): void;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback: AsyncResultsCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback: AsyncResultsCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback: AsyncResultsCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): 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: AsyncResultIterator<T, boolean>, callback: AsyncResultsCallback<T>): any;
detectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultsCallback<T>): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback: AsyncResultsCallback<T>): any;
some<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultsCallback<T>): any;
any<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultsCallback<T>): any;
every<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback: AsyncResultsCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback: AsyncResultsCallback<R>): any;
// Control Flow
series<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
series<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
parallel<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
parallel<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
parallelLimit<T>(tasks: T[], limit: number, callback?: AsyncMultipleResultsCallback<T>): void;
parallelLimit<T>(tasks: T, limit: number, callback?: AsyncMultipleResultsCallback<T>): void;
series<T>(tasks: T[], callback?: AsyncResultsCallback<T>): void;
series<T>(tasks: T, callback?: AsyncResultsCallback<T>): void;
parallel<T>(tasks: T[], callback?: AsyncResultsCallback<T>): void;
parallel<T>(tasks: T, callback?: AsyncResultsCallback<T>): void;
parallelLimit<T>(tasks: T[], limit: number, callback?: AsyncResultsCallback<T>): void;
parallelLimit<T>(tasks: T, limit: number, callback?: AsyncResultsCallback<T>): void;
whilst(test: Function, fn: Function, callback: Function): void;
until(test: Function, fn: Function, callback: Function): void;
waterfall<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
waterfall<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
waterfall<T>(tasks: T[], callback?: AsyncResultsCallback<T>): void;
waterfall<T>(tasks: T, callback?: AsyncResultsCallback<T>): void;
queue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
// auto(tasks: any[], callback?: AsyncMultipleResultsCallback<T>): void;
auto(tasks: any, callback?: AsyncMultipleResultsCallback<any>): void;
// auto(tasks: any[], callback?: AsyncResultsCallback<T>): void;
auto(tasks: any, callback?: AsyncResultsCallback<any>): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): void;
nextTick<T>(callback: Function): void;
+75 -1
View File
@@ -18,7 +18,81 @@ declare module "aws-sdk" {
accessKeyId: string;
}
export interface ClientConfig {
export interface Logger {
write?: (chunk: any, encoding?: string, callback?: () => void) => void;
log?: (...messages: any[]) => void;
}
export interface HttpOptions {
proxy?: string;
agent?: any;
timeout?: number;
xhrAsync?: boolean;
xhrWithCredentials?: boolean;
}
export interface Services {
autoscaling?: any;
cloudformation?: any;
cloudfront?: any;
cloudsearch?: any;
cloudsearchdomain?: any;
cloudtrail?: any;
cloudwatch?: any;
cloudwatchlogs?: any;
cognitoidentity?: any;
cognitosync?: any;
datapipeline?: any;
directconnect?: any;
dynamodb?: any;
ec2?: any;
elasticache?: any;
elasticbeanstalk?: any;
elastictranscoder?: any;
elb?: any;
emr?: any;
glacier?: any;
httpOptions?: HttpOptions;
iam?: any;
importexport?: any;
kinesis?: any;
opsworks?: any;
rds?: any;
redshift?: any;
route53?: any;
route53domains?: any;
s3?: any;
ses?: any;
simpledb?: any;
sns?: any;
sqs?: any;
storagegateway?: any;
sts?: any;
support?: any;
swf?: any;
}
export interface ClientConfigPartial extends Services {
credentials?: Credentials;
region?: string;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
logger?: Logger;
maxRedirects?: number;
maxRetries?: number;
paramValidation?: boolean;
s3ForcePathStyle?: boolean;
apiVersion?: any;
apiVersions?: Services;
signatureVersion?: string;
sslEnabled?: boolean;
systemClockOffset?: number;
}
export interface ClientConfig extends ClientConfigPartial {
update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void;
getCredentials?: (callback: (err?: any) => void) => void ;
loadFromPath?: (path: string) => void;
credentials: Credentials;
region: string;
}
+2 -1
View File
@@ -241,7 +241,7 @@ declare module Backbone {
last(): TModel;
last(n: number): TModel[];
lastIndexOf(element: TModel, fromIndex?: number): number;
map(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[];
map(iterator: (element: TModel, index: number, context?: any) => any, context?: any): any[];
max(iterator?: (element: TModel, index: number) => any, context?: any): TModel;
min(iterator?: (element: TModel, index: number) => any, context?: any): TModel;
reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
@@ -279,6 +279,7 @@ declare module Backbone {
constructor(options?: RouterOptions);
initialize(options?: RouterOptions): void;
route(route: string, name: string, callback?: Function): Router;
route(route: RegExp, name: string, callback?: Function): Router;
navigate(fragment: string, options?: NavigateOptions): Router;
navigate(fragment: string, trigger?: boolean): Router;
+882
View File
@@ -0,0 +1,882 @@
/// <reference path="bluebird-1.0.d.ts" />
// Tests by: Bart van der Schoor <https://github.com/Bartvds>
// Note: replicate changes to all overloads in both definition and test file
// Note: keep both static and instance members inline (so similar)
// Note: try to maintain the ordering and separators, and keep to the pattern
var obj: Object;
var bool: boolean;
var num: number;
var str: string;
var err: Error;
var x: any;
var f: Function;
var func: Function;
var arr: any[];
var exp: RegExp;
var anyArr: any[];
var strArr: string[];
var numArr: number[];
// - - - - - - - - - - - - - - - - -
var value: any;
var reason: any;
var insanity: any;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Foo {
foo(): string;
}
interface Bar {
bar(): string;
}
// - - - - - - - - - - - - - - - - -
interface StrFooMap {
[key:string]:Foo;
}
interface StrBarMap {
[key:string]:Bar;
}
// - - - - - - - - - - - - - - - - -
interface StrFooArrMap {
[key:string]:Foo[];
}
interface StrBarArrMap {
[key:string]:Bar[];
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var foo: Foo;
var bar: Bar;
var fooArr: Foo[];
var barArr: Bar[];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var numProm: Promise<number>;
var strProm: Promise<string>;
var anyProm: Promise<any>;
var boolProm: Promise<boolean>;
var objProm: Promise<Object>;
var voidProm: Promise<void>;
var fooProm: Promise<Foo>;
var barProm: Promise<Bar>;
// - - - - - - - - - - - - - - - - -
var numThen: Promise.Thenable<number>;
var strThen: Promise.Thenable<string>;
var anyThen: Promise.Thenable<any>;
var boolThen: Promise.Thenable<boolean>;
var objThen: Promise.Thenable<Object>;
var voidThen: Promise.Thenable<void>;
var fooThen: Promise.Thenable<Foo>;
var barThen: Promise.Thenable<Bar>;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var numArrProm: Promise<number[]>;
var strArrProm: Promise<string[]>;
var anyArrProm: Promise<any[]>;
var fooArrProm: Promise<Foo[]>;
var barArrProm: Promise<Bar[]>;
// - - - - - - - - - - - - - - - - -
var numArrThen: Promise.Thenable<number[]>;
var strArrThen: Promise.Thenable<string[]>;
var anyArrThen: Promise.Thenable<any[]>;
var fooArrThen: Promise.Thenable<Foo[]>;
var barArrThen: Promise.Thenable<Bar[]>;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var numPromArr: Promise<number>[];
var strPromArr: Promise<string>[];
var anyPromArr: Promise<any>[];
var fooPromArr: Promise<Foo>[];
var barPromArr: Promise<Bar>[];
// - - - - - - - - - - - - - - - - -
var numThenArr: Promise.Thenable<number>[];
var strThenArr: Promise.Thenable<string>[];
var anyThenArr: Promise.Thenable<any>[];
var fooThenArr: Promise.Thenable<Foo>[];
var barThenArr: Promise.Thenable<Bar>[];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// booya!
var fooThenArrThen: Promise.Thenable<Promise.Thenable<Foo>[]>;
var barThenArrThen: Promise.Thenable<Promise.Thenable<Bar>[]>;
var fooResolver: Promise.Resolver<Foo>;
var barResolver: Promise.Resolver<Bar>;
var fooInspection: Promise.Inspection<Foo>;
var barInspection: Promise.Inspection<Bar>;
var fooInspectionArrProm: Promise<Promise.Inspection<Foo>[]>;
var barInspectionArrProm: Promise<Promise.Inspection<Bar>[]>;
var BlueBird: typeof Promise;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooThen = fooProm;
barThen = barProm;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = new Promise((resolve: (value: Foo) => void, reject: (reason: any) => void) => {
if (bool) {
resolve(foo);
}
else {
reject(new Error(str));
}
});
fooProm = new Promise((resolve: (value: Foo) => void) => {
if (bool) {
resolve(foo);
}
});
// - - - - - - - - - - - - - - - - - - - - - - -
// needs a hint when used untyped?
fooProm = new Promise<Foo>((resolve, reject) => {
if (bool) {
resolve(fooThen);
}
else {
reject(new Error(str));
}
});
fooProm = new Promise<Foo>((resolve) => {
resolve(fooThen);
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooResolver.resolve(foo);
fooResolver.reject(err);
fooResolver.progress(bar);
fooResolver.callback = (err: any, value: Foo) => {
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool = fooInspection.isFulfilled();
bool = fooInspection.isRejected();
bool = fooInspection.isPending();
foo = fooInspection.value();
x = fooInspection.error();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
}, (note: any) => {
return bar;
});
barProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
});
barProm = fooProm.then((value: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.catch((reason: any) => {
return bar;
});
barProm = fooProm.caught((reason: any) => {
return bar;
});
barProm = fooProm.catch((reason: any) => {
return bar;
}, (reason: any) => {
return bar;
});
barProm = fooProm.caught((reason: any) => {
return bar;
}, (reason: any) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.catch(Error, (reason: any) => {
return bar;
});
barProm = fooProm.caught(Error, (reason: any) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.error((reason: any) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.finally((value: Foo) => {
// return is ignored
return foo;
});
fooProm = fooProm.finally((value: Foo) => {
// return is ignored
return fooThen;
});
fooProm = fooProm.finally((value: Foo) => {
// return is ignored
});
fooProm = fooProm.finally(() => {
// return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.lastly((value: Foo) => {
// return is ignored
return foo;
});
fooProm = fooProm.lastly((value: Foo) => {
// return is ignored
return fooThen;
});
fooProm = fooProm.lastly((value: Foo) => {
// return is ignored
});
fooProm = fooProm.lastly(() => {
// return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.bind(obj);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.done((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
}, (note: any) => {
});
barProm = fooProm.done((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
});
barProm = fooProm.done((value: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.done((value: Foo) => {
return barThen;
}, (reason: any) => {
return barThen;
}, (note: any) => {
});
barProm = fooProm.done((value: Foo) => {
return barThen;
}, (reason: any) => {
return barThen;
});
barProm = fooProm.done((value: Foo) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.progressed((note: any) => {
return foo;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.delay(num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.timeout(num);
fooProm = fooProm.timeout(num, str);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm.nodeify();
fooProm = fooProm.nodeify((err: any) => {
});
fooProm = fooProm.nodeify((err: any, foo?: Foo) => {
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.fork((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
}, (note: any) => {
});
barProm = fooProm.fork((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
});
barProm = fooProm.fork((value: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.fork((value: Foo) => {
return barThen;
}, (reason: any) => {
return barThen;
}, (note: any) => {
});
barProm = fooProm.fork((value: Foo) => {
return barThen;
}, (reason: any) => {
return barThen;
});
barProm = fooProm.fork((value: Foo) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.cancel<Bar>();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.cancellable();
fooProm = fooProm.uncancellable();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool = fooProm.isCancellable();
bool = fooProm.isFulfilled();
bool = fooProm.isRejected();
bool = fooProm.isPending();
bool = fooProm.isResolved();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooInspection = fooProm.inspect();
anyProm = fooProm.call(str);
anyProm = fooProm.call(str, 1, 2, 3);
//TODO enable get() test when implemented
// barProm = fooProm.get(str);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.return(bar);
barProm = fooProm.thenReturn(bar);
voidProm = fooProm.return();
voidProm = fooProm.thenReturn();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooProm
fooProm = fooProm.throw(err);
fooProm = fooProm.thenThrow(err);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
str = fooProm.toString();
obj = fooProm.toJSON();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooArrProm.spread<Bar>((one: Foo, two: Bar) => {
return bar;
}, (reason: any) => {
return bar;
});
barProm = fooArrProm.spread<Bar>((one: Foo, two: Bar, twotwo: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - -
barProm = fooArrProm.spread<Bar>((one: Foo, two: Bar) => {
return barThen;
}, (reason: any) => {
return barThen;
});
barProm = fooArrProm.spread<Bar>((one: Foo, two: Bar, twotwo: Foo) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO fix collection inference
barArrProm = fooProm.all<Bar>();
objProm = fooProm.props();
barInspectionArrProm = fooProm.settle<Bar>();
barProm = fooProm.any<Bar>();
barArrProm = fooProm.some<Bar>(num);
barProm = fooProm.race<Bar>();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO fix collection inference
barArrProm = fooProm.map<Foo, Bar>((item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = fooProm.map<Foo, Bar>((item: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.reduce<Foo, Bar>((memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
});
barProm = fooProm.reduce<Foo, Bar>((memo: Bar, item: Foo) => {
return memo;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooArrProm = fooArrProm.filter<Foo>((item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = fooArrProm.filter<Foo>((item: Foo) => {
return bool;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = Promise.try(() => {
return foo;
});
fooProm = Promise.try(() => {
return foo;
}, arr);
fooProm = Promise.try(() => {
return foo;
}, arr, x);
// - - - - - - - - - - - - - - - - -
fooProm = Promise.try(() => {
return fooThen;
});
fooProm = Promise.try(() => {
return fooThen;
}, arr);
fooProm = Promise.try(() => {
return fooThen;
}, arr, x);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = Promise.attempt(() => {
return foo;
});
fooProm = Promise.attempt(() => {
return foo;
}, arr);
fooProm = Promise.attempt(() => {
return foo;
}, arr, x);
// - - - - - - - - - - - - - - - - -
fooProm = Promise.attempt(() => {
return fooThen;
});
fooProm = Promise.attempt(() => {
return fooThen;
}, arr);
fooProm = Promise.attempt(() => {
return fooThen;
}, arr, x);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
func = Promise.method(function () {
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = Promise.resolve(foo);
fooProm = Promise.resolve(fooThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
voidProm = Promise.reject(reason);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooResolver = Promise.defer<Foo>();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = Promise.cast(foo);
fooProm = Promise.cast(fooThen);
voidProm = Promise.bind(x);
bool = Promise.is(value);
Promise.longStackTraces();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO enable delay
fooProm = Promise.delay(fooThen, num);
fooProm = Promise.delay(foo, num);
voidProm = Promise.delay(num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
func = Promise.promisify(f);
func = Promise.promisify(f, obj);
;
obj = Promise.promisifyAll(obj);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO enable generator
/*
func = Promise.coroutine(f);
barProm = Promise.spawn<number>(f);
*/
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BlueBird = Promise.noConflict();
Promise.onPossiblyUnhandledRejection((reason: any) => {
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO expand tests to overloads
fooArrProm = Promise.all(fooThenArrThen);
fooArrProm = Promise.all(fooArrProm);
fooArrProm = Promise.all(fooThenArr);
fooArrProm = Promise.all(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
objProm = Promise.props(objProm);
objProm = Promise.props(obj);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO expand tests to overloads
fooInspectionArrProm = Promise.settle(fooThenArrThen);
fooInspectionArrProm = Promise.settle(fooArrProm);
fooInspectionArrProm = Promise.settle(fooThenArr);
fooInspectionArrProm = Promise.settle(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO expand tests to overloads
fooProm = Promise.any(fooThenArrThen);
fooProm = Promise.any(fooArrProm);
fooProm = Promise.any(fooThenArr);
fooProm = Promise.any(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO expand tests to overloads
fooProm = Promise.race(fooThenArrThen);
fooProm = Promise.race(fooArrProm);
fooProm = Promise.race(fooThenArr);
fooProm = Promise.race(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO expand tests to overloads
fooArrProm = Promise.some(fooThenArrThen, num);
fooArrProm = Promise.some(fooArrThen, num);
fooArrProm = Promise.some(fooThenArr, num);
fooArrProm = Promise.some(fooArr, num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooArrProm = Promise.join(foo, foo, foo);
fooArrProm = Promise.join(fooThen, fooThen, fooThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// map()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
barArrProm = Promise.map(fooThenArrThen, (item: Foo) => {
return bar;
});
barArrProm = Promise.map(fooThenArrThen, (item: Foo) => {
return barThen;
});
barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
barArrProm = Promise.map(fooArrThen, (item: Foo) => {
return bar;
});
barArrProm = Promise.map(fooArrThen, (item: Foo) => {
return barThen;
});
barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
barArrProm = Promise.map(fooThenArr, (item: Foo) => {
return bar;
});
barArrProm = Promise.map(fooThenArr, (item: Foo) => {
return barThen;
});
barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
barArrProm = Promise.map(fooArr, (item: Foo) => {
return bar;
});
barArrProm = Promise.map(fooArr, (item: Foo) => {
return barThen;
});
barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// reduce()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// filter()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => {
return bool;
});
fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => {
return boolThen;
});
fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
fooArrProm = Promise.filter(fooArrThen, (item: Foo) => {
return bool;
});
fooArrProm = Promise.filter(fooArrThen, (item: Foo) => {
return boolThen;
});
fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
fooArrProm = Promise.filter(fooThenArr, (item: Foo) => {
return bool;
});
fooArrProm = Promise.filter(fooThenArr, (item: Foo) => {
return boolThen;
});
fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
fooArrProm = Promise.filter(fooArr, (item: Foo) => {
return bool;
});
fooArrProm = Promise.filter(fooArr, (item: Foo) => {
return boolThen;
});
fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+670
View File
@@ -0,0 +1,670 @@
// Type definitions for bluebird 1.0.0
// Project: https://github.com/petkaantonov/bluebird
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts
// By: Campredon <https://github.com/fdecampredon/>
// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code):
// - https://github.com/borisyankov/DefinitelyTyped/issues/1563
// Note: replicate changes to all overloads in both definition and test file
// Note: keep both static and instance members inline (so similar)
// TODO fix remaining TODO annotations in both definition and test
// TODO verify support to have no return statement in handlers to get a Promise<void> (more overloads?)
declare class Promise<R> implements Promise.Thenable<R> {
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*/
constructor(callback: (resolve: (thenable: Promise.Thenable<R>) => void, reject: (error: any) => void) => void);
constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void);
/**
* Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
then<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(onReject?: (error: any) => U): Promise<U>;
caught<U>(onReject?: (error: any) => U): Promise<U>;
/**
* This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called.
*
* This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
/**
* Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections.
*/
error<U>(onReject: (reason: any) => Promise.Thenable<U>): Promise<U>;
error<U>(onReject: (reason: any) => U): Promise<U>;
/**
* Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
*
* Alias `.lastly();` for compatibility with earlier ECMAScript version.
*/
finally(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
finally(handler: (value: R) => R): Promise<R>;
finally(handler: (value: R) => void): Promise<R>;
lastly(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
lastly(handler: (value: R) => R): Promise<R>;
lastly(handler: (value: R) => void): Promise<R>;
/**
* Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
*/
bind(thisArg: any): Promise<R>;
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise.
*/
progressed(handler: (note: any) => any): Promise<R>;
/**
* Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
delay(ms: number): Promise<R>;
/**
* Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance.
*
* You may specify a custom error message with the `message` parameter.
*/
timeout(ms: number, message?: string): Promise<R>;
/**
* Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success.
* Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything.
*/
nodeify(callback: (err: any, value?: R) => void): Promise<R>;
nodeify(...sink: any[]): void;
/**
* Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise.
*/
cancellable(): Promise<R>;
/**
* Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending.
*
* That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason.
*
* In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`.
*
* Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable.
*/
// TODO what to do with this?
cancel<U>(): Promise<U>;
/**
* Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors.
*/
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Create an uncancellable promise based on this promise.
*/
uncancellable(): Promise<R>;
/**
* See if this promise can be cancelled.
*/
isCancellable(): boolean;
/**
* See if this `promise` has been fulfilled.
*/
isFulfilled(): boolean;
/**
* See if this `promise` has been rejected.
*/
isRejected(): boolean;
/**
* See if this `promise` is still defer.
*/
isPending(): boolean;
/**
* See if this `promise` is resolved -> either fulfilled or rejected.
*/
isResolved(): boolean;
/**
* Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`.
*/
inspect(): Promise.Inspection<R>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call(propertyName: string, ...args: any[]): Promise<any>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
// TODO find way to fix get()
// get<U>(propertyName: string): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return(): Promise<any>;
thenReturn(): Promise<any>;
return<U>(value: U): Promise<U>;
thenReturn<U>(value: U): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason: Error): Promise<R>;
thenThrow(reason: Error): Promise<R>;
/**
* Convert to String.
*/
toString(): string;
/**
* This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
*/
toJSON(): Object;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
*/
// TODO how to model instance.spread()? like Q?
spread<U>(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U>(onFulfill: Function, onReject?: (reason: any) => U): Promise<U>;
/*
// TODO or something like this?
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => U): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise<U>;
*/
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
all<U>(): Promise<U[]>;
/**
* Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO how to model instance.props()?
props(): Promise<Object>;
/**
* Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
settle<U>(): Promise<Promise.Inspection<U>[]>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
any<U>(): Promise<U>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
some<U>(count: number): Promise<U[]>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
race<U>(): Promise<U>;
/**
* Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => U): Promise<U[]>;
/**
* Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
filter<U>(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<U[]>;
filter<U>(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise<U[]>;
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
*/
static try<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
static try<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
static attempt<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
static attempt<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
/**
* Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
*/
static method(fn: Function): Function;
/**
* Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
*/
static resolve(): Promise<void>;
static resolve<R>(value: Promise.Thenable<R>): Promise<R>;
static resolve<R>(value: R): Promise<R>;
/**
* Create a promise that is rejected with the given `reason`.
*/
static reject(reason: any): Promise<any>;
static reject<R>(reason: any): Promise<R>;
/**
* Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
*/
static defer<R>(): Promise.Resolver<R>;
/**
* Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable.
*/
static cast<R>(value: Promise.Thenable<R>): Promise<R>;
static cast<R>(value: R): Promise<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
static bind(thisArg: any): Promise<void>;
/**
* See if `value` is a trusted Promise.
*/
static is(value: any): boolean;
/**
* Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
static longStackTraces(): void;
/**
* Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise.
*/
// TODO enable more overloads
static delay<R>(value: Promise.Thenable<R>, ms: number): Promise<R>;
static delay<R>(value: R, ms: number): Promise<R>;
static delay(ms: number): Promise<void>;
/**
* Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
*
* If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
*
* If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
*/
// TODO how to model promisify?
static promisify(nodeFunction: Function, receiver?: any): Function;
/**
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
static promisifyAll(target: Object): Object;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix coroutine GeneratorFunction
static coroutine<R>(generatorFunction: Function): Function;
/**
* Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix spawn GeneratorFunction
static spawn<R>(generatorFunction: Function): Promise<R>;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else.
*/
static noConflict(): typeof Promise;
/**
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*/
static onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason.
*/
// TODO enable more overloads
// promise of array with promises of value
static all<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R[]>;
// promise of array with values
static all<R>(values: Promise.Thenable<R[]>): Promise<R[]>;
// array with promises of value
static all<R>(values: Promise.Thenable<R>[]): Promise<R[]>;
// array with values
static all<R>(values: R[]): Promise<R[]>;
/**
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
*
* *The original object is not modified.*
*/
// TODO verify this is correct
// trusted promise for object
static props(object: Promise<Object>): Promise<Object>;
// object
static props(object: Object): Promise<Object>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array.
*
* *original: The array is not modified. The input array sparsity is retained in the resulting array.*
*/
// promise of array with promises of value
static settle<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<Promise.Inspection<R>[]>;
// promise of array with values
static settle<R>(values: Promise.Thenable<R[]>): Promise<Promise.Inspection<R>[]>;
// array with promises of value
static settle<R>(values: Promise.Thenable<R>[]): Promise<Promise.Inspection<R>[]>;
// array with values
static settle<R>(values: R[]): Promise<Promise.Inspection<R>[]>;
/**
* Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly.
*/
// promise of array with promises of value
static any<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R>;
// promise of array with values
static any<R>(values: Promise.Thenable<R[]>): Promise<R>;
// array with promises of value
static any<R>(values: Promise.Thenable<R>[]): Promise<R>;
// array with values
static any<R>(values: R[]): Promise<R>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
*
* **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
*/
// promise of array with promises of value
static race<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R>;
// promise of array with values
static race<R>(values: Promise.Thenable<R[]>): Promise<R>;
// array with promises of value
static race<R>(values: Promise.Thenable<R>[]): Promise<R>;
// array with values
static race<R>(values: R[]): Promise<R>;
/**
* Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution.
*
* If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
static some<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, count: number): Promise<R[]>;
// promise of array with values
static some<R>(values: Promise.Thenable<R[]>, count: number): Promise<R[]>;
// array with promises of value
static some<R>(values: Promise.Thenable<R>[], count: number): Promise<R[]>;
// array with values
static some<R>(values: R[], count: number): Promise<R[]>;
/**
* Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments.
*/
// variadic array with promises of value
static join<R>(...values: Promise.Thenable<R>[]): Promise<R[]>;
// variadic array with values
static join<R>(...values: R[]): Promise<R[]>;
/**
* Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
static map<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// promise of array with values
static map<R, U>(values: Promise.Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with promises of value
static map<R, U>(values: Promise.Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with values
static map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
/**
* Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
*/
// promise of array with promises of value
static reduce<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// promise of array with values
static reduce<R, U>(values: Promise.Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with promises of value
static reduce<R, U>(values: Promise.Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with values
static reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
// promise of array with promises of value
static filter<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// promise of array with values
static filter<R>(values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with promises of value
static filter<R>(values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with values
static filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
}
declare module Promise {
export interface RangeError extends Error {
}
export interface CancellationError extends Error {
}
export interface TimeoutError extends Error {
}
export interface TypeError extends Error {
}
export interface RejectionError extends Error {
}
export interface Thenable<R> {
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected?: (error: any) => U): Thenable<U>;
then<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable<U>;
}
export interface Resolver<R> {
/**
* Returns a reference to the controlled promise that can be passed to clients.
*/
promise: Promise<R>;
/**
* Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state.
*/
resolve(value: R): void;
resolve(): void;
/**
* Reject the underlying promise with `reason` as the rejection reason.
*/
reject(reason: any): void;
/**
* Progress the underlying promise with `value` as the progression value.
*/
progress(value: any): void;
/**
* Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
*
* If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values.
*/
// TODO specify resolver callback
callback: (err: any, value: R, ...values: R[]) => void;
}
export interface Inspection<R> {
/**
* See if the underlying promise was fulfilled at the creation time of this inspection object.
*/
isFulfilled(): boolean;
/**
* See if the underlying promise was rejected at the creation time of this inspection object.
*/
isRejected(): boolean;
/**
* See if the underlying promise was defer at the creation time of this inspection object.
*/
isPending(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
*
* throws `TypeError`
*/
error(): any;
}
}
declare module 'bluebird' {
export = Promise;
}
+44 -29
View File
@@ -20,6 +20,7 @@ var exp: RegExp;
var anyArr: any[];
var strArr: string[];
var numArr: number[];
var voidVar: void;
// - - - - - - - - - - - - - - - - -
@@ -199,7 +200,7 @@ bool = fooInspection.isPending();
foo = fooInspection.value();
x = fooInspection.error();
x = fooInspection.reason();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@@ -244,9 +245,15 @@ barProm = fooProm.caught((reason: any) => {
barProm = fooProm.catch(Error, (reason: any) => {
return bar;
});
barProm = fooProm.catch(Promise.CancellationError, (reason: any) => {
return bar;
});
barProm = fooProm.caught(Error, (reason: any) => {
return bar;
});
barProm = fooProm.caught(Promise.CancellationError, (reason: any) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@@ -256,36 +263,28 @@ barProm = fooProm.error((reason: any) => {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.finally((value: Foo) => {
// return is ignored
return foo;
});
fooProm = fooProm.finally((value: Foo) => {
// return is ignored
return fooThen;
});
fooProm = fooProm.finally((value: Foo) => {
// return is ignored
fooProm = fooProm.finally(() => {
// non-Thenable return is ignored
return "foo";
});
fooProm = fooProm.finally(() => {
// return is ignored
return fooThen;
});
fooProm = fooProm.finally(() => {
// non-Thenable return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.lastly((value: Foo) => {
// return is ignored
return foo;
});
fooProm = fooProm.lastly((value: Foo) => {
// return is ignored
return fooThen;
});
fooProm = fooProm.lastly((value: Foo) => {
// return is ignored
fooProm = fooProm.lastly(() => {
// non-Thenable return is ignored
return "foo";
});
fooProm = fooProm.lastly(() => {
// return is ignored
return fooThen;
});
fooProm = fooProm.lastly(() => {
// non-Thenable return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@@ -294,40 +293,56 @@ fooProm = fooProm.bind(obj);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.done((value: Foo) => {
voidVar = fooProm.done((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
}, (note: any) => {
});
barProm = fooProm.done((value: Foo) => {
voidVar = fooProm.done((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
});
barProm = fooProm.done((value: Foo) => {
voidVar = fooProm.done((value: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.done((value: Foo) => {
voidVar = fooProm.done((value: Foo) => {
return barThen;
}, (reason: any) => {
return barThen;
}, (note: any) => {
});
barProm = fooProm.done((value: Foo) => {
voidVar = fooProm.done((value: Foo) => {
return barThen;
}, (reason: any) => {
return barThen;
});
barProm = fooProm.done((value: Foo) => {
voidVar = fooProm.done((value: Foo) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.tap((value: Foo) => {
// non-Thenable return is ignored
return "foo";
});
fooProm = fooProm.tap((value: Foo) => {
return fooThen;
});
fooProm = fooProm.tap((value: Foo) => {
return voidThen;
});
fooProm = fooProm.tap(() => {
// non-Thenable return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.progressed((note: any) => {
+53 -13
View File
@@ -1,4 +1,4 @@
// Type definitions for bluebird 1.0.0
// Type definitions for bluebird 2.0.0
// Project: https://github.com/petkaantonov/bluebird
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -16,7 +16,7 @@
// TODO verify support to have no return statement in handlers to get a Promise<void> (more overloads?)
declare class Promise<R> implements Promise.Thenable<R> {
declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R> {
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*/
@@ -72,13 +72,11 @@ declare class Promise<R> implements Promise.Thenable<R> {
*
* Alias `.lastly();` for compatibility with earlier ECMAScript version.
*/
finally(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
finally(handler: (value: R) => R): Promise<R>;
finally(handler: (value: R) => void): Promise<R>;
finally<U>(handler: () => Promise.Thenable<U>): Promise<R>;
finally<U>(handler: () => U): Promise<R>;
lastly(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
lastly(handler: (value: R) => R): Promise<R>;
lastly(handler: (value: R) => void): Promise<R>;
lastly<U>(handler: () => Promise.Thenable<U>): Promise<R>;
lastly<U>(handler: () => U): Promise<R>;
/**
* Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
@@ -88,10 +86,16 @@ declare class Promise<R> implements Promise.Thenable<R> {
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): void;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void;
done<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): void;
done<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void;
/**
* Like `.finally()`, but not called for rejections.
*/
tap<U>(onFulFill: (value: R) => Promise.Thenable<U>): Promise<R>;
tap<U>(onFulfill: (value: R) => U): Promise<R>;
/**
* Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise.
@@ -172,6 +176,20 @@ declare class Promise<R> implements Promise.Thenable<R> {
*/
isResolved(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet.
*
* throws `TypeError`
*/
reason(): any;
/**
* Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`.
*/
@@ -594,6 +612,20 @@ declare module Promise {
}
export interface RejectionError extends Error {
}
export interface OperationalError extends Error {
}
// Ideally, we'd define e.g. "export class RangeError extends Error {}",
// but as Error is defined as an interface (not a class), TypeScript doesn't
// allow extending Error, only implementing it.
// However, if we want to catch() only a specific error type, we need to pass
// a constructor function to it. So, as a workaround, we define them here as such.
export function RangeError(): RangeError;
export function CancellationError(): CancellationError;
export function TimeoutError(): TimeoutError;
export function TypeError(): TypeError;
export function RejectionError(): RejectionError;
export function OperationalError(): OperationalError;
export interface Thenable<R> {
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected: (error: any) => Thenable<U>): Thenable<U>;
@@ -661,8 +693,16 @@ declare module Promise {
*
* throws `TypeError`
*/
error(): any;
reason(): any;
}
/**
* Changes how bluebird schedules calls a-synchronously.
*
* @param scheduler Should be a function that asynchronously schedules
* the calling of the passed in function
*/
export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void;
}
declare module 'bluebird' {
+4 -1
View File
@@ -376,6 +376,7 @@ declare module breeze {
clear(): void;
createEmptyCopy(): EntityManager;
createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol) : Entity;
createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol, mergeStrategy?: StrategySymbol): Entity;
createEntity(entityType: EntityType, config?: {}, entityState?: EntityStateSymbol): Entity;
detachEntity(entity: Entity): boolean;
executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Q.Promise<QueryResult>;
@@ -525,6 +526,7 @@ declare module breeze {
where(property: string, operator: string, value: any): EntityQuery;
where(property: string, operator: FilterQueryOpSymbol, value: any): EntityQuery;
where(predicate: FilterQueryOpSymbol): EntityQuery;
where(property: string, filterop: FilterQueryOpSymbol, property2: string, filterop2: FilterQueryOpSymbol,value:any): EntityQuery;
withParameters(params: Object): EntityQuery;
}
@@ -617,6 +619,7 @@ declare module breeze {
LessThanOrEqual: FilterQueryOpSymbol;
NotEquals: FilterQueryOpSymbol;
StartsWith: FilterQueryOpSymbol;
Any: FilterQueryOpSymbol;
}
var FilterQueryOp: FilterQueryOp;
@@ -651,7 +654,7 @@ declare module breeze {
getEntityTypes(): IStructuralType[];
hasMetadataFor(serviceName: string): boolean;
static importMetadata(exportedString: string): MetadataStore;
importMetadata(exportedString: string): MetadataStore;
importMetadata(exportedString: string, allowMerge?: boolean): MetadataStore;
isEmpty(): boolean;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) =>void ): void;
trackUnmappedType(entityCtor: Function, interceptor?: Function): void;
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for buffer-equal 1.0 0
// Type definitions for buffer-equal 0.0.1
// Project: https://github.com/substack/node-buffer-equal
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+1 -1
View File
@@ -96,7 +96,7 @@ log.fatal(error);
log.fatal(object);
log.fatal('Hello, %s', 'world!');
var recursive = {
var recursive: any = {
hello: 'world',
whats: {
huh: recursive
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for business-rules-engine - v1.0.20
// Type definitions for business-rules-engine v1.0.20
// Project: https://github.com/rsamec/form
// Definitions by: Roman Samec <https://github.com/rsamec>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for CanvasJS v1.5.1 GA
// Type definitions for CanvasJS v1.5.1
// Project: http://canvasjs.com/
// Definitions by: Mark Overholt <https://github.com/mover5>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for CasperJS v1.0.0 API
// Type definitions for CasperJS v1.0.0
// Project: http://casperjs.org/
// Definitions by: Jed Mao <https://github.com/jedmao>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for chai-fuzzy 1.3.0 assert style
// Type definitions for chai-fuzzy 1.3.0
// Project: http://chaijs.com/plugins/chai-fuzzy
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+37
View File
@@ -0,0 +1,37 @@
/// <reference path="change-case.d.ts"/>
import changeCase = require("change-case");
var s: string;
var b: boolean;
s = changeCase.dot(s);
s = changeCase.dotCase(s);
s = changeCase.swap(s);
s = changeCase.swapCase(s);
s = changeCase.path(s);
s = changeCase.pathCase(s);
s = changeCase.upper(s);
s = changeCase.upperCase(s);
s = changeCase.lower(s);
s = changeCase.lowerCase(s);
s = changeCase.camel(s);
s = changeCase.camelCase(s);
s = changeCase.snake(s);
s = changeCase.snakeCase(s);
s = changeCase.title(s);
s = changeCase.titleCase(s);
s = changeCase.param(s);
s = changeCase.paramCase(s);
s = changeCase.pascal(s);
s = changeCase.pascalCase(s);
s = changeCase.constant(s);
s = changeCase.constantCase(s);
s = changeCase.sentence(s);
s = changeCase.sentenceCase(s);
b = changeCase.isUpper(s);
b = changeCase.isUpperCase(s);
b = changeCase.isLower(s);
b = changeCase.isLowerCase(s);
s = changeCase.ucFirst(s);
s = changeCase.upperCaseFirst(s);
+37
View File
@@ -0,0 +1,37 @@
// Type definitions for change-case
// Project: https://github.com/blakeembrey/change-case
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "change-case" {
function dot(s: string): string;
function dotCase(s: string): string;
function swap(s: string): string;
function swapCase(s: string): string;
function path(s: string): string;
function pathCase(s: string): string;
function upper(s: string): string;
function upperCase(s: string): string;
function lower(s: string): string;
function lowerCase(s: string): string;
function camel(s: string): string;
function camelCase(s: string): string;
function snake(s: string): string;
function snakeCase(s: string): string;
function title(s: string): string;
function titleCase(s: string): string;
function param(s: string): string;
function paramCase(s: string): string;
function pascal(s: string): string;
function pascalCase(s: string): string;
function constant(s: string): string;
function constantCase(s: string): string;
function sentence(s: string): string;
function sentenceCase(s: string): string;
function isUpper(s: string): boolean;
function isUpperCase(s: string): boolean;
function isLower(s: string): boolean;
function isLowerCase(s: string): boolean;
function ucFirst(s: string): string;
function upperCaseFirst(s: string): string;
}
+10 -1
View File
@@ -1949,7 +1949,7 @@ declare module chrome.tabs {
export function reload(tabId?: number, reloadProperties?: ReloadProperties, func?: Function): void;
export function duplicate(tabId: number, callback?: (tab?: Tab) => void): void;
export function sendMessage(tabId: number, message: any, responseCallback?: (response: any) => void): void;
export function connect(tabId: number, connectInfo?: ConnectInfo): void;
export function connect(tabId: number, connectInfo?: ConnectInfo): runtime.Port;
export function insertCSS(tabId: number, details: InjectDetails, callback?: Function): void;
export function highlight(highlightInfo: HighlightInfo, callback: (window: chrome.windows.Window) => void): void;
export function query(queryInfo: QueryInfo, callback: (result: Tab[]) => void): void;
@@ -2397,38 +2397,47 @@ declare module chrome.webRequest {
interface WebRequestCompletedEvent extends chrome.events.Event {
addListener(callback: (details: OnCompletedDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnCompletedDetails) => BlockingResponse): void;
}
interface WebRequestHeadersReceivedEvent extends chrome.events.Event {
addListener(callback: (details: OnHeadersReceivedDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnHeadersReceivedDetails) => BlockingResponse): void;
}
interface WebRequestBeforeRedirectEvent extends chrome.events.Event {
addListener(callback: (details: OnBeforeRedirectDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnBeforeRedirectDetails) => BlockingResponse): void;
}
interface WebRequestAuthRequiredEvent extends chrome.events.Event {
addListener(callback: (details: OnAuthRequiredDetails, callback?: (response: BlockingResponse) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]) => void): void;
removeListener(callback: (details: OnAuthRequiredDetails, callback?: (response: BlockingResponse) => void) => void): void;
}
interface WebRequestBeforeSendHeadersEvent extends chrome.events.Event {
addListener(callback: (details: OnBeforeSendHeadersDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnBeforeSendHeadersDetails) => BlockingResponse): void;
}
interface WebRequestErrorOccurredEvent extends chrome.events.Event {
addListener(callback: (details: OnErrorOccurredDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnErrorOccurredDetails) => BlockingResponse): void;
}
interface WebRequestResponseStartedEvent extends chrome.events.Event {
addListener(callback: (details: OnResponseStartedDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnResponseStartedDetails) => BlockingResponse): void;
}
interface WebRequestSendHeadersEvent extends chrome.events.Event {
addListener(callback: (details: OnSendHeadersDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnSendHeadersDetails) => BlockingResponse): void;
}
interface WebRequestBeforeRequestEvent extends chrome.events.Event {
addListener(callback: (details: OnBeforeRequestDetails) => BlockingResponse, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnBeforeRequestDetails) => BlockingResponse): void;
}
var MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES: number;
+6
View File
@@ -550,11 +550,17 @@ declare module CKEDITOR {
}
interface toolbarGroups {
name?: string;
groups?: string[];
}
interface config {
startupMode?: string;
removeButtons?: string;
removePlugins?: string;
toolbar?: any;
toolbarGroups?: toolbarGroups[];
skin?: string;
language?: string;
plugins?: string;
+55
View File
@@ -0,0 +1,55 @@
/// <reference path="cli-color.d.ts" />
/// <reference path="../node/node.d.ts" />
import clc = require('cli-color');
import ansiTrim = require('cli-color/trim');
import setupThrobber = require('cli-color/throbber');
var text: string;
var color: number;
var x: number;
var y: number;
var n: number;
var period: number;
// Test cli-color
text = clc('foo');
text = clc('foo', 42, { toString: () => 'bar' });
text = clc.bold.italic.underline.blink.inverse.strike(text);
text = clc.black.red.green.yellow.blue.magenta.cyan.white(text);
text = clc.bgBlack.bgRed.bgGreen.bgYellow.bgBlack.bgMagenta.bgCyan.bgWhite(text);
text = clc.blackBright.redBright.greenBright.yellowBright.blueBright.magentaBright.cyanBright.whiteBright(text);
text = clc.bgBlackBright.bgRedBright.bgGreenBright.bgYellowBright.bgBlueBright.bgMagentaBright.bgCyanBright.bgWhiteBright(text);
text = clc.xterm(color).bgXterm(color)(text);
text = clc.bold.red.bgGreen.yellowBright.bgBlueBright.xterm(color)(text, text, text);
text = clc.move(x, y);
text = clc.moveTo(x, y);
text = clc.bol();
text = clc.bol(n);
text = clc.bol(n, true);
text = clc.up(n);
text = clc.down(n);
text = clc.left(n);
text = clc.right(n);
text = clc.beep;
text = clc.reset;
var width: number = clc.width;
var height: number = clc.height;
var support: boolean = clc.xtermSupported;
// Test cli-color/trim
text = ansiTrim(clc.red(text));
// Test cli-color/throbber
var throbber: setupThrobber.Throbber;
throbber = setupThrobber(process.stdout.write.bind(process.stdout), period);
throbber = setupThrobber(process.stdout.write.bind(process.stdout), period, clc.red);
throbber.start();
throbber.stop();
throbber.restart();
+96
View File
@@ -0,0 +1,96 @@
// Type definitions for cli-color 0.3.2
// Project: https://github.com/medikoo/cli-color
// Definitions by: Joel Spadin <https://github.com/ChaosinaCan>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "cli-color" {
module m {
export interface Format {
(...text: any[]): string;
bold: Format;
italic: Format;
underline: Format;
blink: Format;
inverse: Format;
strike: Format;
black: Format;
red: Format;
green: Format;
yellow: Format;
blue: Format;
magenta: Format;
cyan: Format;
white: Format;
bgBlack: Format;
bgRed: Format;
bgGreen: Format;
bgYellow: Format;
bgBlue: Format;
bgMagenta: Format;
bgCyan: Format;
bgWhite: Format;
blackBright: Format;
redBright: Format;
greenBright: Format;
yellowBright: Format;
blueBright: Format;
magentaBright: Format;
cyanBright: Format;
whiteBright: Format;
bgBlackBright: Format;
bgRedBright: Format;
bgGreenBright: Format;
bgYellowBright: Format;
bgBlueBright: Format;
bgMagentaBright: Format;
bgCyanBright: Format;
bgWhiteBright: Format;
xterm(color: number): Format;
bgXterm(color: number): Format;
move(x: number, y: number): string;
moveTo(x: number, y: number): string;
bol(n?: number, erase?: boolean): string;
up(n: number): string;
down(n: number): string;
left(n: number): string;
right(n: number): string;
beep: string;
reset: string;
width: number;
height: number;
xtermSupported: boolean;
}
}
var m: m.Format;
export = m;
}
declare module "cli-color/trim" {
function ansiTrim(str: string): string;
export = ansiTrim;
}
declare module "cli-color/throbber" {
import clc = require('cli-color');
module setupThrobber {
export interface Throbber {
start(): void;
stop(): void;
restart(): void;
}
}
function setupThrobber(write: (str: string) => any, period: number, format?: clc.Format): setupThrobber.Throbber;
export = setupThrobber;
}
+2 -1
View File
@@ -6,4 +6,5 @@ var original = {
var copy = clone(original);
copy = clone(original, false);
copy = clone(original, true);
copy = clone(original, true, 1);
copy = clone.clonePrototype(original);
+11 -3
View File
@@ -8,10 +8,18 @@
*/
declare module "clone" {
/**
* @param parent
* @param circular If not given, defaults to true in JS lib.
* @param val the value that you want to clone, any type allowed
* @param circular Call clone with circular set to false if you are certain that obj contains no circular references. This will give better performance if needed. There is no error if undefined or null is passed as obj.
* @param depth to wich the object is to be cloned (optional, defaults to infinity)
*/
function clone(parent: Object, circular?: boolean): Object
function clone<T>(val: T, circular?: boolean, depth?: number): T;
module clone {
/**
* @param obj the object that you want to clone
*/
function clonePrototype<T>(obj: T): T;
}
export = clone
}
+13
View File
@@ -1,5 +1,18 @@
///<reference path="colors.d.ts" />
import colors = require("colors");
var test:string = 'test';
var arr:string[] = ['color', 'odd'.italic.zebra, 'radical'.bold.rainbow, test.underline + 'super'.green];
colors.black("abc").trim();
colors.red("abc").trim();
colors.green("abc").trim();
colors.yellow("abc").trim();
colors.blue("abc").trim();
colors.magenta("abc").trim();
colors.cyan("abc").trim();
colors.white("abc").trim();
colors.gray("abc").trim();
colors.grey("abc").trim();
+11
View File
@@ -5,6 +5,17 @@
declare module "colors" {
export function setTheme(theme:any):any;
export function black(text: string): string;
export function red(text: string): string;
export function green(text: string): string;
export function yellow(text: string): string;
export function blue(text: string): string;
export function magenta(text: string): string;
export function cyan(text: string): string;
export function white(text: string): string;
export function gray(text: string): string;
export function grey(text: string): string;
}
interface String {
+47
View File
@@ -0,0 +1,47 @@
/// <reference path="content-type.d.ts" />
import MediaType = require('content-type');
// https://github.com/deoxxa/content-type/blob/master/README.md
function new_test(): void {
var p = new MediaType('text/html;level=1;q=0.5');
p.q === 0.5;
p.params.level === "1";
var q = new MediaType('application/json', { profile: 'http://example.com/schema.json' });
q.type === "application/json";
q.params.profile === "http://example.com/schema.json";
q.q = 1;
q.toString() === 'application/json;q=1;profile="http://example.com/schema.json"';
}
function mediaCmp_test(): void {
MediaType.mediaCmp(MediaType.parseMedia('text/html'), MediaType.parseMedia('text/html')) === 0;
MediaType.mediaCmp(MediaType.parseMedia('*/*'), MediaType.parseMedia('text/html')) === 1;
MediaType.mediaCmp(MediaType.parseMedia('text/html;level=1'), MediaType.parseMedia('text/html')) === -1;
MediaType.mediaCmp(MediaType.parseMedia('application/json;profile="v1.json"'), MediaType.parseMedia('application/json;profile="v2.json"')) === null;
}
// https://github.com/deoxxa/content-type/blob/master/example.js
function example(): void {
var representations = [
'application/json',
'text/html',
'application/json;profile="schema.json"',
'application/json;profile="different.json"',
];
var accept = [
'text/html;q=0.50',
'*/*;q=0.01',
'application/json;profile=different.json',
'application/json;profile="a,b;c.json?d=1;f=2";q=0.2',
];
console.log('Formats:\n\t' + representations.map(MediaType.parseMedia).join('\n\t'));
console.log('Accept:\n\t' + accept.map(MediaType.parseMedia).join('\n\t'));
console.log('Selected:', (MediaType.select(representations.map(MediaType.parseMedia), accept.map(MediaType.parseMedia)) || 'None').toString());
}
+32
View File
@@ -0,0 +1,32 @@
// Type definitions for content-type v0.0.1
// Project: https://github.com/deoxxa/content-type
// Definitions by: Pine Mizune <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module ContentType {
interface MediaType {
type: string;
q?: number;
params: any;
toString(): string;
}
interface SelectOptions {
sortAvailable?: boolean;
sortAccepted?: boolean;
}
interface MediaTypeStatic {
new (s: string, p?: any): MediaType;
parseMedia(type: string): MediaType;
splitQuotedString(str: string, delimiter?: string, quote?: string): string[];
splitContentTypes(str: string): string[];
select(availableTypes: MediaType[], acceptedTypes: MediaType[], options?: SelectOptions): string;
mediaCmp(a: MediaType, b: MediaType): number;
}
}
declare module "content-type" {
var x: ContentType.MediaTypeStatic;
export = x;
}
+30
View File
@@ -0,0 +1,30 @@
/// <reference path="cookiejs.d.ts" />
// Based on https://github.com/js-coder/cookie.js/blob/gh-pages/tests/spec.js
cookie.set({a: '1', b: '2', c: '3'});
cookie;
cookie.enabled();
cookie.set('n', '5');
cookie.get('a');
cookie.get('__undef__');
cookie.get('__undef__', 'fallback');
cookie.get(['a', 'b']);
cookie.get(['a', '__undef__'], 'fallback');
cookie('a');
cookie('__undef__');
cookie('__undef__', 'fallback');
cookie(['a', 'b']);
cookie(['a', '__undef__'], 'fallback');
cookie.remove('a');
cookie.remove('a', 'b');
cookie.remove(['a', 'b']);
cookie.empty();
cookie.all();
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for cookie.js v1.0.0
// Project: https://github.com/js-coder/cookie.js
// Definitions by: Boltmade <https://github.com/Boltmade>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare function cookie(key : string, fallback?: string) : string;
declare function cookie(keys : string[], fallback?: string) : string;
declare module cookie {
export function set(key : string, value : string, options? : any) : void;
export function set(obj : any, options? : any) : void;
export function remove(key : string) : void;
export function remove(keys : string[]) : void;
export function remove(...args : string[]) : void;
export function empty() : void;
export function get(key : string, fallback?: string) : string;
export function get(keys : string[], fallback?: string) : string;
export function all() : any;
export function enabled() : boolean;
}
declare module "cookiejs" {
export = cookie;
}
Vendored
+8 -4
View File
@@ -9,6 +9,10 @@ declare module D3 {
* Select an element from the current document
*/
select: {
/**
* Returns the empty selection
*/
(): Selection;
/**
* Selects the first element that matches the specified selector string
*
@@ -1158,7 +1162,7 @@ declare module D3 {
/**
* If separation is specified, uses the specified function to compute separation between neighboring nodes. If separation is not specified, returns the current separation function
*/
seperation: {
separation: {
/**
* Gets the current separation function
*/
@@ -1166,7 +1170,7 @@ declare module D3 {
/**
* Sets the specified function to compute separation between neighboring nodes
*/
(seperation: (a: GraphNode, b: GraphNode) => number): TreeLayout;
(separation: (a: GraphNode, b: GraphNode) => number): TreeLayout;
};
/**
* Gets or sets the available layout size
@@ -1378,9 +1382,9 @@ declare module D3 {
}
nodes(root: GraphNode): GraphNode[];
links(nodes: GraphNode[]): GraphLink[];
seperation: {
separation: {
(): (a: GraphNode, b: GraphNode) => number;
(seperation: (a: GraphNode, b: GraphNode) => number): ClusterLayout;
(separation: (a: GraphNode, b: GraphNode) => number): ClusterLayout;
}
size: {
(): number[];
+1 -1
View File
@@ -15,7 +15,7 @@ interface IDateJSLiteral {
}
/** DateJS Public Static Methods */
interface IDateJSStatic extends Date {
interface IDateJSStatic extends IDateJS {
/** Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM) */
today(): IDateJS;
/** Compares the first date to the second date and returns an number indication of their relative values. -1 = this is lessthan date. 0 = values are equal. 1 = this is greaterthan date. */
+54
View File
@@ -0,0 +1,54 @@
///<reference path="dotdotdot.d.ts" />
///<reference path="../jquery/jquery.d.ts" />
$("span").dotdotdot({ ellipsis: ":::" });
$("span").dotdotdot({ wrap: "letter" });
$("span").dotdotdot({ fallbackToLetter: false });
$("span").dotdotdot({ after: $("#after") });
$("span").dotdotdot({ watch: true });
$("span").dotdotdot({ height: 42 });
$("span").dotdotdot({ tolerance: 69 });
$("span").dotdotdot({ callback: () => { } });
$("span").dotdotdot({ callback: (isTruncated: boolean) => { } });
$("span").dotdotdot({ callback: (isTruncated: boolean, orgContent: any) => { } });
$("span").dotdotdot({ lastCharacter: {} });
$("span").dotdotdot({ lastCharacter: { remove: [','] } });
$("span").dotdotdot({ lastCharacter: { noEllipsis: ['.', '.'] } });
// Copied from documentation
$("#wrapper").dotdotdot({
/* The text to add as ellipsis. */
ellipsis: '... ',
/* How to cut off the text/html: 'word'/'letter'/'children' */
wrap: 'word',
/* Wrap-option fallback to 'letter' for long words */
fallbackToLetter: true,
/* jQuery-selector for the element to keep and put after the ellipsis. */
after: null,
/* Whether to update the ellipsis: true/'window' */
watch: false,
/* Optionally set a max-height, if null, the height will be measured. */
height: null,
/* Deviation for the height-option. */
tolerance: 0,
/* Callback function that is fired after the ellipsis is added,
receives two parameters: isTruncated(boolean), orgContent(string). */
callback: function (isTruncated, orgContent) { },
lastCharacter: {
/* Remove these characters from the end of the truncated text. */
remove: [' ', ',', ';', '.', '!', '?'],
/* Don't add an ellipsis if this array contains
the last character of the truncated text. */
noEllipsis: []
}
});
+76
View File
@@ -0,0 +1,76 @@
// Type definitions for dotdotdot v1.6.16
// Project: http://dotdotdot.frebsite.nl/
// Definitions by: Milan Jaros <https://github.com/milanjaros>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface JQuery {
/**
* jQuery.dotdotdot is an advanced cross-browser ellipsis for multiple line content plugin.
* @param options settings that could modify a behaviour.
*/
dotdotdot(options?: JQueryDotDotDot.IDotDotDotOptions): JQuery;
}
declare module JQueryDotDotDot {
interface IDotDotDotOptions {
/** The text to add as ellipsis.
* Default: '... '
*/
ellipsis?: string;
/** How to cut off the text/html: 'word'/'letter'/'children'
* Default: 'word'
*/
wrap?: string;
/** Wrap-option fallback to 'letter' for long words
* Default: true
*/
fallbackToLetter?: boolean;
/** jQuery-selector for the element to keep and put after the ellipsis.
* Default: null
*/
after?: JQuery;
/** Whether to update the ellipsis: true/'window'
* Default: false
*/
watch?: boolean;
/** Optionally set a max-height, if null, the height will be measured.
* Default: null
*/
height?: number;
/** Deviation for the height-option.
* Default: 0
*/
tolerance?: number; //
/** Callback function that is fired after the ellipsis is added,
* receives two parameters:
* @param isTruncated (boolean)
* @param orgContent (string) Documentation says it is string but it is object
* which has e.g.
* context: HTMLHtmlElement;
* length: number; // seems to be always 1
* [index] // this contains the text: orgContent[0].data
*/
callback? (isTruncated: boolean, orgContent: any): void;
lastCharacter?: IDotDotDotOptionsLastCharacter;
}
interface IDotDotDotOptionsLastCharacter {
/** Remove these characters from the end of the truncated text.
* Default: [' ', ',', ';', '.', '!', '?']
*/
remove?: string[];
/** Don't add an ellipsis if this array contains
* the last character of the truncated text.
* Default: []
*/
noEllipsis?: string[];
}
}
+41
View File
@@ -0,0 +1,41 @@
/// <reference path="each.d.ts" />
/// <reference path="../node/node.d.ts" />
function testEach() {
var EachStaticClass: EachStatic = function (array: any[]) {
return {
paused: true,
readable: false,
started: true,
done: true,
total: true,
on: function (eventName: string, cb: (a: any, b?: () => void) => void) {
return EachStaticClass([]);
},
parallel: function (mode: any) {
return EachStaticClass([]);
},
shift: function (items: any[]) {},
write: function (items: any[]) {},
unshift: function (items: any[]) {},
end: function () {
return EachStaticClass([]);
},
times: function () {
return EachStaticClass([]);
},
repeat: function () {
return EachStaticClass([]);
},
sync: function () {
return EachStaticClass([]);
},
files: function (a: any, glob?: any) {}
};
};
var each: Each = EachStaticClass([1, 2, 3]);
var EachReq: EachStatic = require("each");
var each: Each = EachReq([4, 5, 6]);
}
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for NodeEach v0.4.9
// Project: http://www.adaltas.com/projects/node-each/
// Definitions by: Michael Zabka <https://github.com/misak113/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Each {
paused: boolean;
readable: boolean;
started: boolean;
done: boolean;
total: boolean;
on(eventName: string, onCallback: Function): Each;
on(eventName: "item", onItem: (item: any, next: (error?: Error) => void) => void): Each;
on(eventName: "error", onError: (error: Error[]) => void): Each;
on(eventName: "error", onError: (error: Error) => void): Each;
on(eventName: "both", onBoth: (error?: Error[]) => void): Each;
on(eventName: "end", onEnd: () => void): Each;
parallel(mode: number): Each;
parallel(mode: boolean): Each;
shift(items: any[]): void;
write(items: any[]): void;
unshift(items: any[]): void;
end(): Each;
times(): Each;
repeat(): Each;
sync(): Each;
files(glob: any): void;
files(base: any, glob: any): void;
}
interface EachStatic {
(array: any[]): Each;
}
declare var each: EachStatic;
declare module "each" {
export = each;
}
+20
View File
@@ -65,4 +65,24 @@ function colorMatrixTest() {
];
shape.cache(-50, -50, 100, 100);
}
function test_canvas_tick() {
var canvas = <HTMLCanvasElement>document.getElementById('canvas');
var stage = new createjs.Stage(canvas);
var stage = createjs.Ticker.addEventListener("tick", stage);
}
function matrixDecompose() {
var matrix = new createjs.Matrix2D();
var shape = new createjs.Shape();
var transform = matrix.decompose(shape);
var transformData = matrix.decompose();
shape.x = transformData.x;
shape.y = transformData.y;
shape.scaleX = transformData.scaleX;
shape.scaleY = transformData.scaleY;
shape.skewX = transformData.skewX;
shape.skewY = transformData.skewY;
shape.rotation = transformData.rotation;
}
+2
View File
@@ -383,6 +383,7 @@ declare module createjs {
appendTransform(x: number, y: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number, regX?: number, regY?: number): Matrix2D;
clone(): Matrix2D;
copy(matrix: Matrix2D): Matrix2D;
decompose(): {x: number; y: number; scaleX: number; scaleY: number; rotation: number; skewX: number; skewY: number};
decompose(target: Object): Matrix2D;
identity(): Matrix2D;
initialize(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number): Matrix2D;
@@ -728,6 +729,7 @@ declare module createjs {
static setPaused(value: boolean): void;
// EventDispatcher mixins
static addEventListener(type: string, listener: Stage, useCapture?: boolean): Stage;
static addEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function;
static addEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function;
static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object;
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="./empower.d.ts" />
var baseAssert:any;
var fakeFormatter:any;
()=> {
var assert = empower(baseAssert, fakeFormatter);
};
var option:empower.Options = {
modifyMessageOnRethrow: false,
saveContextOnRethrow: false
};
()=> {
var assert = empower(baseAssert, fakeFormatter, option);
};
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for empower
// Project: https://github.com/twada/empower
// Definitions by: vvakame <https://github.com/vvakame>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare function empower(originalAssert:any, formatter:any, options?:empower.Options):any;
declare module empower {
export interface Options {
destructive?: boolean;
modifyMessageOnRethrow?: boolean;
saveContextOnRethrow?: boolean;
patterns?: string[];
}
}
declare module "empower" {
export = empower;
}
+14 -4
View File
@@ -1,7 +1,19 @@
///<reference path="eventemitter2.d.ts"/>
// import eventemitter2 = require("eventemitter2");
// var EventEmitter2 = eventemitter2.EventEmitter2;
// Example for CommonJS/AMD
/*
import eventemitter2 = require("eventemitter2");
var EventEmitter2 = eventemitter2.EventEmitter2;
class Child extends eventemitter2.EventEmitter2 {
}
*/
// This class definition doesn't work in CommonJS/AMD.
class Child extends EventEmitter2 {
}
var server = new EventEmitter2();
function testConfiguration() {
var foo = new EventEmitter2({
@@ -14,8 +26,6 @@ function testConfiguration() {
var bazz = new EventEmitter2();
}
var server = new EventEmitter2();
function testAddListener() {
server.addListener('data', function (value1: any, value2: any, value3: any) {
console.log('The event was raised!');
+133 -26
View File
@@ -3,34 +3,146 @@
// Definitions by: ryiwamoto <https://github.com/ryiwamoto/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module eventemitter2 {
interface Configuration {
/**
* use wildcards
*/
wildcard?: boolean;
interface EventEmitter2Configuration {
/**
* use wildcards
*/
wildcard?: boolean;
/**
* the delimiter used to segment namespaces, defaults to `.`.
*/
delimiter?: string;
/**
* the delimiter used to segment namespaces, defaults to `.`.
*/
delimiter?: string;
/**
* if you want to emit the newListener event set to true.
*/
newListener?: boolean;
/**
* if you want to emit the newListener event set to true.
*/
newListener?: boolean;
/**
* max listeners that can be assigned to an event, default 10.
*/
maxListeners?: number;
}
/**
* max listeners that can be assigned to an event, default 10.
*/
maxListeners?: number;
}
declare class EventEmitter2 {
/**
* @param conf
*/
constructor(conf?: EventEmitter2Configuration);
/**
* Adds a listener to the end of the listeners array for the specified event.
* @param event
* @param listener
*/
addListener(event: string, listener: Function): EventEmitter2;
/**
* Adds a listener to the end of the listeners array for the specified event.
* @param event
* @param listener
*/
on(event: string, listener: Function): EventEmitter2;
/**
* Adds a listener that will be fired when any event is emitted.
* @param listener
*/
onAny(listener: Function): EventEmitter2;
/**
* Removes the listener that will be fired when any event is emitted.
* @param listener
*/
offAny(listener: Function): EventEmitter2;
/**
* Adds a one time listener for the event.
* The listener is invoked only the first time the event is fired, after which it is removed.
* @param event
* @param listener
*/
once(event: string, listener: Function): EventEmitter2;
/**
* Adds a listener that will execute n times for the event before being removed.
* The listener is invoked only the first n times the event is fired, after which it is removed.
* @param event
* @param timesToListen
* @param listener
*/
many(event: string, timesToListen: number, listener: Function): EventEmitter2;
/**
* Remove a listener from the listener array for the specified event.
* Caution: changes array indices in the listener array behind the listener.
* @param event
* @param listener
*/
removeListener(event: string, listener: Function): EventEmitter2;
/**
* Remove a listener from the listener array for the specified event.
* Caution: changes array indices in the listener array behind the listener.
* @param event
* @param listener
*/
off(event: string, listener: Function): EventEmitter2;
/**
* Removes all listeners, or those of the specified event.
* @param event
*/
removeAllListeners(event?: string): EventEmitter2;
/**
* Removes all listeners, or those of the specified event.
* @param events
*/
removeAllListeners(events: string[]): EventEmitter2;
/**
* By default EventEmitters will print a warning if more than 10 listeners are added to it.
* This is a useful default which helps finding memory leaks.
* Obviously not all Emitters should be limited to 10. This function allows that to be increased.
* Set to zero for unlimited.
* @param n
*/
setMaxListeners(n: number): void;
/**
* Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.
* @param event
*/
listeners(event: string): Function[];
/**
* Returns an array of listeners that are listening for any event that is specified.
* This array can be manipulated, e.g. to remove listeners.
*/
listenersAny(): Function[];
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
* @param event
* @param args
*/
emit(event: string, ...args: any[]): boolean;
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
* @param event
*/
emit(event: string[]): boolean;
}
declare module "eventemitter2" {
export class EventEmitter2 {
/**
* @param conf
*/
constructor(conf?: Configuration);
constructor(conf?: EventEmitter2Configuration);
/**
* Adds a listener to the end of the listeners array for the specified event.
@@ -129,7 +241,7 @@ declare module eventemitter2 {
* @param event
* @param args
*/
emit(event: string, ...args: string[]): boolean;
emit(event: string, ...args: any[]): boolean;
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
@@ -139,8 +251,3 @@ declare module eventemitter2 {
}
}
declare module "eventemitter2" {
export = eventemitter2;
}
declare var EventEmitter2: typeof eventemitter2.EventEmitter2;
+21
View File
@@ -0,0 +1,21 @@
/// <reference path="./express-jwt.d.ts" />
import express = require('express');
import jwt = require('express-jwt');
import unless = require('express-unless');
var app = express();
app.use(jwt({
secret: 'shhhhhhared-secret'
}));
app.use(jwt({
secret: 'shhhhhhared-secret',
userProperty: 'auth'
}));
var jwtCheck = jwt({
secret: 'shhhhhhared-secret'
});
jwtCheck.unless = unless;
app.use(jwtCheck.unless({ path: '/api/login' }));
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for express-jwt
// Project: https://www.npmjs.org/package/express-jwt
// Definitions by: Wonshik Kim <https://github.com/wokim/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
/// <reference path="../express-unless/express-unless.d.ts" />
declare module "express-jwt" {
import express = require('express');
import unless = require('express-unless');
function jwt(options: jwt.Options): jwt.RequestHandler;
module jwt {
export interface Options {
secret: string;
userProperty?: string;
skip?: string[];
credentialsRequired?: boolean;
}
export interface RequestHandler extends express.RequestHandler {
unless?: typeof unless;
}
}
export = jwt;
}
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="./express-unless.d.ts" />
import express = require('express');
import unless = require('express-unless');
var app = express();
var middleware:unless.RequestHandler = function (req, res, next) {
next();
}
middleware.unless = unless;
app.use(middleware.unless({ method: 'OPTIONS' }));
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for express-unless
// Project: https://www.npmjs.org/package/express-unless
// Definitions by: Wonshik Kim <https://github.com/wokim/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "express-unless" {
import express = require('express');
function unless(options:unless.Options): express.RequestHandler;
module unless {
export interface Options {
custom?: (req: express.Request) => boolean;
path?: any; // TODO: union type 'string|string[]' is not supported yet
ext?: any; // TODO: union type 'string|string[]' is not supported yet
method?: any; // TODO: union type 'string|string[]' is not supported yet
}
export interface RequestHandler extends express.RequestHandler {
unless?: typeof unless;
}
}
export = unless;
}
+3
View File
@@ -681,6 +681,9 @@ declare module "express" {
header(field: any): Response;
header(field: string, value?: string): Response;
// Property indicating if HTTP headers has been sent for the response.
headersSent: boolean;
/**
* Get value for header `field`.
*
+805 -10
View File
@@ -11,6 +11,152 @@ dataRef.auth(AUTH_TOKEN, function(error, result) {
}
});
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com/');
/*
* Firebase.authWithCustomToken()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithCustomToken(AUTH_TOKEN, function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authAnonymously()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authAnonymously(function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authWithPassword()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithPassword({
"email": "bobtony@firebase.com",
"password": "correcthorsebatterystaple"
}, function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authWithOAuthPopup()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithOAuthPopup("twitter", function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authWithOAuthRedirect
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithOAuthRedirect("twitter", function (error) {
if (error) {
console.log('Login Failed!', error);
} else {
// We'll never get here, as the page will redirect on success.
}
});
}
/*
* Firebase.authWithOAuthToken()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Authenticate with Facebook using an existing OAuth 2.0 access token
dataRef.authWithOAuthToken("facebook", "<ACCESS-TOKEN>", function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Authenticate with Twitter using an existing OAuth 1.0a credential set
dataRef.authWithOAuthToken("twitter", {
"user_id": "<USER-ID>",
"oauth_token": "<ACCESS-TOKEN>",
"oauth_token_secret": "<ACCESS-TOKEN-SECRET>",
}, function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.getAuth()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
var authData = dataRef.getAuth();
if (authData) {
console.log('Authenticated user with uid:', authData.uid);
}
}
/*
* Firebase.onAuth()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.onAuth(function (authData) {
if (authData) {
console.log('Client is authenticated with uid ' + authData.uid);
} else {
// Client is unauthenticated
}
});
}
/*
* Firebase.offAuth
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
var onAuthChange = function (authData: FirebaseAuthData) { /*...*/ };
firebaseRef.onAuth(onAuthChange);
// Sometime later...
firebaseRef.offAuth(onAuthChange);
}
//Time to log out!
dataRef.unauth();
@@ -36,6 +182,146 @@ var fredRef3:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/use
var x4:string = fredRef3.name();
// x is now 'fred'.
/*
* Firebase.key()
*/
() => {
var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred");
var key = fredRef.key(); // key === "fred"
key = fredRef.child("name/last").key(); // key === "last"
}
() => {
// Calling key() on the root of a Firebase will return null:
var rootRef = new Firebase("https://samplechat.firebaseio-demo.com");
var key = rootRef.key(); // key === null
}
/*
* Firebase.set()
*/
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
fredNameRef.child('first').set('Fred');
fredNameRef.child('last').set('Flintstone');
// We've written 'Fred' to the Firebase location storing fred's first name,
// and 'Flintstone' to the location storing his last name
}
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
fredNameRef.set({ first: 'Fred', last: 'Flintstone' });
// Exact same effect as the previous example, except we've written
// fred's first and last name simultaneously
}
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
var onComplete = function (error: any) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
fredNameRef.set({ first: 'Fred', last: 'Flintstone' }, onComplete);
// Same as the previous example, except we will also log a message
// when the data has finished synchronizing
}
/*
* Firebase.update()
*/
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
// Modify the 'first' and 'last' children, but leave other data at fredNameRef unchanged
fredNameRef.update({ first: 'Fred', last: 'Flintstone' });
}
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
// Same as the previous example, except we will also display an alert
// message when the data has finished synchronizing.
var onComplete = function (error:any) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
fredNameRef.update({ first: 'Wilma', last: 'Flintstone' }, onComplete);
}
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
//The following 2 function calls are equivalent
fredRef.update({ name: { first: 'Fred', last: 'Flintstone' }});
fredRef.child('name').set({ first: 'Fred', last: 'Flintstone' });
}
/*
* Firebase.remove()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
fredRef.remove();
// All data at the Firebase location for user 'fred' has been deleted
// (including any child data)
}
() => {
var onComplete = function (error: any) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
fredRef.remove(onComplete);
// Same as the previous example, except we will also log
// a message when the delete has finished synchronizing
}
/*
* Firebase.push()
*/
() => {
var messageListRef = new Firebase('https://samplechat.firebaseio-demo.com/message_list');
var newMessageRef = messageListRef.push();
newMessageRef.set({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
// We've appended a new message to the message_list location.
var path = newMessageRef.toString();
// path will be something like
// 'https://samplechat.firebaseio-demo.com/message_list/-IKo28nwJLH0Nc5XeFmj'
}
() => {
var messageListRef = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
messageListRef.push({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
// Same effect as the previous example, but we've combined the push() and the set().
}
/*
* Firebase.setWithPriority()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
var user = {
name: {
first: 'Fred',
last: 'Flintstone'
},
rank: 1000
};
fredRef.setWithPriority(user, 1000);
// We've written Fred's name and rank to firebase, and used his rank (1000) as the
// priority of the data so he'll be ordered relative to other users by his rank
}
/*
* Firebase.setPriority()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
fredRef.setPriority(1000);
// We have changed the priority of fred's user data to 1000
}
// Increment Fred's rank by 1.
var fredRankRef:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred/rank');
fredRankRef.transaction(function(currentRank: number) {
@@ -51,7 +337,7 @@ wilmaRef.transaction(function(currentData) {
console.log('User wilma already exists.');
return; // Abort the transaction.
}
}, function(error: any, committed: boolean, snapshot: IFirebaseDataSnapshot) {
}, function(error: any, committed: boolean, snapshot: FirebaseDataSnapshot) {
if (error)
console.log('Transaction failed abnormally!', error);
else if (!committed)
@@ -61,14 +347,523 @@ wilmaRef.transaction(function(currentData) {
console.log('Wilma\'s data: ', snapshot.val());
});
var messageListRef: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
var lastMessagesQuery:IFirebaseQuery = messageListRef.endAt().limit(500);
lastMessagesQuery.on('child_added', function(childSnapshot: IFirebaseDataSnapshot) { /* handle child add */ });
/*
* Firebase.createUser()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.createUser({
email: "bobtony@firebase.com",
password: "correcthorsebatterystaple"
}, function (err) {
if (err) {
switch (err.code) {
case 'EMAIL_TAKEN':
// The new user account cannot be created because the email is already in use.
case 'INVALID_EMAIL':
// The specified email is not a valid email.
default:
}
} else {
// User account created successfully!
}
});
}
var messageListRef2:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
var firstMessagesQuery:IFirebaseQuery = messageListRef2.startAt().limit(500);
firstMessagesQuery.on('child_added', function(childSnapshot: IFirebaseDataSnapshot) { /* handle child add */ });
/*
* Firebase.changePassword()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.changePassword({
email: "bobtony@firebase.com",
oldPassword: "correcthorsebatterystaple",
newPassword: "shinynewpassword"
}, function (err) {
if (err) {
switch (err.code) {
case 'INVALID_PASSWORD':
// The specified user account password is incorrect.
case 'INVALID_USER':
// The specified user account does not exist.
default:
}
} else {
// User password changed successfully!
}
});
}
var usersRef3: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users');
var usersQuery: IFirebaseQuery = usersRef3.startAt(1000).limit(50);
usersQuery.on('child_added', function(userSnapshot: IFirebaseDataSnapshot) { /* handle user */ });
/*
* Firebase.removeUser()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.removeUser({
email: "bobtony@firebase.com",
password: "correcthorsebatterystaple"
}, function (err) {
if (err) {
switch (err.code) {
case 'INVALID_USER':
// The specified user account does not exist.
case 'INVALID_PASSWORD':
// The specified user account password is incorrect.
default:
}
} else {
// User account deleted successfully!
}
});
}
/*
* Firebase.resetPassword()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.resetPassword({
email: "bobtony@firebase.com"
}, function (err) {
if (err) {
switch (err.code) {
case 'INVALID_USER':
// The specified user account does not exist.
default:
}
} else {
// Password reset email sent successfully!
}
});
}
//var messageListRef: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
//var lastMessagesQuery:FirebaseQuery = messageListRef.endAt().limit(500);
//lastMessagesQuery.on('child_added', function(childSnapshot: FirebaseDataSnapshot) { /* handle child add */ });
//var messageListRef2:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
//var firstMessagesQuery:FirebaseQuery = messageListRef2.startAt().limit(500);
//firstMessagesQuery.on('child_added', function(childSnapshot: FirebaseDataSnapshot) { /* handle child add */ });
//var usersRef3: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users');
//var usersQuery: FirebaseQuery = usersRef3.startAt(1000).limit(50);
//usersQuery.on('child_added', function(userSnapshot: FirebaseDataSnapshot) { /* handle user */ });
/*
* Firebase.goOffline()
* Firebase.goOnline()
*/
() => {
var usersRef = new Firebase('https://samplechat.firebaseio-demo.com/users');
Firebase.goOffline(); // All Firebase instances are disconnected
Firebase.goOnline(); // All Firebase instances automatically reconnect
}
/*
* FirebaseQuery.on()
*/
() => {
firebaseRef.on('value', function (dataSnapshot) {
// code to handle new value.
});
firebaseRef.on('child_added', function (childSnapshot, prevChildName) {
// code to handle new child.
});
firebaseRef.on('child_removed', function (oldChildSnapshot) {
// code to handle child removal.
});
firebaseRef.on('child_changed', function (childSnapshot, prevChildName) {
// code to handle child data changes.
});
firebaseRef.on('child_changed', function (childSnapshot, prevChildName) {
// code to handle child data changes.
});
}
/*
* FirebaseQuery.off()
*/
() => {
var onValueChange = function (dataSnapshot: FirebaseDataSnapshot) { /* handle... */ };
firebaseRef.on('value', onValueChange);
// Sometime later...
firebaseRef.off('value', onValueChange);
}
() => {
// Or you can save a line of code by using an inline function
// and on()'s return value.
var onValueChange = firebaseRef.on('value', function (dataSnapshot) { /* handle... */ });
// Sometime later...
firebaseRef.off('value', onValueChange);
}
/*
* FirebaseQuery.once()
*/
() => {
// Basic usage of .once() to read the data located at firebaseRef.
firebaseRef.once('value', function (dataSnapshot) {
// handle read data.
});
}
() => {
// Provide a failureCallback to be notified when this
// callback is revoked due to security violations.
firebaseRef.once('value', function (dataSnapshot) {
// code to handle new value
}, function (err: any) {
// code to handle read error
});
}
() => {
// Provide a context to override "this" when callbacks are triggered.
firebaseRef.once('value', function (dataSnapshot) {
// this.x is 1
}, { x: 1 });
}
/*
* FirebaseQuery.orderByChild()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can read all dinosaurs ordered by height using the following query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").on("child_added", function (snapshot) {
console.log(snapshot.key() + " was " + snapshot.val().height + " meters tall");
});
}
/*
* FirebaseQuery.orderByKey()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can read all dinosaurs in alphabetical order, ignoring their priority,
// using the following query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByKey().on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.orderByPriority()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can read all dinosaurs in priority order using the following query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByPriority().on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.startAt()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can find all dinosaurs that are at least three meters tall
// by combining orderByChild() and startAt():
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").startAt(3).on("child_added", function (snapshot) {
console.log(snapshot.key())
});
}
/*
* FirebaseQuery.endAt()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can find all dinosaurs whose names come before Pterodactyl lexicographically
// by combining orderByKey() and endAt():
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByKey().endAt("pterodactyl").on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.equalTo()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can find all dinosaurs whose height is exactly 25 meters
// by combining orderByChild() and equalTo():
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").equalTo(25).on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.limitToFirst
*/
() => {
// Using our sample Firebase of dinosaur facts,
// we can find the two shortest dinosaurs with this query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").limitToFirst(2).on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.limitToLast
*/
() => {
// Using our sample Firebase of dinosaur facts,
// we can find the two heaviest dinosaurs with this query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("weight").limitToLast(2).on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.ref()
*/
() => {
// The Firebase reference returned by ref() is equivalent to the Firebase reference used to create the Query.
var ref = new Firebase("https://samplechat.firebaseio-demo.com/users");
var query = ref.limitToFirst(5);
var refToSameLocation = query.ref(); // ref === refToSameLocation
}
/*
* Firebase.onDisconnect().set()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectmessage');
disconnectRef.onDisconnect().set('I disconnected!');
}
/*
* Firebase.onDisconnect().update()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectmessage');
disconnectRef.onDisconnect().update({ message: 'I disconnected!' });
}
/*
* Firebase.onDisconnect().remove()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectdata');
disconnectRef.onDisconnect().remove();
}
/*
* Firebase.onDisconnect().setWithPriority()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectMessage');
disconnectRef.onDisconnect().setWithPriority('I disconnected', 10);
}
/*
* Firebase.onDisconnect().cancel()
*/
() => {
var fredOnlineRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/online');
fredOnlineRef.onDisconnect().set(false);
// cancel the previously set onDisconnect().set() event
fredOnlineRef.onDisconnect().cancel();
}
/*
* Firebase.ServerValue.TIMESTAMP
*/
() => {
// Record the current time immediately, and queue an event to
// record the time at which the user disconnects.
var sessionsRef = new Firebase('https://samplechat.firebaseio-demo.com/sessions/');
var mySessionRef = sessionsRef.push();
mySessionRef.onDisconnect().update({ endedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
}
/*
* DataSnapshot.val()
*/
() => {
// Demonstrate writing data and then reading it back as a Javascript object.
var fredNameRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred');
fredNameRef.set({ first: 'Fred', last: 'Flintstone' });
fredNameRef.once('value', function (nameSnapshot) {
var val = nameSnapshot.val();
// val now contains the object { first: 'Fred', last: 'Flintstone' }.
});
}
/*
* DataSnapshot.child()
*/
(dataSnapshot:FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child 'name' that has children 'first'
// (set to 'Fred') and 'last' (set to 'Flintstone'):
var nameSnapshot = dataSnapshot.child('name');
var name = nameSnapshot.val();
// name now contains { first: 'Fred', last: 'Flintstone'}.
var firstNameSnapshot = dataSnapshot.child('name/first');
var firstName = firstNameSnapshot.val();
// firstName now contains 'Fred'.
var favoriteColorSnapshot = dataSnapshot.child('favorite_color');
var favoriteColor = favoriteColorSnapshot.val();
// favoriteColor will be null, because there is no 'favorite_color' child in dataSnapshot.
}
/*
* DataSnapshot.forEach()
*/
(dataSnapshot:FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child "fred" and a child "wilma", this callback
// function will be called twice
dataSnapshot.forEach(function (childSnapshot) {
// key will be "fred" the first time and "wilma" the second time
var key = childSnapshot.key();
// childData will be the actual contents of the child
var childData = childSnapshot.val();
});
}
(dataSnapshot:FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child "fred" and a child "wilma", this callback
// funciton will only be called once (since we return true)
dataSnapshot.forEach(function (childSnapshot) {
var key = childSnapshot.key(); // key will be "fred"
return true;
});
}
/*
* DataSnapshot.hasChild()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a DataSnapshot with child 'fred' and no other children:
var x = dataSnapshot.hasChild('fred');
var y = dataSnapshot.hasChild('whales');
// x is true and y is false.
}
/*
* DataSnapshot.hasChildren()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child 'name' with children 'first'
// (set to 'Fred') and 'last' (set to 'Flintstone'):
var x = dataSnapshot.hasChildren();
// x is true.
var y = dataSnapshot.child('name').hasChildren();
// y is true.
var z = dataSnapshot.child('name/first').hasChildren();
// z is false since 'Fred' is a string and therefore has no children.
}
/*
* DataSnapshot.key()
*/
() => {
// Calling key() on any DataSnapshot (except for one which represents the root of a Firebase)
// will return the key name of the location that generated it:
var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred");
fredRef.on("value", function (fredSnapshot) {
var key = fredSnapshot.key(); // key === "fred"
key = fredSnapshot.child("name/last").key(); // key === "last"
});
}
() => {
// Calling key() on a DataSnapshot generated from a reference to the root of a Firebase return null:
var rootRef = new Firebase("https://samplechat.firebaseio-demo.com");
rootRef.on("value", function (rootSnapshot) {
var key = rootSnapshot.key(); // key === null
});
}
/*
* DataSnapshot.name()
*/
() => {
var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred");
fredRef.on("value", function (fredSnapshot) {
var key = fredSnapshot.name(); // key === "fred"
key = fredSnapshot.child("name/last").name(); // key === "last"
});
}
() => {
var rootRef = new Firebase("https://samplechat.firebaseio-demo.com");
rootRef.on("value", function (rootSnapshot) {
var key = rootSnapshot.name(); // key === null
});
}
/*
* DataSnapshot.numChildren()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child 'name' with children 'first'
// (set to 'Fred') and 'last' (set to 'Flintstone'):
var x = dataSnapshot.numChildren();
// x is 1.
var y = dataSnapshot.child('name').numChildren();
// y is 2.
var z = dataSnapshot.child('name/first').numChildren();
// z is 0 since 'Fred' is a string and therefore has no children.
}
/*
* DataSnaphot.ref()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
fredRef.on('value', function (fredSnapshot) {
var fredRef2 = fredSnapshot.ref();
// fredRef and fredRef2 both point to the same location.
});
}
/*
* DataSnapshot.getPriority()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a snapshot for data with priority 1000:
var x = dataSnapshot.getPriority();
// x is now 1000.
}
/*
* DataSnapshot.exportVal()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
firebaseRef.setWithPriority('hello', 500);
firebaseRef.once('value', function (dataSnapshot) {
var x = dataSnapshot.exportVal();
// x now contains { '.value': 'hello', '.priority': 500 }
});
}
(dataSnapshot: FirebaseDataSnapshot) => {
firebaseRef.set('hello');
firebaseRef.once('value', function (dataSnapshot) {
var x = dataSnapshot.exportVal();
// x now contains 'hello'
});
}
(dataSnapshot: FirebaseDataSnapshot) => {
// Note: To access these variables in JavaScript, you can use x['.value'] and x['.priority'].
firebaseRef.setWithPriority({ a: 'hello', b: 'hi' }, 500);
firebaseRef.once('value', function (dataSnapshot) {
var x = dataSnapshot.exportVal();
// x now contains { 'a': 'hello', 'b': 'hi', '.priority': 500 }
});
}
+268 -35
View File
@@ -1,75 +1,308 @@
// Type definitions for Firebase API
// Type definitions for Firebase API 2.0.2
// Project: https://www.firebase.com/docs/javascript/firebase
// Definitions by: Vincent Botone <https://github.com/vbortone/>
// Definitions by: Vincent Botone <https://github.com/vbortone/>, Shin1 Kashimura <https://github.com/in-async/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface IFirebaseAuthResult {
interface FirebaseAuthResult {
auth: any;
expires: number;
}
interface IFirebaseDataSnapshot {
interface FirebaseDataSnapshot {
/**
* Gets the JavaScript object representation of the DataSnapshot.
*/
val(): any;
child(childPath: string): IFirebaseDataSnapshot;
forEach(childAction: (childSnapshot: IFirebaseDataSnapshot) => boolean): boolean;
/**
* Gets a DataSnapshot for the location at the specified relative path.
*/
child(childPath: string): FirebaseDataSnapshot;
/**
* Enumerates through the DataSnapshots children (in the default order).
*/
forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => void): boolean;
forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => boolean): boolean;
/**
* Returns true if the specified child exists.
*/
hasChild(childPath: string): boolean;
/**
* Returns true if the DataSnapshot has any children.
*/
hasChildren(): boolean;
/**
* Gets the key name of the location that generated this DataSnapshot.
*/
key(): string;
/**
* @deprecated Use key() instead.
* Gets the key name of the location that generated this DataSnapshot.
*/
name(): string;
/**
* Gets the number of children for this DataSnapshot.
*/
numChildren(): number;
/**
* Gets the Firebase reference for the location that generated this DataSnapshot.
*/
ref(): Firebase;
/**
* Gets the priority of the data in this DataSnapshot.
* @returns {string, number, null} The priority, or null if no priority was set.
*/
getPriority(): any; // string or number
/**
* Exports the entire contents of the DataSnapshot as a JavaScript object.
*/
exportVal(): Object;
}
interface IFirebaseOnDisconnect {
interface FirebaseOnDisconnect {
/**
* Ensures the data at this location is set to the specified value when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
set(value: any, onComplete?: (error: any) => void): void;
/**
* Ensures the data at this location is set to the specified value and priority when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void;
setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void;
update(value: any, onComplete?: (error: any) => void): void;
/**
* Writes the enumerated children at this Firebase location when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
update(value: Object, onComplete?: (error: any) => void): void;
/**
* Ensures the data at this location is deleted when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
remove(onComplete?: (error: any) => void): void;
/**
* Cancels all previously queued onDisconnect() set or update events for this location and all children.
*/
cancel(onComplete?: (error: any) => void): void;
}
interface IFirebaseQuery {
on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void;
off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void;
once(eventType: string, successCallback: (dataSnapshot: IFirebaseDataSnapshot) => void, failureCallback?: () => void, context?: Object): void;
limit(limit: number): IFirebaseQuery;
startAt(priority?: string, name?: string): IFirebaseQuery;
startAt(priority?: number, name?: string): IFirebaseQuery;
endAt(priority?: string, name?: string): IFirebaseQuery;
endAt(priority?: number, name?: string): IFirebaseQuery;
interface FirebaseQuery {
/**
* Listens for data changes at a particular location.
*/
on(eventType: string, callback: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: (error: any) => void, context?: Object): (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void;
/**
* Detaches a callback previously attached with on().
*/
off(eventType?: string, callback?: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void;
/**
* Listens for exactly one event of the specified event type, and then stops listening.
*/
once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, context?: Object): void;
once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, failureCallback?: (error: any) => void, context?: Object): void;
/**
* Generates a new Query object ordered by the specified child key.
*/
orderByChild(key: string): FirebaseQuery;
/**
* Generates a new Query object ordered by key name.
*/
orderByKey(): FirebaseQuery;
/**
* Generates a new Query object ordered by priority.
*/
orderByPriority(): FirebaseQuery;
/**
* @deprecated Use limitToFirst() and limitToLast() instead.
* Generates a new Query object limited to the specified number of children.
*/
limit(limit: number): FirebaseQuery;
/**
* Creates a Query with the specified starting point.
* The generated Query includes children which match the specified starting point.
*/
startAt(value: string, key?: string): FirebaseQuery;
startAt(value: number, key?: string): FirebaseQuery;
/**
* Creates a Query with the specified ending point.
* The generated Query includes children which match the specified ending point.
*/
endAt(value: string, key?: string): FirebaseQuery;
endAt(value: number, key?: string): FirebaseQuery;
/**
* Creates a Query which includes children which match the specified value.
*/
equalTo(value: string, key?: string): FirebaseQuery;
equalTo(value: number, key?: string): FirebaseQuery;
/**
* Generates a new Query object limited to the first certain number of children.
*/
limitToFirst(limit: number): FirebaseQuery;
/**
* Generates a new Query object limited to the last certain number of children.
*/
limitToLast(limit: number): FirebaseQuery;
/**
* Gets a Firebase reference to the Query's location.
*/
ref(): Firebase;
}
declare class Firebase implements IFirebaseQuery {
constructor(firebaseURL: string);
auth(authToken: string, onComplete?: (error: any, result: IFirebaseAuthResult) => void, onCancel?:(error: any) => void): void;
interface Firebase extends FirebaseQuery {
/**
* @deprecated Use authWithCustomToken() instead.
* Authenticates a Firebase client using the provided authentication token or Firebase Secret.
*/
auth(authToken: string, onComplete?: (error: any, result: FirebaseAuthResult) => void, onCancel?:(error: any) => void): void;
/**
* Authenticates a Firebase client using an authentication token or Firebase Secret.
*/
authWithCustomToken(autoToken: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?:Object): void;
/**
* Authenticates a Firebase client using a new, temporary guest account.
*/
authAnonymously(onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Authenticates a Firebase client using an email / password combination.
*/
authWithPassword(credentials: FirebaseCredentials, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Authenticates a Firebase client using a popup-based OAuth flow.
*/
authWithOAuthPopup(provider: string, onComplete:(error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Authenticates a Firebase client using a redirect-based OAuth flow.
*/
authWithOAuthRedirect(provider: string, onComplete: (error: any) => void, options?: Object): void;
/**
* Authenticates a Firebase client using OAuth access tokens or credentials.
*/
authWithOAuthToken(provider: string, credentials: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
authWithOAuthToken(provider: string, credentials: Object, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Synchronously access the current authentication state of the client.
*/
getAuth(): FirebaseAuthData;
/**
* Listen for changes to the client's authentication state.
*/
onAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void;
/**
* Detaches a callback previously attached with onAuth().
*/
offAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void;
/**
* Unauthenticates a Firebase client.
*/
unauth(): void;
/**
* Gets a Firebase reference for the location at the specified relative path.
*/
child(childPath: string): Firebase;
/**
* Gets a Firebase reference to the parent location.
*/
parent(): Firebase;
/**
* Gets a Firebase reference to the root of the Firebase.
*/
root(): Firebase;
/**
* Returns the last token in a Firebase location.
*/
key(): string;
/**
* @deprecated Use key() instead.
* Returns the last token in a Firebase location.
*/
name(): string;
/**
* Gets the absolute URL corresponding to this Firebase reference's location.
*/
toString(): string;
/**
* Writes data to this Firebase location.
*/
set(value: any, onComplete?: (error: any) => void): void;
update(value: any, onComplete?: (error: any) => void): void;
/**
* Writes the enumerated children to this Firebase location.
*/
update(value: Object, onComplete?: (error: any) => void): void;
/**
* Removes the data at this Firebase location.
*/
remove(onComplete?: (error: any) => void): void;
push(value: any, onComplete?: (error: any) => void): Firebase;
/**
* Generates a new child location using a unique name and returns a Firebase reference to it.
* @returns {Firebase} A Firebase reference for the generated location.
*/
push(value?: any, onComplete?: (error: any) => void): Firebase;
/**
* Writes data to this Firebase location. Like set() but also specifies the priority for that data.
*/
setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void;
setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void;
/**
* Sets a priority for the data at this Firebase location.
*/
setPriority(priority: string, onComplete?: (error: any) => void): void;
setPriority(priority: number, onComplete?: (error: any) => void): void;
transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: IFirebaseDataSnapshot) => void, applyLocally?: boolean): void;
onDisconnect(): IFirebaseOnDisconnect;
on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void;
off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void;
once(eventType: string, successCallback: (dataSnapshot: IFirebaseDataSnapshot) => void, failureCallback?: () => void, context?: Object): void;
limit(limit: number): IFirebaseQuery;
startAt(priority?: string, name?: string): IFirebaseQuery;
startAt(priority?: number, name?: string): IFirebaseQuery;
endAt(priority?: string, name?: string): IFirebaseQuery;
endAt(priority?: number, name?: string): IFirebaseQuery;
ref(): Firebase;
goOffline(): void;
goOnline(): void;
/**
* Atomically modifies the data at this location.
*/
transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: FirebaseDataSnapshot) => void, applyLocally?: boolean): void;
/**
* Creates a new user account using an email / password combination.
*/
createUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void;
/**
* Change the password of an existing user using an email / password combination.
*/
changePassword(credentials: { email: string; oldPassword: string; newPassword: string }, onComplete: (error: any) => void): void;
/**
* Removes an existing user account using an email / password combination.
*/
removeUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void;
/**
* Sends a password-reset email to the owner of the account, containing a token that may be used to authenticate and change the user password.
*/
resetPassword(credentials: { email: string }, onComplete: (error: any) => void): void;
onDisconnect(): FirebaseOnDisconnect;
}
interface FirebaseStatic {
/**
* Constructs a new Firebase reference from a full Firebase URL.
*/
new (firebaseURL: string): Firebase;
/**
* Manually disconnects the Firebase client from the server and disables automatic reconnection.
*/
goOffline(): void;
/**
* Manually reestablishes a connection to the Firebase server and enables automatic reconnection.
*/
goOnline(): void;
ServerValue: {
/**
* A placeholder value for auto-populating the current timestamp
* (time since the Unix epoch, in milliseconds) by the Firebase servers.
*/
TIMESTAMP: any;
};
}
declare var Firebase: FirebaseStatic;
// Reference: https://www.firebase.com/docs/web/api/firebase/getauth.html
interface FirebaseAuthData {
uid: string;
provider: string;
token: string;
expires: number;
auth: Object;
}
interface FirebaseCredentials {
email: string;
password: string;
}
+81
View File
@@ -0,0 +1,81 @@
/// <reference path="flux.d.ts" />
import flux = require('flux')
//
// Basic dispatcher usage
//
var basicDispatcher = new flux.Dispatcher<any>()
// register(callback: (payload: any) => void): string
var id: string = basicDispatcher.register((payload) => {
// payload is type: any
payload.anything
})
// unregister(id: string): void
basicDispatcher.unregister(id)
// waitFor(ids: string[]): void
basicDispatcher.waitFor([id])
// dispatch(payload: any): void
basicDispatcher.dispatch({ msg: 'hello' })
// isDispatching(): boolean
var dispatcherIsDispatching: boolean = basicDispatcher.isDispatching()
//
// Typed payload
//
enum ActionSource { Server, View }
enum ActionType { Create, Update, Delete }
interface Action {
source: ActionSource
type: ActionType
data: Object
}
var typedDispatcher = new flux.Dispatcher<Action>()
var typedPayload: Action
var typedStore = {
dispatcherID: typedDispatcher.register((payload) => {
typedPayload = payload
})
}
typedDispatcher.dispatch(typedPayload)
//
// Derived dispatcher
//
class CustomDispatcher extends flux.Dispatcher<Action> {
// Dispatch an action with server as source
handleServerAction(type: ActionType, data: Object) {
this.dispatch({
source: ActionSource.Server,
type: type,
data: data,
})
}
// Dispatch an action with view as source
handleViewAction(type: ActionType, data: Object) {
this.dispatch({
source: ActionSource.View,
type: type,
data: data,
})
}
}
var customDispatcher = new CustomDispatcher()
export = customDispatcher
+63
View File
@@ -0,0 +1,63 @@
// Type definitions for Flux
// Project: http://facebook.github.io/flux/
// Definitions by: Steve Baker <https://github.com/stkb/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'flux' {
/**
* Dispatcher class
* Create an instance to use throughout the application.
* Or extend it to create a derived dispatcher class.
*
* Specify a type in the 'TPayload' generic argument to use strongly-typed payloads,
* otherwise specify 'any'
*
* Examples:
* var dispatcher = new flux.Dispatcher<any>()
* var typedDispatcher = new flux.Dispatcher<MyCustomActionType>()
* class DerivedDispatcher extends flux.Dispatcher<MyCustomActionType> { }
*/
export class Dispatcher<TPayload> {
/**
* Create an instance of the Dispatcher class to use throughout the application.
*
* Specify a type in the 'TPayload' generic argument to use strongly-typed payloads,
* otherwise specify 'any'
*
* Examples:
* var dispatcher = new flux.Dispatcher<any>()
* var typedDispatcher = new flux.Dispatcher<MyCustomActionType>()
*/
constructor()
/**
* Registers a callback that will be invoked with every payload sent to the dispatcher.
* Returns a string token to identify the callback to be used with waitFor() or unregister.
*/
register(callback: (payload: TPayload) => void): string
/**
* Unregisters a callback with the given ID token
*/
unregister(id: string): void
/**
* Waits for the callbacks with the specified IDs to be invoked before continuing execution
* of the current callback. This method should only be used by a callback in response
* to a dispatched payload.
*/
waitFor(IDs: string[]): void
/**
* Dispatches a payload to all registered callbacks
*/
dispatch(payload: TPayload): void
/**
* Gets whether the dispatcher is currently dispatching
*/
isDispatching(): boolean
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for fibers
// Type definitions for form-data
// Project: https://github.com/felixge/node-form-data
// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+8 -8
View File
@@ -19,22 +19,22 @@
};
(()=>{
window.addEventListener('GamepadConnected', (e: GamepadEvent)=>{
window.addEventListener('GamepadConnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('GamepadDisconnected', (e: GamepadEvent)=>{
window.addEventListener('GamepadDisconnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
window.addEventListener('webkitGamepadConnected', (e: GamepadEvent)=>{
window.addEventListener('webkitGamepadConnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('webkitGamepadDisconnected', (e: GamepadEvent)=>{
window.addEventListener('webkitGamepadDisconnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
window.addEventListener('mozGamepadConnected', (e: GamepadEvent)=>{
window.addEventListener('mozGamepadConnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('mozGamepadDisconnected', (e: GamepadEvent)=>{
window.addEventListener('mozGamepadDisconnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
@@ -45,9 +45,9 @@
{
requestAnimationFrame.call(window, runAnimation);
var gamepads: GamepadList = getGamepads.call(navigator);
var gamepads: Gamepad.GamepadList = getGamepads.call(navigator);
for(var i = 0; i < gamepads.length; i++){
var pad: Gamepad = gamepads[i];
var pad: Gamepad.Gamepad = gamepads[i];
if(pad){
for (var k = 0; k < pad.buttons.length; k++)
{
+57 -53
View File
@@ -3,55 +3,69 @@
// Definitions by: Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* This interface defines an individual gamepad device.
*/
interface Gamepad{
declare module Gamepad{
/**
* An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID.
* @readonly
* This interface defines an individual gamepad device.
*/
id:string;
/**
* The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused.
* @readonly
*/
index:number;
export interface Gamepad{
/**
* An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID.
* @readonly
*/
id:string;
/**
* The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused.
* @readonly
*/
index:number;
/**
* Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp.
* @readonly
*/
timestamp:number;
/**
* Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick.
* @readonly
*/
axes:number[];
/**
* Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array.
* @readonly
*/
buttons:number[];
}
/**
* Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp.
* @readonly
*
*/
timestamp:number;
export interface GamepadEvent extends Event{
/**
* The single gamepad attribute provides access to the associated gamepad data for this event.
* @readonly
*/
gamepad:Gamepad;
}
/**
* Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick.
* @readonly
export interface GamepadList{
[index: number]: Gamepad;
length: number;
}
/*
* @event gamepadconnected
* A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis.
*/
axes:number[];
/**
* Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array.
* @readonly
/*
* @event gamepaddisconnected
* When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched.
*/
buttons:number[];
}
/**
*
*/
interface GamepadEvent extends Event{
/**
* The single gamepad attribute provides access to the associated gamepad data for this event.
* @readonly
*/
gamepad:Gamepad;
}
interface GamepadList{
[index: number]: Gamepad;
length: number;
}
interface Navigator{
@@ -59,20 +73,10 @@ interface Navigator{
* The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices.
* @readonly
*/
getGamepads(): Gamepad[];
getGamepads(): Gamepad.Gamepad[];
webkitGetGamepads(): Gamepad.GamepadList;
webkitGetGamepads(): GamepadList;
// Not supported yet :(
// mozGetGamepads(): Gamepad[];
}
/*
* @event gamepadconnected
* A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis.
*/
/*
* @event gamepaddisconnected
* When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched.
*/
+50
View File
@@ -0,0 +1,50 @@
///<reference path="glidejs.d.ts" />
///<reference path="../jquery/jquery.d.ts" />
// Copied from documentation
$('.slider').glide();
$('.slider').glide({
autoplay: 5000,
arrows: 'body',
navigation: 'body'
});
var glide: JQueryGlide.IGlideApi = $('.slider').glide().data('api_glide');
// Original line modified: glide.jump(3, console.log('Wooo!'));
glide.jump(3, function () { console.log('Wooo!'); });
// The rest of tests
glide.current();
glide.reinit();
glide.destroy();
glide.play();
glide.pause();
glide.next(function () { });
glide.prev(function () { });
glide.nav("div");
glide.arrows("div");
$(".slider").glide({ autoplay: 4000 });
$(".slider").glide({ hoverpause: true });
$(".slider").glide({ circular: true });
$(".slider").glide({ animationDuration: 500 });
$(".slider").glide({ animationTimingFunc: "cubic - bezier(0.165, 0.840, 0.440, 1.000)" });
$(".slider").glide({ arrows: true });
$(".slider").glide({ arrowsWrapperClass: "slider__arrows" });
$(".slider").glide({ arrowMainClass: "slider__arrows-item" });
$(".slider").glide({ arrowRightClass: "slider__arrows-item--right" });
$(".slider").glide({ arrowLeftClass: "slider__arrows-item--left" });
$(".slider").glide({ arrowRightText: "next" });
$(".slider").glide({ arrowLeftText: "prev" });
$(".slider").glide({ navigation: true });
$(".slider").glide({ navigationCenter: true });
$(".slider").glide({ navigationClass: "slider__nav" });
$(".slider").glide({ navigationItemClass: "slider__nav-item" });
$(".slider").glide({ navigationCurrentItemClass: "slider__nav-item--current" });
$(".slider").glide({ keyboard: true });
$(".slider").glide({ touchDistance: 60 });
$(".slider").glide({ beforeInit: function () { } });
$(".slider").glide({ afterInit: function () { } });
$(".slider").glide({ beforeTransition: function () { } });
$(".slider").glide({ afterTransition: function () { } });
+189
View File
@@ -0,0 +1,189 @@
// Type definitions for Glide.js v1.0.6
// Project: http://glide.jedrzejchalubek.com/
// Definitions by: Milan Jaros <https://github.com/milanjaros/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface JQuery {
/**
* Glide is responsive and touch-friendly jQuery slider.
* Based on CSS3 transitions with fallback to older broswers.
* It's simple, lightweight and fast. Designed to slide,
* no less, no more.
*/
glide(options?: JQueryGlide.IGlideOptions): JQuery;
}
declare module JQueryGlide {
interface IGlideOptions {
/**
* Default: 4000
* {Int or Bool} False for turning off autoplay
*/
autoplay?: any;
/**
* Default: true {Bool} Pause autoplay on mouseover slider
*/
hoverpause?: boolean;
/**
* Default: true {Bool} Circular play (Animation continues without starting over once it reaches the last slide)
*/
circular?: boolean;
/**
* Default: 500
* Animation time in ms
* @type {Int}
*/
animationDuration?: number;
/**
* Default: cubic-bezier(0.165, 0.840, 0.440, 1.000)
* cubic-bezier(0.165, 0.840, 0.440, 1.000)
*/
animationTimingFunc?: string;
/**
* Default: true
* {Bool or String} Show/hide/appendTo arrows
* True for append arrows to slider wrapper
* False for not appending arrows
* Id or class name (e.g. '.class-name') for appending to specific HTML markup
*/
arrows?: any;
/**
* Default: 'slider-arrows'
* {String} Arrows wrapper class
*/
arrowsWrapperClass?: string;
/**
* Default: 'slider-arrow'
* {String} Main class for both arrows
*/
arrowMainClass?: string;
/**
* Default: 'slider-arrow--right'
* {String} Right arrow
*/
arrowRightClass?: string;
/**
* Default: 'next'
* {String} Right arrow text
*/
arrowRightText?: string;
/**
* Default: 'slider-arrow--left'
* {String} Left arrow
*/
arrowLeftClass?: string;
/**
* Default: 'prev'
* {String} Left arrow text
*/
arrowLeftText?: string;
/**
* Default: true
* {Bool or String} Show/hide/appendTo bullets navigation
* True for append arrows to slider wrapper
* False for not appending arrows
* Id or class name (e.g. '.class-name') for appending to specific HTML markup
*/
navigation?: any;
/**
* Default: true
* {Bool} Center bullet navigation
*/
navigationCenter?: boolean;
/**
* Default: 'slider-nav'
* {String} Navigation class
*/
navigationClass?: string;
/**
* Default: 'slider-nav__item'
* {String} Navigation item class
*/
navigationItemClass?: string;
/**
* Default: 'slider-nav__item--current'
* {String} Current navigation item class
*/
navigationCurrentItemClass?: string;
/**
* Default: true
* {Bool} Slide on left / right keyboard arrows press
*/
keyboard?: boolean;
/**
* Default: 60
* {Int or Bool} Touch settings
*/
touchDistance?: any;
/**
* Default: function () {}
* {Function} Callback before plugin init
*/
beforeInit?: Function;
/**
* Default: function () {}
* {Function} Callback after plugin init
*/
afterInit?: Function;
/**
* Default: function () {}
* {Function} Callback before slide change
*/
beforeTransition?: Function;
/**
* Default: function() {}
* {Function} Callback after slide change
*/
afterTransition?: Function;
}
interface IGlideApi {
/**
* Returning current slide number
*/
current(): number;
/**
* Rebuild and recalculate dimensions of slider elements
*/
reinit(): void;
/**
* Destroy and cleanup slider
*/
destroy(): void;
/**
* Starting autoplay
*/
play(): void;
/**
* Stopping autoplay
*/
pause(): void;
/**
* Slide one forward
*/
next(callback: Function): void;
/**
* Slide one backward
*/
prev(callback: Function): void;
/**
* Jump to current slide
*/
jump(distance: number, callback: Function): void;
/**
* Append navigation to specifed target (eq. 'body', '.class', '#id')
*/
nav(target: string): void;
/**
* Append arrows to specifed target (eq. 'body', '.class', '#id')
*/
arrows(target: string): void;
}
}
+350
View File
@@ -0,0 +1,350 @@
/// <reference path="gm.d.ts" />
/// <reference path="../node/node.d.ts" />
import gm = require('gm');
import stream = require('stream');
var src: string;
var matrix: string;
var enable: boolean;
var ltr: boolean;
var password: string;
var bits: number;
var intensity: number;
var r: number;
var g: number;
var b: number;
var opacity: number;
var x: number;
var y: number;
var radius: number;
var sigma: number;
var width: number;
var height: number;
var color: string;
var channel: string;
var type: string;
var factor: number;
var numColors: number;
var operator: string;
var multiplier: number;
var kernel: string;
var usePercent: boolean;
var time: number;
var server: string;
var method: string;
var percent: number;
var encoding: string;
var options: string;
var file: string;
var distance: number;
var geometry: string;
var direction: string;
var name: string;
var offset: number;
var blackPoint: number;
var gamma: number;
var whitePoint: number;
var limit: string;
var format: string;
var iterations: number;
var count: number;
var b: number;
var s: number;
var h: number;
var dest: string;
var images: string[];
var angle: number;
var NxN: string;
var size: number;
var command: string;
var index: number;
var threshold: number;
var attribute: string;
var attrValue: string;
var format: string;
var font: string;
var quality: number;
var align: string;
var depth: number;
var readStream: stream.PassThrough;
gm(src)
.adjoin()
.affine(matrix)
.antialias(enable)
.append(src)
.append(src, ltr)
.authenticate(password)
.autoOrient()
.backdrop()
.bitdepth(bits)
.blackThreshold(intensity)
.blackThreshold(r, g, b)
.blackThreshold(r, g, b, opacity)
.bluePrimary(x, y)
.blur(radius)
.blur(radius, sigma)
.border(width, height)
.borderColor(color)
.box(color)
.channel(channel)
.charcoal(factor)
.chop(width, height)
.chop(width, height, x, y)
.clip()
.coalesce()
.colorize(r, g, b)
.colorMap(type)
.colors(numColors)
.colorspace(type)
.compose(operator)
.compress(type)
.contrast(multiplier)
.convolve(kernel)
.createDirectories()
.crop(width, height)
.crop(width, height, x, y)
.crop(width, height, x, y, usePercent)
.cycle(factor)
.deconstruct()
.define()
.delay(time)
.density(width, height)
.despeckle()
.displace(x, y)
.display(server)
.dispose(method)
.dissolve(percent)
.dither()
.dither(enable)
.edge()
.edge(radius)
.emboss()
.emboss(radius)
.encoding(encoding)
.endian(type)
.enhance()
.equalize()
.extent(width, height)
.extent(width, height, options)
.file(file)
.filter(type)
.flatten()
.flip()
.flop()
.foreground(color)
.frame(width, height, width, height)
.fuzz(distance)
.fuzz(distance, usePercent)
.gamma(r, b, g)
.gaussian(radius)
.gaussian(radius, sigma)
.geometry(width, height)
.geometry(width, height, options)
.geometry(geometry)
.greenPrimary(x, y)
.gravity(direction)
.highlightColor(color)
.highlightStyle(type)
.iconGeometry(geometry)
.implode()
.implode(factor)
.intent(type)
.interlace(type)
.label(name)
.lat(width, height, offset)
.lat(width, height, offset, usePercent)
.level(blackPoint, gamma, whitePoint)
.level(blackPoint, gamma, whitePoint, usePercent)
.limit(type, limit)
.list(type)
.log(format)
.loop(iterations)
.lower(width, height)
.magnify(factor)
.map(file)
.mask(file)
.matte()
.matteColor(color)
.maximumError(count)
.median()
.median(radius)
.minify(factor)
.mode(type)
.modulate(b, s, h)
.monitor()
.monochrome()
.morph(src, dest)
.morph(src, dest, (err, stdout, stderr, cmd) => {
})
.morph(images, dest)
.morph(images, dest, (err, stdout, stderr, cmd) => {
})
.mosaic()
.motionBlur(radius)
.motionBlur(radius, sigma)
.motionBlur(radius, sigma, angle)
.name()
.negative()
.noise(type)
.noise(radius)
.noop()
.normalize()
.opaque(color)
.operator(channel, operator, factor)
.operator(channel, operator, factor, usePercent)
.orderedDither(channel, NxN)
.outputDirectory(dest)
.page(width, height)
.page(width, height, options)
.pause(time)
.pen(color)
.ping()
.pointSize(size)
.noProfile()
.preview(type)
.paint(radius)
.process(command)
.profile(file)
.progress()
.randomThreshold(channel, NxN)
.quality(factor)
.raise(width, height)
.recolor(matrix)
.redPrimary(x, y)
.region(width, height)
.region(width, height, x, y)
.remote()
.render()
.repage('+')
.repage(width, height, x, y)
.repage(width, height, x, y, options)
.sample(geometry)
.samplingFactor(factor, factor)
.rawSize(width, height)
.rawSize(width, height, offset)
.resample(width, height)
.resize(width, height)
.resize(width, height, options)
.roll(x, y)
.rotate(color, angle)
.scene(index)
.scenes(index, index)
.scale(width, height)
.screen()
.segment(threshold, threshold)
.sepia()
.set(attribute, attrValue)
.setFormat(format)
.shade(angle, distance)
.shadow(radius)
.shadow(radius, sigma)
.sharedMemory()
.shave(width, height)
.shave(width, height, usePercent)
.sharpen(radius)
.sharpen(radius, sigma)
.shear(angle, angle)
.silent()
.snaps(count)
.solarize(threshold)
.spread(distance)
.stegano(offset)
.stereo()
.strip()
.swirl(angle)
.textFont(font)
.threshold(threshold)
.threshold(threshold, usePercent)
.thumb(width, height, dest, (err, stdout, stderr, cmd) => {
})
.thumb(width, height, dest, quality, (err, stdout, stderr, cmd) => {
})
.thumb(width, height, dest, quality, align, (err, stdout, stderr, cmd) => {
})
.tile(file)
.title(name)
.transform(color)
.transparent(color)
.treeDepth(depth)
.trim()
.type(type)
.update(time)
.units(type)
.unsharp(radius)
.unsharp(radius, sigma)
.unsharp(radius, sigma, factor)
.unsharp(radius, sigma, factor, threshold)
.usePixmap()
.view()
.virtualPixel(method)
.visual(type)
.watermark(b, s)
.wave(factor, distance)
.whitePoint(x, y)
.whiteThreshold(intensity)
.whiteThreshold(r, g, b)
.whiteThreshold(r, g, b, opacity)
.window(name)
.windowGroup()
.color((err, color) => {
})
.depth((err, bitdepth) => {
})
.filesize((err, size) => {
})
.format((err, format) => {
})
.identify((err, info) => {
})
.res((err, resolution) => {
})
.size((err, size) => {
})
.orientation((err, orient) => {
})
.draw(options)
.drawArc(x, y, x, y, radius, radius)
.drawBezier(x, y, x, y)
.drawBezier(x, y, x, y, x, y)
.drawBezier(x, y, x, y, x, y, x, y)
.drawCircle(x, y, x, y)
.drawEllipse(x, y, radius, radius, radius, radius)
.drawLine(x, y, x, y)
.drawPoint(x, y)
.drawPolygon(x, y, x, y, x, y)
.drawPolygon(x, y, x, y, x, y, x, y)
.drawPolyline(x, y, x, y, x, y)
.drawPolyline(x, y, x, y, x, y, x, y)
.drawRectangle(x, y, x, y)
.drawRectangle(x, y, x, y, radius)
.drawRectangle(x, y, x, y, radius, radius)
.drawText(x, y, name, direction)
.fill(color)
.font(font)
.font(font, size)
.fontSize(size)
.stroke(color)
.stroke(color, width)
.setDraw(type, x, y, method)
.write(dest, (err, stdout, stderr, cmd) => {
});
gm.compare(file, file, (err, isEqual, equality, raw) => {
});
readStream = gm(src).stream();
readStream = gm(src).stream(format);
readStream = gm(src).stream(format, (err, stdout, stderr, cmd) => {
});
gm(src).toBuffer((err, buffer) => {
});
gm(src).toBuffer(format, (err, buffer) => {
});
var imageMagick = gm.subClass({ imageMagick: true });
var readStream = imageMagick(src)
.adjoin()
.stream();
Vendored
+623
View File
@@ -0,0 +1,623 @@
// Type definitions for gm 1.17.0
// Project: https://github.com/aheckmann/gm
// Definitions by: Joel Spadin <https://github.com/ChaosinaCan>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module "gm" {
import stream = require('stream');
function m(image: string): m.State;
module m {
export interface ClassOptions {
imageMagick?: boolean;
}
export interface CompareCallback {
(err: Error, isEqual: boolean, equality: number, raw: number): any;
}
export interface GetterCallback<T> {
(err: Error, value: T): any;
}
export interface WriteCallback {
(err: Error, stdout: string, stderr: string, cmd: string): any;
}
export interface ChannelInfo<T> {
Red: T;
Green: T;
Blue: T;
}
export interface CompareOptions {
file?: string;
highlightColor?: string;
highlightStyle?: string;
tolerance?: number;
}
export interface ColorStatistics {
Minimum: string;
Maximum: string;
Mean: string;
'Standard Deviation': string;
}
export interface Dimensions {
width: number;
height: number;
}
export interface ImageInfo {
'Background Color': string;
'Border Color': string;
'Channel Depths': ChannelInfo<string>;
'Channel Statistics': ChannelInfo<ColorStatistics>;
Class: string;
color: number;
Compose: string;
Compression: string;
depth: number;
Depth: string;
Dispose: string;
Filesize: string;
format: string;
Format: string;
Geometry: string;
Interlace: string;
Iterations: string;
'JPEG-Quality'?: string;
'JPEG-Colorspace'?: string;
'JPEG-Colorspace-Name'?: string;
'JPEG-Sampling-factors'?: string;
'Matte Color': string;
Orientation: string;
'Page geometry': string;
path: string;
'Profile-color'?: string;
'Profile-iptc'?: {
[key: string]: string;
};
'Profile-EXIF'?: {
[key: string]: string;
};
'Profile-XMP'?: string;
Resolution?: string;
size: Dimensions;
Signature: string;
Software: string;
Tainted: string;
Type: string;
}
export interface State {
// Image Operations
adjoin(): State;
affine(matrix: string): State;
antialias(enable: boolean): State;
append(image: string, ltr?: boolean): State;
authenticate(password: string): State;
autoOrient(): State;
backdrop(): State;
bitdepth(bits: number): State;
blackThreshold(intensity: number): State;
blackThreshold(red: number, green: number, blue: number, opacity?: number): State;
bluePrimary(x: number, y: number): State;
blur(radius: number, sigma?: number): State;
border(width: number, height: number): State;
borderColor(color: string): State;
box(color: string): State;
channel(type: 'Red'): State;
channel(type: 'Green'): State;
channel(type: 'Blue'): State;
channel(type: 'Opacity'): State;
channel(type: 'Matte'): State;
channel(type: 'Cyan'): State;
channel(type: 'Magenta'): State;
channel(type: 'Yellow'): State;
channel(type: 'Black'): State;
channel(type: 'Gray'): State;
channel(type: string): State;
charcoal(factor: number): State;
chop(width: number, height: number, x?: number, y?: number): State;
clip(): State;
coalesce(): State;
colorize(red: number, green: number, blue: number): State;
colorMap(type: 'shared'): State;
colorMap(type: 'private'): State;
colorMap(type: string): State;
colors(colors: number): State;
colorspace(space: 'CineonLog'): State;
colorspace(space: 'CMYK'): State;
colorspace(space: 'GRAY'): State;
colorspace(space: 'HSL'): State;
colorspace(space: 'HSB'): State;
colorspace(space: 'OHTA'): State;
colorspace(space: 'RGB'): State;
colorspace(space: 'Rec601Luma'): State;
colorspace(space: 'Rec709Luma'): State;
colorspace(space: 'Rec601YCbCr'): State;
colorspace(space: 'Rec709YCbCr'): State;
colorspace(space: 'Transparent'): State;
colorspace(space: 'XYZ'): State;
colorspace(space: 'YCbCr'): State;
colorspace(space: 'YIQ'): State;
colorspace(space: 'YPbPr'): State;
colorspace(space: 'YUV'): State;
colorspace(space: string): State;
compose(operator: 'Over'): State;
compose(operator: 'In'): State;
compose(operator: 'Out'): State;
compose(operator: 'Atop'): State;
compose(operator: 'Xor'): State;
compose(operator: 'Plus'): State;
compose(operator: 'Minus'): State;
compose(operator: 'Add'): State;
compose(operator: 'Subtract'): State;
compose(operator: 'Difference'): State;
compose(operator: 'Divide'): State;
compose(operator: 'Multiply'): State;
compose(operator: 'Bumpmap'): State;
compose(operator: 'Copy'): State;
compose(operator: 'CopyRed'): State;
compose(operator: 'CopyGreen'): State;
compose(operator: 'CopyBlue'): State;
compose(operator: 'CopyOpacity'): State;
compose(operator: 'CopyCyan'): State;
compose(operator: 'CopyMagenta'): State;
compose(operator: 'CopyYellow'): State;
compose(operator: 'CopyBlack'): State;
compose(operator: string): State;
compress(type: 'None'): State;
compress(type: 'BZip'): State;
compress(type: 'Fax'): State;
compress(type: 'Group4'): State;
compress(type: 'JPEG'): State;
compress(type: 'Lossless'): State;
compress(type: 'LZW'): State;
compress(type: 'RLE'): State;
compress(type: 'Zip'): State;
compress(type: 'LZMA'): State;
compress(type: string): State;
contrast(multiplier: number): State;
convolve(kernel: string): State;
createDirectories(): State;
crop(width: number, height: number, x?: number, y?: number, percent?: boolean): State;
cycle(amount: number): State;
deconstruct(): State;
define(): State;
delay(milliseconds: number): State;
density(width: number, height: number): State;
despeckle(): State;
displace(horizontal: number, vertical: number): State;
display(xServer: string): State;
dispose(method: 'Undefined'): State;
dispose(method: 'None'): State;
dispose(method: 'Background'): State;
dispose(method: 'Previous'): State;
dispose(method: string): State;
dissolve(percent: number): State;
dither(enable?: boolean): State;
edge(radius?: number): State;
emboss(radius?: number): State;
encoding(encoding: 'AdobeCustom'): State;
encoding(encoding: 'AdobeExpert'): State;
encoding(encoding: 'AdobeStandard'): State;
encoding(encoding: 'AppleRoman'): State;
encoding(encoding: 'BIG5'): State;
encoding(encoding: 'GB2312'): State;
encoding(encoding: 'Latin 2'): State;
encoding(encoding: 'None'): State;
encoding(encoding: 'SJIScode'): State;
encoding(encoding: 'Symbol'): State;
encoding(encoding: 'Unicode'): State;
encoding(encoding: 'Wansung'): State;
encoding(encoding: string): State;
endian(type: 'MSB'): State;
endian(type: 'LSB'): State;
endian(type: 'Native'): State;
endian(type: string): State;
enhance(): State;
equalize(): State;
extent(width: number, height: number, options?: string): State;
file(filename: string): State;
filter(type: 'Point'): State;
filter(type: 'Box'): State;
filter(type: 'Triangle'): State;
filter(type: 'Hermite'): State;
filter(type: 'Hanning'): State;
filter(type: 'Hamming'): State;
filter(type: 'Blackman'): State;
filter(type: 'Gaussian'): State;
filter(type: 'Quadratic'): State;
filter(type: 'Cubic'): State;
filter(type: 'Catrom'): State;
filter(type: 'Mitchell'): State;
filter(type: 'Lanczos'): State;
filter(type: 'Bessel'): State;
filter(type: 'Sinc'): State;
filter(type: string): State;
flatten(): State;
flip(): State;
flop(): State;
foreground(color: string): State;
frame(width: number, height: number, outerBevelWidth: number, outBevelHeight: number): State;
fuzz(distance: number, percent?: boolean): State;
gamma(r: number, g: number, b: number): State;
gaussian(radius: number, sigma?: number): State;
/** Width and height are specified in percents */
geometry(width: number, height: number, option: '%'): State;
/** Specify maximum area in pixels */
geometry(width: number, height: number, option: '@'): State;
/** Ignore aspect ratio */
geometry(width: number, height: number, option: '!'): State;
/** Width and height are minimum values */
geometry(width: number, height: number, option: '^'): State;
/** Change dimensions only if image is smaller than width or height */
geometry(width: number, height: number, option: '<'): State;
/** Change dimensions only if image is larger than width or height */
geometry(width: number, height: number, option: '>'): State;
geometry(width: number, height?: number, option?: string): State;
geometry(geometry: string): State;
greenPrimary(x: number, y: number): State;
gravity(direction: 'NorthWest'): State;
gravity(direction: 'North'): State;
gravity(direction: 'NorthEast'): State;
gravity(direction: 'West'): State;
gravity(direction: 'Center'): State;
gravity(direction: 'East'): State;
gravity(direction: 'SouthWest'): State;
gravity(direction: 'South'): State;
gravity(direction: 'SouthEast'): State;
gravity(direction: string): State;
highlightColor(color: string): State;
highlightStyle(style: 'Assign'): State;
highlightStyle(style: 'Threshold'): State;
highlightStyle(style: 'Tint'): State;
highlightStyle(style: 'XOR'): State;
highlightStyle(style: string): State;
iconGeometry(geometry: string): State;
implode(factor?: number): State;
intent(type: 'Absolute'): State;
intent(type: 'Perceptual'): State;
intent(type: 'Relative'): State;
intent(type: 'Saturation'): State;
intent(type: string): State;
interlace(type: 'None'): State;
interlace(type: 'Line'): State;
interlace(type: 'Plane'): State;
interlace(type: 'Partition'): State;
interlace(type: string): State;
label(name: string): State;
lat(width: number, height: number, offset: number, percent?: boolean): State;
level(blackPoint: number, gamma: number, whitePoint: number, percent?: boolean): State;
limit(type: 'disk', val: string): State;
limit(type: 'file', val: string): State;
limit(type: 'map', val: string): State;
limit(type: 'memory', val: string): State;
limit(type: 'pixels', val: string): State;
limit(type: 'threads', val: string): State;
limit(type: string, val: string): State;
list(type: string): State;
list(type: 'Color'): State;
list(type: 'Delegate'): State;
list(type: 'Format'): State;
list(type: 'Magic'): State;
list(type: 'Module'): State;
list(type: 'Resource'): State;
list(type: 'Type'): State;
log(format: string): State;
loop(iterations: number): State;
lower(width: number, height: number): State;
magnify(factor: number): State;
map(filename: string): State;
mask(filename: string): State;
matte(): State;
matteColor(color: string): State;
maximumError(limit: number): State;
median(radius?: number): State;
minify(factor: number): State;
mode(mode: 'frame'): State;
mode(mode: 'unframe'): State;
mode(mode: 'concatenate'): State;
mode(mode: string): State;
modulate(b: number, s: number, h: number): State;
monitor(): State;
monochrome(): State;
morph(otherImg: string, outName: string, callback?: WriteCallback): State;
morph(otherImg: string[], outName: string, callback?: WriteCallback): State;
mosaic(): State;
motionBlur(radius: number, sigma?: number, angle?: number): State;
name(): State;
negative(): State;
noise(type: 'uniform'): State;
noise(type: 'gaussian'): State;
noise(type: 'multiplicative'): State;
noise(type: 'impulse'): State;
noise(type: 'laplacian'): State;
noise(type: 'poisson'): State;
noise(type: string): State;
noise(radius: number): State;
noop(): State;
normalize(): State;
opaque(color: string): State;
operator(channel: string, operator: 'Add', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'And', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Assign', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Depth', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Divide', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Gamma', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Negate', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'LShift', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Log', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Max', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Min', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Multiply', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Or', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Pow', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'RShift', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Subtract', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Threshold', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Threshold-White', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Threshold-White-Negate', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Threshold-Black', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Threshold-Black-Negate', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Xor', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Noise-Gaussian', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Noise-Impulse', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Noise-Laplacian', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Noise-Multiplicative', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Noise-Poisson', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Noise-Random', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: 'Noise-Uniform', rvalue: number, percent?: boolean): State;
operator(channel: string, operator: string, rvalue: number, percent?: boolean): State;
orderedDither(channelType: 'All', NxN: string): State;
orderedDither(channelType: 'Intensity', NxN: string): State;
orderedDither(channelType: 'Red', NxN: string): State;
orderedDither(channelType: 'Green', NxN: string): State;
orderedDither(channelType: 'Blue', NxN: string): State;
orderedDither(channelType: 'Cyan', NxN: string): State;
orderedDither(channelType: 'Magenta', NxN: string): State;
orderedDither(channelType: 'Yellow', NxN: string): State;
orderedDither(channelType: 'Black', NxN: string): State;
orderedDither(channelType: 'Opacity', NxN: string): State;
orderedDither(channelType: string, NxN: string): State;
outputDirectory(directory: string): State;
page(width: number, height: number, arg?: '%'): State;
page(width: number, height: number, arg?: '!'): State;
page(width: number, height: number, arg?: '<'): State;
page(width: number, height: number, arg?: '>'): State;
page(width: number, height: number, arg?: string): State;
pause(seconds: number): State;
pen(color: string): State;
ping(): State;
pointSize(size: number): State;
noProfile(): State;
preview(type: 'Rotate'): State;
preview(type: 'Shear'): State;
preview(type: 'Roll'): State;
preview(type: 'Hue'): State;
preview(type: 'Saturation'): State;
preview(type: 'Brightness'): State;
preview(type: 'Gamma'): State;
preview(type: 'Spiff'): State;
preview(type: 'Dull'): State;
preview(type: 'Grayscale'): State;
preview(type: 'Quantize'): State;
preview(type: 'Despeckle'): State;
preview(type: 'ReduceNoise'): State;
preview(type: 'AddNoise'): State;
preview(type: 'Sharpen'): State;
preview(type: 'Blur'): State;
preview(type: 'Threshold'): State;
preview(type: 'EdgeDetect'): State;
preview(type: 'Spread'): State;
preview(type: 'Shade'): State;
preview(type: 'Raise'): State;
preview(type: 'Segment'): State;
preview(type: 'Solarize'): State;
preview(type: 'Swirl'): State;
preview(type: 'Implode'): State;
preview(type: 'Wave'): State;
preview(type: 'OilPaint'): State;
preview(type: 'CharcoalDrawing'): State;
preview(type: 'JPEG'): State;
preview(type: string): State;
paint(radius: number): State;
process(command: string): State;
profile(filename: string): State;
progress(): State;
randomThreshold(channelType: 'All', LOWxHIGH: string): State;
randomThreshold(channelType: 'Intensity', LOWxHIGH: string): State;
randomThreshold(channelType: 'Red', LOWxHIGH: string): State;
randomThreshold(channelType: 'Green', LOWxHIGH: string): State;
randomThreshold(channelType: 'Blue', LOWxHIGH: string): State;
randomThreshold(channelType: 'Cyan', LOWxHIGH: string): State;
randomThreshold(channelType: 'Magenta', LOWxHIGH: string): State;
randomThreshold(channelType: 'Yellow', LOWxHIGH: string): State;
randomThreshold(channelType: 'Black', LOWxHIGH: string): State;
randomThreshold(channelType: 'Opacity', LOWxHIGH: string): State;
randomThreshold(channelType: string, LOWxHIGH: string): State;
quality(level: number): State;
raise(width: number, height: number): State;
recolor(matrix: string): State;
redPrimary(x: number, y: number): State;
region(width: number, height: number, x?: number, y?: number): State;
remote(): State;
render(): State;
repage(reset: '+'): State;
repage(reset: string): State;
repage(width: number, height: number, xoff: number, yoff: number, arg?: string): State;
sample(geometry: string): State;
samplingFactor(horizontalFactor: number, verticalFactor: number): State;
rawSize(width: number, height: number, offset?: number): State;
resample(horizontal: number, vertical: number): State;
/** Width and height are specified in percents */
resize(width: number, height: number, option: '%'): State;
/** Specify maximum area in pixels */
resize(width: number, height: number, option: '@'): State;
/** Ignore aspect ratio */
resize(width: number, height: number, option: '!'): State;
/** Width and height are minimum values */
resize(width: number, height: number, option: '^'): State;
/** Change dimensions only if image is smaller than width or height */
resize(width: number, height: number, option: '<'): State;
/** Change dimensions only if image is larger than width or height */
resize(width: number, height: number, option: '>'): State;
resize(width: number, height?: number, option?: string): State;
roll(horizontal: number, vertical: number): State;
rotate(backgroundColor: string, degrees: number): State;
scene(index: number): State;
scenes(start: number, end: number): State;
scale(width: number, height: number): State;
screen(): State;
segment(clustherThreshold: number, smoothingThreshold: number): State;
sepia(): State;
set(attribute: string, value: string): State;
setFormat(format: string): State;
shade(azimuth: number, elevation: number): State;
shadow(radius: number, sigma?: number): State;
sharedMemory(): State;
shave(width: number, height: number, percent?: boolean): State;
sharpen(radius: number, sigma?: number): State;
shear(xDegrees: number, yDegress: number): State;
silent(): State;
snaps(count: number): State;
solarize(threshold: number): State;
spread(amount: number): State;
stegano(offset: number): State;
stereo(): State;
strip(): State;
swirl(degrees: number): State;
textFont(font: string): State;
threshold(value: number, percent?: boolean): State;
thumb(width: number, height: number, outName: string, callback: WriteCallback): State;
thumb(width: number, height: number, outName: string, quality: number, callback: WriteCallback): State;
thumb(width: number, height: number, outName: string, quality: number, align: 'topleft', callback: WriteCallback): State;
thumb(width: number, height: number, outName: string, quality: number, align: 'center', callback: WriteCallback): State;
thumb(width: number, height: number, outName: string, quality: number, align: string, callback: WriteCallback): State;
tile(filename: string): State;
title(title: string): State;
transform(color: string): State;
transparent(color: string): State;
treeDepth(depth: number): State;
trim(): State;
type(type: 'Bilevel'): State;
type(type: 'Grayscale'): State;
type(type: 'Palette'): State;
type(type: 'PaletteMatte'): State;
type(type: 'TrueColor'): State;
type(type: 'TrueColorMatte'): State;
type(type: 'ColorSeparation'): State;
type(type: 'ColorSeparationMatte'): State;
type(type: 'Optimize'): State;
type(type: string): State;
update(seconds: number): State;
units(type: 'Undefined'): State;
units(type: 'PixelsPerInch'): State;
units(type: 'PixelsPerCentimeter'): State;
units(type: string): State;
unsharp(radius: number, sigma?: number, amount?: number, threshold?: number): State;
usePixmap(): State;
view(): State;
virtualPixel(method: 'Constant'): State;
virtualPixel(method: 'Edge'): State;
virtualPixel(method: 'Mirror'): State;
virtualPixel(method: 'Tile'): State;
virtualPixel(method: string): State;
visual(type: 'StaticGray'): State;
visual(type: 'GrayScale'): State;
visual(type: 'StaticColor'): State;
visual(type: 'PseudoColor'): State;
visual(type: 'TrueColor'): State;
visual(type: 'DirectColor'): State;
visual(type: 'default'): State;
visual(type: string): State;
watermark(brightness: number, saturation: number): State;
wave(amplitude: number, wavelength: number): State;
whitePoint(x: number, y: number): State;
whiteThreshold(intensity: number): State;
whiteThreshold(red: number, green: number, blue: number, opacity?: number): State;
window(id: string): State;
windowGroup(): State;
// Getters
color(callback: GetterCallback<number>): State;
depth(callback: GetterCallback<number>): State;
filesize(callback: GetterCallback<string>): State;
format(callback: GetterCallback<string>): State;
identify(callback: GetterCallback<ImageInfo>): State;
res(callback: GetterCallback<string>): State;
size(callback: GetterCallback<Dimensions>): State;
orientation(callback: GetterCallback<string>): State;
// Drawing Operations
draw(args: string): State;
drawArc(x0: number, y0: number, x1: number, y1: number, r0: number, r1: number): State;
drawBezier(x0: number, y0: number, x1: number, y1: number): State;
drawBezier(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): State;
drawBezier(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, ...coords: number[]): State;
drawCircle(x0: number, y0: number, x1: number, y1: number): State;
drawEllipse(x0: number, y0: number, rx: number, ry: number, a0: number, a1: number): State;
drawLine(x0: number, y0: number, x1: number, y1: number): State;
drawPoint(x: number, y: number): State;
drawPolygon(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): State;
drawPolygon(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, ...coords: number[]): State;
drawPolyline(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): State;
drawPolyline(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, ...coords: number[]): State;
drawRectangle(x0: number, y0: number, x1: number, y1: number): State;
drawRectangle(x0: number, y0: number, x1: number, y1: number, rc: number): State;
drawRectangle(x0: number, y0: number, x1: number, y1: number, wc: number, hc: number): State;
drawText(x: number, y: number, text: string, gravity: 'NorthWest'): State;
drawText(x: number, y: number, text: string, gravity: 'North'): State;
drawText(x: number, y: number, text: string, gravity: 'NorthEast'): State;
drawText(x: number, y: number, text: string, gravity: 'West'): State;
drawText(x: number, y: number, text: string, gravity: 'Center'): State;
drawText(x: number, y: number, text: string, gravity: 'East'): State;
drawText(x: number, y: number, text: string, gravity: 'SouthWest'): State;
drawText(x: number, y: number, text: string, gravity: 'South'): State;
drawText(x: number, y: number, text: string, gravity: 'SouthEast'): State;
drawText(x: number, y: number, text: string, gravity?: string): State;
fill(color: string): State;
font(name: string, size?: number): State;
fontSize(size: number): State;
stroke(color: string, width?: number): State;
strokeWidth(width: number): State;
setDraw(property: 'color', x: number, y: number, method: 'point'): State;
setDraw(property: 'color', x: number, y: number, method: 'replace'): State;
setDraw(property: 'color', x: number, y: number, method: 'floodfill'): State;
setDraw(property: 'color', x: number, y: number, method: 'filltoborder'): State;
setDraw(property: 'color', x: number, y: number, method: 'reset'): State;
setDraw(property: 'matte', x: number, y: number, method: 'point'): State;
setDraw(property: 'matte', x: number, y: number, method: 'replace'): State;
setDraw(property: 'matte', x: number, y: number, method: 'floodfill'): State;
setDraw(property: 'matte', x: number, y: number, method: 'filltoborder'): State;
setDraw(property: 'matte', x: number, y: number, method: 'reset'): State;
setDraw(property: string, x: number, y: number, method: string): State;
// Commands
stream(callback?: WriteCallback): stream.PassThrough;
stream(format: string, callback?: WriteCallback): stream.PassThrough;
toBuffer(callback: (err: Error, buffer: Buffer) => any): stream.PassThrough;
toBuffer(format: string, callback: (err: Error, buffer: Buffer) => any): stream.PassThrough;
write(filename: string, callback: WriteCallback): void;
}
export interface SubClass {
(image: string): State;
}
export function compare(filename1: string, filename2: string, callback: CompareCallback): void;
export function compare(filename1: string, filename2: string, tolerance: number, callback: CompareCallback): void;
export function compare(filename1: string, filename2: string, options: CompareOptions, callback: CompareCallback): void;
export function subClass(options: ClassOptions): SubClass;
}
export = m;
}
+7 -7
View File
@@ -1574,13 +1574,13 @@ declare module google.maps {
}
export interface HeatmapLayerOptions {
data: LatLng[];
dissipating: boolean;
gradient: string[];
map: Map;
maxIntensity: number;
opacity: number;
radius: number;
data: any;
dissipating?: boolean;
gradient?: string[];
map?: Map;
maxIntensity?: number;
opacity?: number;
radius?: number;
}
export interface WeightedLocation {
+49
View File
@@ -0,0 +1,49 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="hammerjs-1.1.3.d.ts" />
// plugin check
if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) {
Hammer.plugins.fakeMultitouch();
Hammer.plugins.showTouches();
}
// instance method check
var el = document.getElementById("container");
Hammer(el).on("doubletap", function () {
alert('you doubletapped me!');
});
var hammertime = Hammer(el, {
drag: false,
transform: false
}).off("tap", function (event:HammerEvent) {
alert('hello!');
});
hammertime.enable(false);
hammertime.on("touch drag transform", function (ev: HammerEvent) {
if (!ev.gesture) {
return;
}
if (ev.gesture.deltaX >= 20) {
hammertime.trigger("swipe", ev.gesture);
}
});
// jQuery check
$("#element")
.hammer({
// Options
})
.on("tap", function (ev) {
console.log(ev);
});
$("#container").hammer({
prevent_default: false,
drag_block_vertical: false
}).on("hold tap doubletap transformstart transform transformend dragstart drag dragend release swipe", function (ev) {
});
+142
View File
@@ -0,0 +1,142 @@
// Type definitions for Hammer.js 1.1.3
// Project: http://eightmedia.github.com/hammer.js/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Drew Noakes <https://drewnoakes.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
declare var Hammer: HammerStatic;
interface HammerStatic {
(element: any, options?: HammerOptions): HammerInstance;
VERSION: number;
HAS_POINTEREVENTS: boolean;
HAS_TOUCHEVENTS: boolean;
UPDATE_VELOCITY_INTERVAL: number;
POINTER_MOUSE: HammerPointerType;
POINTER_TOUCH: HammerPointerType;
POINTER_PEN: HammerPointerType;
DIRECTION_UP: HammerDirectionType;
DIRECTION_DOWN: HammerDirectionType;
DIRECTION_LEFT: HammerDirectionType;
DIRECTION_RIGH: HammerDirectionType;
EVENT_START: HammerTouchEventState;
EVENT_MOVE: HammerTouchEventState;
EVENT_END: HammerTouchEventState;
plugins: any;
gestures: any;
READY: boolean;
}
declare class HammerInstance {
constructor(element: any, options?: HammerOptions);
on(gesture: string, handler: (event: HammerEvent) => void): HammerInstance;
off(gesture: string, handler: (event: HammerEvent) => void): HammerInstance;
enable(toggle: boolean): HammerInstance;
// You shouldn't normally use this internal method. Only use it when you know what you're doing! You can read the sourcecode for information about how to use this.
trigger(gesture: string, eventData: HammerGestureEventData): HammerInstance;
}
// Gesture Options : https://github.com/EightMedia/hammer.js/wiki/Getting-Started#gesture-options
interface HammerOptions {
behavior?: {
contentZooming?: string;
tapHighlightColor?: string;
touchAction?: string;
touchCallout?: string;
userDrag?: string;
userSelect?: string;
};
doubleTapDistance?: number;
doubleTapInterval?: number;
drag?: boolean;
dragBlockHorizontal?: boolean;
dragBlockVertical?: boolean;
dragDistanceCorrection?: boolean;
dragLockMinDistance?: number;
dragLockToAxis?: boolean;
dragMaxTouches?: number;
dragMinDistance?: number;
gesture?: boolean;
hold?: boolean;
holdThreshold?: number;
holdTimeout?: number;
preventDefault?: boolean;
preventMouse?: boolean;
release?: boolean;
showTouches?: boolean;
swipe?: boolean;
swipeMaxTouches?: number;
swipeMinTouches?: number;
swipeVelocityX?: number;
swipeVelocityY?: number;
tap?: boolean;
tapAlways?: boolean;
tapMaxDistance?: number;
tapMaxTime?: number;
touch?: boolean;
transform?: boolean;
transformMinRotation?: number;
transformMinScale?: number;
}
interface HammerGestureEventData {
timestamp: number;
target: HTMLElement;
touches: HammerPoint[];
pointerType: HammerPointerType;
center: HammerPoint;
deltaTime: number;
deltaX: number;
deltaY: number;
velocityX: number;
velocityY: number;
angle: number;
interimAngle: number;
direction: HammerDirectionType;
interimDirection: HammerDirectionType;
distance: number;
scale: number;
rotation: number;
eventType: HammerTouchEventState;
srcEvent: any;
startEvent: any;
stopPropagation(): void;
preventDefault(): void;
stopDetect(): void;
}
interface HammerPoint {
clientX: number;
clientY: number;
pageX: number;
pageY: number;
}
interface HammerEvent {
type: string;
gesture: HammerGestureEventData;
stopPropagation(): void;
preventDefault(): void;
}
declare enum HammerPointerType {
}
declare enum HammerDirectionType {
}
declare enum HammerTouchEventState {
}
interface JQuery {
hammer(options?: HammerOptions): JQuery;
}
+115 -49
View File
@@ -1,49 +1,115 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="hammerjs.d.ts" />
// plugin check
if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) {
Hammer.plugins.fakeMultitouch();
Hammer.plugins.showTouches();
}
// instance method check
var el = document.getElementById("container");
Hammer(el).on("doubletap", function () {
alert('you doubletapped me!');
});
var hammertime = Hammer(el, {
drag: false,
transform: false
}).off("tap", function (event:HammerEvent) {
alert('hello!');
});
hammertime.enable(false);
hammertime.on("touch drag transform", function (ev: HammerEvent) {
if (!ev.gesture) {
return;
}
if (ev.gesture.deltaX >= 20) {
hammertime.trigger("swipe", ev.gesture);
}
});
// jQuery check
$("#element")
.hammer({
// Options
})
.on("tap", function (ev) {
console.log(ev);
});
$("#container").hammer({
prevent_default: false,
drag_block_vertical: false
}).on("hold tap doubletap transformstart transform transformend dragstart drag dragend release swipe", function (ev) {
});
// Tests based on examples at http://hammerjs.github.io/examples/
/// <reference path="hammerjs.d.ts" />
(() =>
{
var myElement = document.getElementById( 'myElement' );
// create a simple instance
// by default, it only adds horizontal recognizers
var mc = new Hammer( myElement );
// listen to events...
mc.on( "panleft panright tap press", function ( ev )
{
myElement.textContent = ev.type + " gesture detected.";
} );
})();
(() =>
{
var myElement = document.getElementById( 'myElement' );
// create a simple instance
// by default, it only adds horizontal recognizers
var mc = new Hammer( myElement );
// let the pan gesture support all directions.
// this will block the vertical scrolling on a touch-device while on the element
mc.get( 'pan' ).set( {direction: Hammer.DIRECTION_ALL} );
// listen to events...
mc.on( "panleft panright panup pandown tap press", function ( ev:HammerInput )
{
myElement.textContent = ev.type + " gesture detected.";
} );
})();
(() =>
{
var myElement = document.getElementById( 'myElement' );
var mc = new Hammer.Manager( myElement );
// create a pinch and rotate recognizer
// these require 2 pointers
var pinch = new Hammer.Pinch();
var rotate = new Hammer.Rotate();
// we want to detect both the same time
pinch.recognizeWith( rotate );
// add to the Manager
mc.add( [pinch, rotate] );
mc.on( "pinch rotate", function ( ev:HammerInput )
{
myElement.textContent += ev.type + " ";
} );
})();
(() =>
{
var myElement = document.getElementById( 'myElement' );
// We create a manager object, which is the same as Hammer(), but without the presetted recognizers.
var mc = new Hammer.Manager( myElement );
// Default, tap recognizer
mc.add( new Hammer.Tap() );
// Tap recognizer with minimal 4 taps
mc.add( new Hammer.Tap( {event: 'quadrupletap', taps: 4} ) );
// we want to recognize this simulatenous, so a quadrupletap will be detected even while a tap has been recognized.
// the tap event will be emitted on every tap
mc.get( 'quadrupletap' ).recognizeWith( 'tap' );
mc.on( "tap quadrupletap", function ( ev )
{
myElement.textContent += ev.type + " ";
} );
})();
(() =>
{
var myElement = document.getElementById( 'myElement' );
// We create a manager object, which is the same as Hammer(), but without the presetted recognizers.
var mc = new Hammer.Manager( myElement );
// Tap recognizer with minimal 2 taps
mc.add( new Hammer.Tap( {event: 'doubletap', taps: 2} ) );
// Single tap recognizer
mc.add( new Hammer.Tap( {event: 'singletap'} ) );
// we want to recognize this simulatenous, so a quadrupletap will be detected even while a tap has been recognized.
mc.get( 'doubletap' ).recognizeWith( 'singletap' );
// we only want to trigger a tap, when we don't have detected a doubletap
mc.get( 'singletap' ).requireFailure( 'doubletap' );
mc.on( "singletap doubletap", function ( ev )
{
myElement.textContent += ev.type + " ";
} );
})();
+327 -142
View File
@@ -1,142 +1,327 @@
// Type definitions for Hammer.js 1.1.3
// Project: http://eightmedia.github.com/hammer.js/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Drew Noakes <https://drewnoakes.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
declare var Hammer: HammerStatic;
interface HammerStatic {
(element: any, options?: HammerOptions): HammerInstance;
VERSION: number;
HAS_POINTEREVENTS: boolean;
HAS_TOUCHEVENTS: boolean;
UPDATE_VELOCITY_INTERVAL: number;
POINTER_MOUSE: HammerPointerType;
POINTER_TOUCH: HammerPointerType;
POINTER_PEN: HammerPointerType;
DIRECTION_UP: HammerDirectionType;
DIRECTION_DOWN: HammerDirectionType;
DIRECTION_LEFT: HammerDirectionType;
DIRECTION_RIGH: HammerDirectionType;
EVENT_START: HammerTouchEventState;
EVENT_MOVE: HammerTouchEventState;
EVENT_END: HammerTouchEventState;
plugins: any;
gestures: any;
READY: boolean;
}
declare class HammerInstance {
constructor(element: any, options?: HammerOptions);
on(gesture: string, handler: (event: HammerEvent) => void): HammerInstance;
off(gesture: string, handler: (event: HammerEvent) => void): HammerInstance;
enable(toggle: boolean): HammerInstance;
// You shouldn't normally use this internal method. Only use it when you know what you're doing! You can read the sourcecode for information about how to use this.
trigger(gesture: string, eventData: HammerGestureEventData): HammerInstance;
}
// Gesture Options : https://github.com/EightMedia/hammer.js/wiki/Getting-Started#gesture-options
interface HammerOptions {
behavior?: {
contentZooming?: string;
tapHighlightColor?: string;
touchAction?: string;
touchCallout?: string;
userDrag?: string;
userSelect?: string;
};
doubleTapDistance?: number;
doubleTapInterval?: number;
drag?: boolean;
dragBlockHorizontal?: boolean;
dragBlockVertical?: boolean;
dragDistanceCorrection?: boolean;
dragLockMinDistance?: number;
dragLockToAxis?: boolean;
dragMaxTouches?: number;
dragMinDistance?: number;
gesture?: boolean;
hold?: boolean;
holdThreshold?: number;
holdTimeout?: number;
preventDefault?: boolean;
preventMouse?: boolean;
release?: boolean;
showTouches?: boolean;
swipe?: boolean;
swipeMaxTouches?: number;
swipeMinTouches?: number;
swipeVelocityX?: number;
swipeVelocityY?: number;
tap?: boolean;
tapAlways?: boolean;
tapMaxDistance?: number;
tapMaxTime?: number;
touch?: boolean;
transform?: boolean;
transformMinRotation?: number;
transformMinScale?: number;
}
interface HammerGestureEventData {
timestamp: number;
target: HTMLElement;
touches: HammerPoint[];
pointerType: HammerPointerType;
center: HammerPoint;
deltaTime: number;
deltaX: number;
deltaY: number;
velocityX: number;
velocityY: number;
angle: number;
interimAngle: number;
direction: HammerDirectionType;
interimDirection: HammerDirectionType;
distance: number;
scale: number;
rotation: number;
eventType: HammerTouchEventState;
srcEvent: any;
startEvent: any;
stopPropagation(): void;
preventDefault(): void;
stopDetect(): void;
}
interface HammerPoint {
clientX: number;
clientY: number;
pageX: number;
pageY: number;
}
interface HammerEvent {
type: string;
gesture: HammerGestureEventData;
stopPropagation(): void;
preventDefault(): void;
}
declare enum HammerPointerType {
}
declare enum HammerDirectionType {
}
declare enum HammerTouchEventState {
}
interface JQuery {
hammer(options?: HammerOptions): JQuery;
}
// Type definitions for Hammer.js 2.0.4
// Project: http://hammerjs.github.io/
// Definitions by: Philip Bulley <https://github.com/milkisevil/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var Hammer:HammerStatic;
interface HammerStatic
{
new( element:HTMLElement, options?:any ): HammerManager;
defaults:HammerDefaults;
VERSION: number;
INPUT_START: number;
INPUT_MOVE: number;
INPUT_END: number;
INPUT_CANCEL: number;
STATE_POSSIBLE: number;
STATE_BEGAN: number;
STATE_CHANGED: number;
STATE_ENDED: number;
STATE_RECOGNIZED: number;
STATE_CANCELLED: number;
STATE_FAILED: number;
DIRECTION_NONE: number;
DIRECTION_LEFT: number;
DIRECTION_RIGHT: number;
DIRECTION_UP: number;
DIRECTION_DOWN: number;
DIRECTION_HORIZONTAL: number;
DIRECTION_VERTICAL: number;
DIRECTION_ALL: number;
Manager: HammerManager;
Input: HammerInput;
TouchAction: TouchAction;
TouchInput: TouchInput;
MouseInput: MouseInput;
PointerEventInput: PointerEventInput;
TouchMouseInput: TouchMouseInput;
SingleTouchInput: SingleTouchInput;
Recognizer: RecognizerStatic;
AttrRecognizer: AttrRecognizerStatic;
Tap: TapRecognizerStatic;
Pan: PanRecognizerStatic;
Swipe: SwipeRecognizerStatic;
Pinch: PinchRecognizerStatic;
Rotate: RotateRecognizerStatic;
Press: PressRecognizerStatic;
on( target:EventTarget, types:string, handler:Function ):void;
off( target:EventTarget, types:string, handler:Function ):void;
each( obj:any, iterator:Function, context:any ): void;
merge( dest:any, src:any ): any;
extend( dest:any, src:any, merge:boolean ): any;
inherit( child:Function, base:Function, properties:any ):any;
bindFn( fn:Function, context:any ):Function;
prefixed( obj:any, property:string ):string;
}
interface HammerDefaults
{
domEvents:boolean;
enable:boolean;
preset:any[];
touchAction:string;
cssProps:CssProps;
inputClass():void;
inputTarget():void;
}
interface CssProps
{
contentZooming:string;
tapHighlightColor:string;
touchCallout:string;
touchSelect:string;
userDrag:string;
userSelect:string;
}
interface HammerOptions extends HammerDefaults
{
}
interface HammerManager
{
new( element:HTMLElement, options?:any ):HammerManager;
add( recogniser:Recognizer ):Recognizer;
add( recogniser:Recognizer ):HammerManager;
add( recogniser:Recognizer[] ):Recognizer;
add( recogniser:Recognizer[] ):HammerManager;
destroy():void;
emit( event:string, data:any ):void;
get( recogniser:Recognizer ):Recognizer;
get( recogniser:string ):Recognizer;
off( events:string, handler:( event:HammerInput ) => void ):void;
on( events:string, handler:( event:HammerInput ) => void ):void;
recognize( inputData:any ):void;
remove( recogniser:Recognizer ):HammerManager;
remove( recogniser:string ):HammerManager;
set( options:HammerOptions ):HammerManager;
stop( force:boolean ):void;
}
declare class HammerInput
{
constructor( manager:HammerManager, callback:Function );
destroy():void;
handler():void;
init():void;
/** Name of the event. Like panstart. */
type:string;
/** Movement of the X axis. */
deltaX:number;
/** Movement of the Y axis. */
deltaY:number;
/** Total time in ms since the first input. */
deltaTime:number;
/** Distance moved. */
distance:number;
/** Angle moved. */
angle:number;
/** Velocity on the X axis, in px/ms. */
velocityX:number;
/** Velocity on the Y axis, in px/ms */
velocityY:number;
/** Highest velocityX/Y value. */
velocity:number;
/** Direction moved. Matches the DIRECTION constants. */
direction:number;
/** Direction moved from it's starting point. Matches the DIRECTION constants. */
offsetDirection:string;
/** Scaling that has been done when multi-touch. 1 on a single touch. */
scale:number;
/** Rotation that has been done when multi-touch. 0 on a single touch. */
rotation:number;
/** Center position for multi-touch, or just the single pointer. */
center:HammerPoint;
/** Source event object, type TouchEvent, MouseEvent or PointerEvent. */
srcEvent:Event; // TODO: Update to Union Type (TouchEvent | MouseEvent | PointerEvent) if it lands in TS1.4
/** Target that received the event. */
target:HTMLElement;
/** Primary pointer type, could be touch, mouse, pen or kinect. */
pointerType:string;
/** Event type, matches the INPUT constants. */
eventType:string;
/** true when the first input. */
isFirst:boolean;
/** true when the final (last) input. */
isFinal:boolean;
/** Array with all pointers, including the ended pointers (touchend, mouseup). */
pointers:any[];
/** Array with all new/moved/lost pointers. */
changedPointers:any[];
/** Reference to the srcEvent.preventDefault() method. Only for experts! */
preventDefault:Function;
}
declare class MouseInput extends HammerInput
{
constructor( manager:HammerManager, callback:Function );
}
declare class PointerEventInput extends HammerInput
{
constructor( manager:HammerManager, callback:Function );
}
declare class SingleTouchInput extends HammerInput
{
constructor( manager:HammerManager, callback:Function );
}
declare class TouchInput extends HammerInput
{
constructor( manager:HammerManager, callback:Function );
}
declare class TouchMouseInput extends HammerInput
{
constructor( manager:HammerManager, callback:Function );
}
interface RecognizerStatic
{
new( options?:any ):Recognizer;
}
interface Recognizer
{
defaults:any;
canEmit():boolean;
canRecognizeWith( otherRecognizer:Recognizer ):boolean;
dropRecognizeWith( otherRecognizer:Recognizer ):Recognizer;
dropRecognizeWith( otherRecognizer:string ):Recognizer;
dropRequireFailure( otherRecognizer:Recognizer ):Recognizer;
dropRequireFailure( otherRecognizer:string ):Recognizer;
emit( input:HammerInput ):void;
getTouchAction():any[];
hasRequireFailures():boolean;
process( inputData:HammerInput ):string;
recognize( inputData:HammerInput ):void;
recognizeWith( otherRecognizer:Recognizer ):Recognizer;
recognizeWith( otherRecognizer:string ):Recognizer;
requireFailure( otherRecognizer:Recognizer ):Recognizer;
requireFailure( otherRecognizer:string ):Recognizer;
reset():void;
set( options?:any ):Recognizer;
tryEmit( input:HammerInput ):void;
}
interface AttrRecognizerStatic
{
attrTest( input:HammerInput ):boolean;
process( input:HammerInput ):any;
}
interface AttrRecognizer extends Recognizer
{
new( options?:any ):AttrRecognizer;
}
interface PanRecognizerStatic
{
new( options?:any ):PanRecognizer;
}
interface PanRecognizer extends AttrRecognizer
{
}
interface PinchRecognizerStatic
{
new( options?:any ):PinchRecognizer;
}
interface PinchRecognizer extends AttrRecognizer
{
}
interface PressRecognizerStatic
{
new( options?:any ):PressRecognizer;
}
interface PressRecognizer extends AttrRecognizer
{
}
interface RotateRecognizerStatic
{
new( options?:any ):RotateRecognizer;
}
interface RotateRecognizer extends AttrRecognizer
{
}
interface SwipeRecognizerStatic
{
new( options?:any ):SwipeRecognizer;
}
interface SwipeRecognizer
{
}
interface TapRecognizerStatic
{
new( options?:any ):TapRecognizer;
}
interface TapRecognizer extends AttrRecognizer
{
}
declare class TouchAction
{
constructor( manager:HammerManager, value:string );
compute():string;
preventDefaults( input:HammerInput ):void;
preventSrc( srcEvent:any ):void;
set( value:string ):void;
update():void;
}
interface HammerPoint
{
x: number;
y: number;
}
+30
View File
@@ -25,6 +25,36 @@ server.pack.register([plugin], (err: Object) => {
if (err) { throw err; }
});
// Add server method
var add = function (a: number, b: number, next: (err: any, result?: any, ttl?: number) => void) {
next(null, a + b);
};
server.method('sum', add, { cache: { expiresIn: 2000 } });
server.methods.sum(4, 5, (err: any, result: any) => {
console.log(result);
});
var addArray = function (array: Array<number>, next: (err: any, result?: any, ttl?: number) => void) {
var sum: number = 0;
array.forEach((item: number) => {
sum += item;
});
next(null, sum);
};
server.method('sumObj', addArray, {
cache: { expiresIn: 2000 },
generateKey: (array: Array<number>) => {
return array.join(',');
}
});
server.methods.sumObj([5, 6], (err: any, result: any) => {
console.log(result);
});
// Add the route
server.route({
method: 'GET',

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