Merge remote-tracking branch 'refs/remotes/DefinitelyTyped/master'

This commit is contained in:
Kasidit Iamthong
2016-07-04 03:47:31 +07:00
436 changed files with 98739 additions and 21836 deletions
+9
View File
@@ -1,5 +1,14 @@
/// <reference path="FileSaver.d.ts" />
import {saveAs as importedSaveAs} from "file-saver";
function testImportedSaveAs() {
var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
var filename: string = 'hello world.txt';
var disableAutoBOM = true;
importedSaveAs(data, filename, disableAutoBOM);
}
/**
* @summary Test for "saveAs" function.
*/
+6 -1
View File
@@ -15,7 +15,7 @@ interface FileSaver {
* @type {Blob}
*/
data: Blob,
/**
* @summary File name.
* @type {DOMString}
@@ -31,3 +31,8 @@ interface FileSaver {
}
declare var saveAs: FileSaver;
declare module "file-saver" {
var fileSaver: { saveAs: typeof saveAs };
export = fileSaver
}
+2 -2
View File
@@ -24,7 +24,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi
* Directly from the GitHub repos
* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped)
* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd)
* [Typings - TypeScript Definition Manager](https://github.com/typings/typings)
## List of definitions
@@ -32,7 +32,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi
## Requested definitions
Here is are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
## License
+2 -3
View File
@@ -77,9 +77,6 @@ declare namespace AceAjax {
onTextInput(text: any): void;
}
var KeyBinding: {
new(editor: Editor): KeyBinding;
}
export interface TextMode {
@@ -1037,6 +1034,8 @@ declare namespace AceAjax {
**/
export interface Editor {
on(ev: string, callback: (e: any) => any): void;
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void;
addEventListener(ev: string, callback: Function): void;
+3
View File
@@ -5,6 +5,9 @@ var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
editor.on("blur", (e) => e);
editor.on("change", (e) => e);
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/javascript");
+8
View File
@@ -12,4 +12,12 @@ var config : adal.Config = {
var auth = new AuthenticationContext(config);
Logging.log = (message: string) => {
console.log(message);
}
Logging.level = 4;
auth.info("Logging message");
var userName: string = auth.getCachedUser().userName;
+16 -3
View File
@@ -4,9 +4,10 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var AuthenticationContext: adal.AuthenticationContextStatic;
declare var Logging: adal.Logging;
declare module 'adal' {
export = AuthenticationContext;
export = { AuthenticationContext, Logging };
}
declare namespace adal {
@@ -36,6 +37,18 @@ declare namespace adal {
stateResponse: string,
requestType: string
}
interface Logging {
log: (message: string) => void;
level: LoggingLevel;
}
enum LoggingLevel {
ERROR = 0,
WARNING = 1,
INFO = 2,
VERBOSE = 3
}
interface AuthenticationContextStatic {
new (config: Config): AuthenticationContext;
@@ -118,9 +131,9 @@ declare namespace adal {
/**
* Gets requestInfo from given hash.
* @returns {string} error message related to login
* @returns {RequestInfo} for appropriate hash.
*/
getRequestInfo(hash: string): string;
getRequestInfo(hash: string): RequestInfo;
/**
* Saves token from hash that is received from redirect.
+279 -281
View File
@@ -19,277 +19,6 @@ declare module "agenda" {
(err?: Error, result?: T): void;
}
/**
* Agenda Configuration.
*/
interface AgendaConfiguration {
/**
* Sets the interval with which the queue is checked. A number in milliseconds or a frequency string.
*/
processEvery?: string | number;
/**
* Takes a number which specifies the default number of a specific job that can be running at any given moment.
* By default it is 5.
*/
defaultConcurrency?: number;
/**
* Takes a number which specifies the max number of jobs that can be running at any given moment. By default it
* is 20.
*/
maxConcurrency?: number;
/**
* Takes a number which specifies the default number of a specific job that can be locked at any given moment.
* By default it is 0 for no max.
*/
defaultLockLimit?: number;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
*/
lockLimit?: number;
/**
* Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This
* can be overridden by specifying the lockLifetime option to a defined job.
*/
defaultLockLifetime?: number;
/**
* Specifies that Agenda should be initialized using and existing MongoDB connection.
*/
mongo?: {
/**
* The MongoDB database connection to use.
*/
db: Db;
/**
* The name of the collection to use.
*/
collection?: string;
}
/**
* Specifies that Agenda should connect to MongoDB.
*/
db?: {
/**
* The connection URL.
*/
address: string;
/**
* The name of the collection to use.
*/
collection?: string;
/**
* Connection options to pass to MongoDB.
*/
options?: any;
}
}
/**
* The database record associated with a job.
*/
interface JobAttributes {
/**
* The record identity.
*/
_id: ObjectID;
/**
* The name of the job.
*/
name: string;
/**
* The type of the job (single|normal).
*/
type: string;
/**
* The job details.
*/
data: { [name: string]: any };
/**
* The priority of the job.
*/
priority: number;
/**
* How often the job is repeated using a human-readable or cron format.
*/
repeatInterval: string | number;
/**
* The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/).
*/
repeatTimezone: string;
/**
* Date/time the job was las modified.
*/
lastModifiedBy: string;
/**
* Date/time the job will run next.
*/
nextRunAt: Date;
/**
* Date/time the job was locked.
*/
lockedAt: Date;
/**
* Date/time the job was last run.
*/
lastRunAt: Date;
/**
* Date/time the job last finished running.
*/
lastFinishedAt: Date;
/**
* The reason the job failed.
*/
failReason: string;
/**
* The number of times the job has failed.
*/
failCount: number;
/**
* The date/time the job last failed.
*/
failedAt: Date;
}
/**
* A scheduled job.
*/
interface Job {
/**
* The database record associated with the job.
*/
attrs: JobAttributes;
/**
* Specifies an interval on which the job should repeat.
* @param interval A human-readable format String, a cron format String, or a Number.
* @param options An optional argument that can include a timezone field. The timezone should be a string as
* accepted by moment-timezone and is considered when using an interval in the cron string format.
*/
repeatEvery(interval: string | number, options?: { timezone?: string }): Job
/**
* Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples).
* @param time
*/
repeatAt(time: string): Job
/**
* Disables the job.
*/
disable(): Job;
/**
* Enables the job.
*/
enable(): Job;
/**
* Ensure that only one instance of this job exists with the specified properties
* @param value The properties associated with the job that must be unqiue.
* @param opts
*/
unique(value: any, opts?: { insertOnly?: boolean }): Job;
/**
* Specifies the next time at which the job should run.
* @param time The next time at which the job should run.
*/
schedule(time: string | Date): Job;
/**
* Specifies the priority weighting of the job.
* @param value The priority of the job (lowest|low|normal|high|highest|number).
*/
priority(value: string | number): Job;
/**
* Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.
* @param reason A message or Error object that indicates why the job failed.
*/
fail(reason: string | Error): Job;
/**
* Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually
* @param cb Called when the job is completed.
*/
run(cb?: ResultCallback<Job>): Job;
/**
* Returns true if the job is running; otherwise, returns false.
*/
isRunning(): boolean;
/**
* Saves the job into the database.
* @param cb Called when the job is saved.
*/
save(cb?: ResultCallback<Job>): Job;
/**
* Removes the job from the database and cancels the job.
* @param cb Called after the job has beeb removed from the database.
*/
remove(cb?: Callback): void;
/**
* Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running
* jobs.
* @param cb Called after the job has been saved to the database.
*/
touch(cb?: Callback): void;
}
interface JobOptions {
/**
* Maximum number of that job that can be running at once (per instance of agenda)
*/
concurrency?: number;
/**
* Maximum number of that job that can be locked at once (per instance of agenda)
*/
lockLimit?: number;
/**
* Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will
* automatically unlock if done() is called.
*/
lockLifetime?: number;
/**
* (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run
* first.
*/
priority?: string | number;
}
class Agenda extends EventEmitter {
/**
@@ -297,7 +26,7 @@ declare module "agenda" {
* @param config Optional configuration to initialize the Agenda.
* @param cb Optional callback called with the MongoDB colleciton.
*/
constructor(config?: AgendaConfiguration, cb?: ResultCallback<Collection>);
constructor(config?: Agenda.AgendaConfiguration, cb?: ResultCallback<Collection>);
/**
* Connect to the specified MongoDB server and database.
@@ -360,14 +89,14 @@ declare module "agenda" {
* @param name The name of the job.
* @param data Data to associated with the job.
*/
create(name: string, data?: any): Job;
create(name: string, data?: any): Agenda.Job;
/**
* Find all Jobs matching `query` and pass same back in cb().
* @param query
* @param cb
*/
jobs(query: any, cb: ResultCallback<Job[]>): void;
jobs(query: any, cb: ResultCallback<Agenda.Job[]>): void;
/**
* Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want
@@ -384,8 +113,8 @@ declare module "agenda" {
* @param options The options for the job.
* @param handler The handler to execute.
*/
define(name: string, handler: (job?: Job, done?: (err?: Error) => void) => void): void;
define(name: string, options: JobOptions, handler: (job?: Job, done?: (err?: Error) => void) => void): void;
define(name: string, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
define(name: string, options: Agenda.JobOptions, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
/**
* Runs job name at the given interval. Optionally, data and options can be passed in.
@@ -395,8 +124,8 @@ declare module "agenda" {
* @param options An optional argument that will be passed to job.repeatEvery.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback<Job>): Job;
every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback<Job[]>): Job[];
every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
/**
* Schedules a job to run name once at a given time.
@@ -405,8 +134,8 @@ declare module "agenda" {
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback<Job>): Job;
schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback<Job[]>): Job[];
schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
/**
* Schedules a job to run name once immediately.
@@ -414,7 +143,7 @@ declare module "agenda" {
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
now(name: string, data?: any, cb?: ResultCallback<Job>): Job;
now(name: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
/**
* Cancels any jobs matching the passed mongodb-native query, and removes them from the database.
@@ -436,7 +165,276 @@ declare module "agenda" {
}
namespace Agenda {
/**
* Agenda Configuration.
*/
interface AgendaConfiguration {
/**
* Sets the interval with which the queue is checked. A number in milliseconds or a frequency string.
*/
processEvery?: string | number;
/**
* Takes a number which specifies the default number of a specific job that can be running at any given moment.
* By default it is 5.
*/
defaultConcurrency?: number;
/**
* Takes a number which specifies the max number of jobs that can be running at any given moment. By default it
* is 20.
*/
maxConcurrency?: number;
/**
* Takes a number which specifies the default number of a specific job that can be locked at any given moment.
* By default it is 0 for no max.
*/
defaultLockLimit?: number;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
*/
lockLimit?: number;
/**
* Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This
* can be overridden by specifying the lockLifetime option to a defined job.
*/
defaultLockLifetime?: number;
/**
* Specifies that Agenda should be initialized using and existing MongoDB connection.
*/
mongo?: {
/**
* The MongoDB database connection to use.
*/
db: Db;
/**
* The name of the collection to use.
*/
collection?: string;
}
/**
* Specifies that Agenda should connect to MongoDB.
*/
db?: {
/**
* The connection URL.
*/
address: string;
/**
* The name of the collection to use.
*/
collection?: string;
/**
* Connection options to pass to MongoDB.
*/
options?: any;
}
}
/**
* The database record associated with a job.
*/
interface JobAttributes {
/**
* The record identity.
*/
_id: ObjectID;
/**
* The name of the job.
*/
name: string;
/**
* The type of the job (single|normal).
*/
type: string;
/**
* The job details.
*/
data: { [name: string]: any };
/**
* The priority of the job.
*/
priority: number;
/**
* How often the job is repeated using a human-readable or cron format.
*/
repeatInterval: string | number;
/**
* The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/).
*/
repeatTimezone: string;
/**
* Date/time the job was las modified.
*/
lastModifiedBy: string;
/**
* Date/time the job will run next.
*/
nextRunAt: Date;
/**
* Date/time the job was locked.
*/
lockedAt: Date;
/**
* Date/time the job was last run.
*/
lastRunAt: Date;
/**
* Date/time the job last finished running.
*/
lastFinishedAt: Date;
/**
* The reason the job failed.
*/
failReason: string;
/**
* The number of times the job has failed.
*/
failCount: number;
/**
* The date/time the job last failed.
*/
failedAt: Date;
}
/**
* A scheduled job.
*/
interface Job {
/**
* The database record associated with the job.
*/
attrs: JobAttributes;
/**
* Specifies an interval on which the job should repeat.
* @param interval A human-readable format String, a cron format String, or a Number.
* @param options An optional argument that can include a timezone field. The timezone should be a string as
* accepted by moment-timezone and is considered when using an interval in the cron string format.
*/
repeatEvery(interval: string | number, options?: { timezone?: string }): Job
/**
* Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples).
* @param time
*/
repeatAt(time: string): Job
/**
* Disables the job.
*/
disable(): Job;
/**
* Enables the job.
*/
enable(): Job;
/**
* Ensure that only one instance of this job exists with the specified properties
* @param value The properties associated with the job that must be unqiue.
* @param opts
*/
unique(value: any, opts?: { insertOnly?: boolean }): Job;
/**
* Specifies the next time at which the job should run.
* @param time The next time at which the job should run.
*/
schedule(time: string | Date): Job;
/**
* Specifies the priority weighting of the job.
* @param value The priority of the job (lowest|low|normal|high|highest|number).
*/
priority(value: string | number): Job;
/**
* Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.
* @param reason A message or Error object that indicates why the job failed.
*/
fail(reason: string | Error): Job;
/**
* Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually
* @param cb Called when the job is completed.
*/
run(cb?: ResultCallback<Job>): Job;
/**
* Returns true if the job is running; otherwise, returns false.
*/
isRunning(): boolean;
/**
* Saves the job into the database.
* @param cb Called when the job is saved.
*/
save(cb?: ResultCallback<Job>): Job;
/**
* Removes the job from the database and cancels the job.
* @param cb Called after the job has beeb removed from the database.
*/
remove(cb?: Callback): void;
/**
* Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running
* jobs.
* @param cb Called after the job has been saved to the database.
*/
touch(cb?: Callback): void;
}
interface JobOptions {
/**
* Maximum number of that job that can be running at once (per instance of agenda)
*/
concurrency?: number;
/**
* Maximum number of that job that can be locked at once (per instance of agenda)
*/
lockLimit?: number;
/**
* Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will
* automatically unlock if done() is called.
*/
lockLifetime?: number;
/**
* (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run
* first.
*/
priority?: string | number;
}
}
export = Agenda;
@@ -67,6 +67,16 @@ myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().placeholder('Prompt input placeholder text'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().initialValue('Buddy'));
};
$scope['prerenderedDialog'] = () => {
$mdDialog.show({
template: '<md-dialog>Hello!</md-dialog>',
contentElement: '#myDialog',
clickOutsideToClose: true
});
};
$scope['hideDialog'] = $mdDialog.hide.bind($mdDialog, 'hide');
$scope['cancelDialog'] = $mdDialog.cancel.bind($mdDialog, 'cancel');
});
@@ -110,3 +120,51 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!'));
});
myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => {
$scope['createPanel'] = () => {
var config = {
template: '<h1>Hello!</h1>',
hasBackdrop: true,
disableParentScroll: true,
zIndex: 150
};
$mdPanel.create(config);
var panelRef = $mdPanel.create(config);
panelRef.open()
.then((ref: ng.material.IPanelRef) => {
ref.addClass('foo');
ref.removeClass('bar');
ref.close();
})
.finally(() => {
panelRef = undefined;
});
};
$scope['openPanel'] = () => {
$mdPanel.open({
template: '<h1>Hello!</h1>',
hasBackdrop: true,
disableParentScroll: true,
zIndex: 150
})
.then((panelRef: ng.material.IPanelRef) => {
panelRef.addClass('foo');
panelRef.removeClass('bar');
panelRef.close();
});
};
$scope['newPanelPosition'] = () => {
$mdPanel.newPanelPosition().absolute().center();
$mdPanel.newPanelPosition().relativeTo('.demo-menu-open-button').addPanelPosition("ALIGN_START", "BELOW");
};
$scope['newPanelAnimation'] = () => {
$mdPanel.newPanelAnimation().openFrom('.some-target');
$mdPanel.newPanelAnimation().openFrom({top: 0, left: 0});
};
});
+81 -6
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Matt Traynham <https://github.com/mtraynham>
// Definitions by: Alex Staroselsky <https://github.com/AlStar01>, Blake Bigelow <https://github.com/blbigelow>, Peter Hajdu <https://github.com/PeterHajdu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
@@ -65,15 +65,17 @@ declare namespace angular.material {
interface IConfirmDialog extends IPresetDialog<IConfirmDialog> {
cancel(cancel: string): IConfirmDialog;
}
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
cancel(cancel: string): IPromptDialog;
placeholder(placeholder: string): IPromptDialog;
placeholder(placeholder: string): IPromptDialog;
initialValue(initialValue: string): IPromptDialog;
}
interface IDialogOptions {
templateUrl?: string;
template?: string;
contentElement?: string|Element;
autoWrap?: boolean; // default: true
targetEvent?: MouseEvent;
openFrom?: any;
@@ -81,7 +83,7 @@ declare namespace angular.material {
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
disableParentScroll?: boolean; // default: true
hasBackdrop?: boolean // default: true
hasBackdrop?: boolean; // default: true
clickOutsideToClose?: boolean; // default: false
escapeToClose?: boolean; // default: true
focusOnOpen?: boolean; // default: true
@@ -94,11 +96,12 @@ declare namespace angular.material {
onShowing?: Function;
onComplete?: Function;
onRemoving?: Function;
fullscreen?: boolean;
skipHide?: boolean;
fullscreen?: boolean; // default: false
}
interface IDialogService {
show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise<any>;
show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog|IPromptDialog): angular.IPromise<any>;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
prompt(): IPromptDialog;
@@ -283,4 +286,76 @@ declare namespace angular.material {
grey: IPalette;
'blue-grey': IPalette;
}
interface IPanelConfig {
template?: string;
templateUrl?: string;
controller?: string|Function;
controllerAs?: string;
bindToController?: boolean; // default: true
locals?: {[index: string]: any};
resolve?: {[index: string]: angular.IPromise<any>}
attachTo?: string|JQuery|Element;
panelClass?: string;
zIndex?: number; // default: 80
position?: IPanelPosition;
clickOutsideToClose?: boolean; // default: false
escapeToClose?: boolean; // default: false
trapFocus?: boolean; // default: false
focusOnOpen?: boolean; // default: true
fullscreen?: boolean; // default: false
animation?: IPanelAnimation;
hasBackdrop?: boolean; // default: false
disableParentScroll?: boolean; // default: false
onDomAdded?: Function;
onOpenComplete?: Function;
onRemoving?: Function;
onDomRemoved?: Function;
origin?: string|JQuery|Element;
}
interface IPanelRef {
id: string;
config: IPanelConfig;
isAttached: boolean;
open(): angular.IPromise<any>;
close(): angular.IPromise<any>;
attach(): angular.IPromise<any>;
detach(): angular.IPromise<any>;
show(): angular.IPromise<any>;
hide(): angular.IPromise<any>;
destroy(): void;
addClass(newClass: string): void;
removeClass(oldClass: string): void;
toggleClass(toggleClass: string): void;
focusOnOpen(): void;
}
interface IPanelPosition {
absolute(): IPanelPosition;
relativeTo(someElement: string|JQuery|Element): IPanelPosition;
top(opt_top: string): IPanelPosition; // default: '0'
bottom(opt_bottom: string): IPanelPosition; // default: '0'
left(opt_left: string): IPanelPosition; // default: '0'
right(opt_right: string): IPanelPosition; // default: '0'
centerHorizontally(): IPanelPosition;
centerVertically(): IPanelPosition;
center(): IPanelPosition;
addPanelPosition(xPosition: string, yPosition: string): IPanelPosition;
withOffsetX(offsetX: string): IPanelPosition;
withOffsetY(offsetY: string): IPanelPosition;
}
interface IPanelAnimation {
openFrom(from: string|Element|Event|{top: number, left: number}): IPanelAnimation;
closeTo(to: string|Element|{top: number, left: number}): IPanelAnimation;
withAnimation(cssClass: string|{open: string, close: string}): IPanelAnimation;
}
interface IPanelService {
create(opt_config: IPanelConfig): IPanelRef;
open(opt_config: IPanelConfig): angular.IPromise<IPanelRef>;
newPanelPosition(): IPanelPosition;
newPanelAnimation(): IPanelAnimation;
}
}
@@ -0,0 +1,42 @@
///<reference path="angular-q-spread.d.ts"/>
interface IMyService {
getFirstname(): ng.IPromise<string>;
getLastname(): ng.IPromise<string>;
}
interface IScope {
name: string;
}
function TestCtrl($scope: IScope, $q: ng.IQService, MyService: IMyService) {
$scope.name = null;
function firstCallback(firstname: string, lastname: string)
{
return firstname + ' ' + lastname;
}
function anotherCallback(fullname: string)
{
$scope.name = fullname;
}
function failureCallback(reason: any)
{
alert('Could not load data: ' + reason);
}
$q
.all([
MyService.getFirstname(),
MyService.getLastname()
])
.spread(firstCallback)
.then(anotherCallback)
.catch(failureCallback);
};
TestCtrl.$inject = ['$scope', '$q', 'MyService'];
angular.module('test').controller('TestCtrl', TestCtrl);
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for angular-q-spread module
// Project: https://www.npmjs.com/package/angular-q-spread
// Definitions by: rafw87 <https://github.com/rafw87>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular {
interface IPromise<T> {
/**
This method can be used as a replacement for then. Similarly, it takes two parameters, a callback when all promises are resolved and a callback for failure. The resolve callback is going to be called with the result of the list of promises passed to $q.all as separate parameters instead of one parameters which is an array.
* @param successCallback Callback for resolved promise, similar to then's one, but takes multiple parameters instead of single array parameter
* @param errorCallback Callback for error, the same as for then
*/
spread<TResult>(successCallback: (...promiseValues: any[]) => IPromise<TResult>|TResult, errorCallback?: (reason: any) => any): IPromise<TResult>;
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ declare namespace angular.translate {
}
interface ITranslateProvider extends angular.IServiceProvider {
translations(): ITranslationTable;
translations(key?: string): ITranslationTable;
translations(key: string, translationTable: ITranslationTable): ITranslateProvider;
cloakClassName(): string;
cloakClassName(name: string): ITranslateProvider;
@@ -0,0 +1,71 @@
/// <reference path="angular-websocket.d.ts" />
let dummySocket: ng.websocket.IWebSocket;
let dummyPromise: ng.IPromise<void>;
let dummyScope: ng.IScope;
let provider: ng.websocket.IWebSocketProvider = (url: string, protocols?:string[] | ng.websocket.IWebSocketConfigOptions, options?: ng.websocket.IWebSocketConfigOptions) => {
return dummySocket;
}
let socketWithProtocol = provider("wss://localhost", "protocol");
let socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]);
let socketWithOptions = provider("wss://localhost", {
scope: dummyScope,
rootScopeFailOver: true,
useApplyAsync: true,
initialTimeout: 100,
maxTimeout: 300000,
reconnectIfNotNormalClose: true,
binaryType: "blob"
});
let socketWithProtocolAndOptions = provider("wss://localhost", "protocol", {
scope: dummyScope,
rootScopeFailOver: true,
useApplyAsync: true,
initialTimeout: 100,
maxTimeout: 300000,
reconnectIfNotNormalClose: true,
binaryType: "blob"
});
let socket = provider("wss://localhost");
socket.onOpen((event) => {})
.onClose((event) => {})
.onError((event) => {})
.onMessage((event) => {});
socket.onMessage((event) => {}, { filter: /Some Filter/ })
.onMessage((event) => {}, { filter: 'Some Filter' })
.onMessage((event) => {}, { filter: 'Some Filter', autoApply: true })
.onMessage((event) => {}, { autoApply: false });
socket.close(true);
socket.close();
socket.send("Some great data here!").finally(() => {});
socket.send({ list: [1, 2, 3, 4] });
socket.socket.send("data");
socket.socket.close();
socket.socket.close(1);
socket.socket.close(1, "reason");
socket.sendQueue.push({ message: "msg", defered: dummyPromise });
socket.onOpenCallbacks.push((event: Event) => {});
socket.onCloseCallbacks.push((event: CloseEvent) => {});
socket.onErrorCallbacks.push((event: Event) => {});
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: 'Some Filter', autoApply: true });
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: /Some Filter/, autoApply: true });
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: undefined, autoApply: true });
socket.readyState = 0;
socket.initialTimeout = 10;
socket.maxTimeout = 5000;
+157
View File
@@ -0,0 +1,157 @@
// Type definitions for angular-websocket v2.0
// Project: https://github.com/AngularClass/angular-websocket
// Definitions by: Nick Veys <https://github.com/nickveys>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path='../angularjs/angular.d.ts' />
declare namespace angular.websocket {
/**
* Options available to be specified for IWebSocketProvider.
*/
type IWebSocketConfigOptions = {
scope?: ng.IScope;
rootScopeFailOver?: boolean;
useApplyAsync?: boolean;
initialTimeout?: number;
maxTimeout?: number;
binaryType?: "blob" | "arraybuffer";
reconnectIfNotNormalClose?: boolean;
}
interface IWebSocketProvider {
/**
* Creates and opens an IWebSocket instance.
*
* @param url url to connect to
* @return websocket instance
*/
(url: string, protocols?: string | string[] | IWebSocketConfigOptions, options?: IWebSocketConfigOptions): IWebSocket;
}
/** Options available to be specified for IWebSocket.onMessage */
type IWebSocketMessageOptions = {
/**
* If specified, only messages that match the filter will cause the message event
* to be fired.
*/
filter?: string | RegExp;
/** If true, each message handled will safely call `$rootScope.$digest()`. */
autoApply?: boolean;
}
/** Type corresponding to onMessage callbaks stored in $Websocket#onMessageCallbacks instance. */
type IWebSocketMessageHandler = {
fn: (evt: MessageEvent) => void;
pattern: string | RegExp;
autoApply: boolean;
}
/** Type corresponding to items stored in $WebSocket#sendQueue instance. */
type IWebSocketQueueItem = {
message: any;
defered: ng.IPromise<void>;
}
interface IWebSocket {
/**
* Adds a callback to be executed each time a socket connection is opened for
* this instance.
*
* @param event event object
* @returns this instance, for method chaining
*/
onOpen(callback: (event: Event) => void): IWebSocket;
/**
* Adds a callback to be executed each time a socket connection is closed for
* this instance.
*
* @param event event object
* @returns this instance, for method chaining
*/
onClose(callback: (event: CloseEvent) => void): IWebSocket;
/**
* Adds a callback to be executed each time a socket connection is closed for
* this instance.
*
* @param event event object
* @returns this instance, for method chaining
*/
onError(callback: (event: Event) => void): IWebSocket;
/**
* Adds a callback to be executed each time a socket connection has an error for
* this instance.
*
* @param event event object
* @returns this instance, for method chaining
*/
onMessage(callback: (event: MessageEvent) => void, options?: IWebSocketMessageOptions): IWebSocket;
/**
* Closes the underlying socket, as long as no data is still being sent from the client.
*
* @param force if `true`, force close even if data is still being sent
* @returns this instance, for method chaining
*/
close(force?: boolean): IWebSocket;
/**
* Adds data to a queue, and attempts to send if the socket is ready.
*
* @param data data to send, if this is an object, it will be stringified before sending
*/
send(data: string | {}): ng.IPromise<any>;
/**
* WebSocket instance.
*/
socket: WebSocket;
/**
* Queue of send calls to be made on socket when socket is able to receive data.
*/
sendQueue: IWebSocketQueueItem[];
/**
* List of callbacks to be executed when the socket is opened.
*/
onOpenCallbacks: ((evt: Event) => void)[];
/**
* List of callbacks to be executed when a message is received from the socket.
*/
onMessageCallbacks: IWebSocketMessageHandler[];
/**
* List of callbacks to be executed when an error is received from the socket.
*/
onErrorCallbacks: ((evt: Event) => void)[];
/**
* List of callbacks to be executed when the socket is closed.
*/
onCloseCallbacks: ((evt: CloseEvent) => void)[];
/**
* Returns either the readyState value from the underlying WebSocket instance
* or a proprietary value representing the internal state
*/
readyState: number;
/**
* The initial timeout.
*/
initialTimeout: number;
/**
* Maximun timeout used to determine reconnection delay.
*/
maxTimeout: number;
}
}
@@ -0,0 +1,15 @@
/// <reference path="angular-xeditable.d.ts" />
var myApp = angular.module('testModule', ['xeditable']);
myApp.run(["editableOptions", (editableOptions: angular.xeditable.IEditableOptions) => {
editableOptions.activate = "select";
editableOptions.activationEvent = "click";
editableOptions.blurElem = "ignore";
editableOptions.blurForm = "submit";
editableOptions.buttons = "no";
editableOptions.icon_set = "font-awesome";
editableOptions.isDisabled = true;
editableOptions.theme = "bs3";
}]);
+56
View File
@@ -0,0 +1,56 @@
// Type definitions for Angular xEditable 0.2.0 (angular.xeditable module)
// Project: https://vitalets.github.io/angular-xeditable/
// Definitions by: Joao Monteiro <https://github.com/jpmnteiro>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare namespace angular.xeditable {
interface IEditableOptions {
/**
* Theme. Possible values `bs3`, `bs2`, `default`
*/
theme: string;
/**
* Icon Set. Possible values `font-awesome`, `default`.
*/
icon_set: string;
/**
* Whether to show buttons for single editalbe element.
* Possible values `right` (default), `no`.
*/
buttons: string;
/**
* Default value for `blur` attribute of single editable element.
* Can be `cancel|submit|ignore`.
*/
blurElem: string;
/**
* Default value for `blur` attribute of editable form.
* Can be `cancel|submit|ignore`.
*/
blurForm: string;
/**
* How input elements get activated. Possible values: `focus|select|none`.
*/
activate: string;
/**
* Whether to disable x-editable. Can be overloaded on each element.
*/
isDisabled: boolean;
/*
* Event, on which the edit mode gets activated.
* Can be any event.
*/
activationEvent: string;
}
}
+36 -25
View File
@@ -19,14 +19,14 @@ declare namespace angular.animate {
}
interface IAnimateCallbackObject {
eventFn?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any;
setClass?: (element: IAugmentedJQuery, addedClasses: string, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any;
addClass?: (element: IAugmentedJQuery, addedClasses: string, doneFunction: Function, options: IAnimationOptions) => any;
removeClass?: (element: IAugmentedJQuery, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any;
enter?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any;
leave?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any;
move?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any;
animate?: (element: IAugmentedJQuery, fromStyles: string, toStyles: string, doneFunction: Function, options: IAnimationOptions) => any;
eventFn?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any;
setClass?: (element: JQuery, addedClasses: string, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any;
addClass?: (element: JQuery, addedClasses: string, doneFunction: Function, options: IAnimationOptions) => any;
removeClass?: (element: JQuery, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any;
enter?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any;
leave?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any;
move?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any;
animate?: (element: JQuery, fromStyles: string, toStyles: string, doneFunction: Function, options: IAnimationOptions) => any;
}
interface IAnimationPromise extends IPromise<void> {}
@@ -43,7 +43,7 @@ declare namespace angular.animate {
* @param container the container element that will capture each of the animation events that are fired on itself as well as among its children
* @param callback the callback function that will be fired when the listener is triggered
*/
on(event: string, container: JQuery, callback: Function): void;
on(event: string, container: JQuery, callback: (element?: JQuery, phase?: string) => any): void;
/**
* Deregisters an event listener based on the event which has been associated with the provided element.
@@ -52,7 +52,7 @@ declare namespace angular.animate {
* @param container the container element the event listener was placed on
* @param callback the callback function that was registered as the listener
*/
off(event: string, container?: JQuery, callback?: Function): void;
off(event: string, container?: JQuery, callback?: (element?: JQuery, phase?: string) => any): void;
/**
* Associates the provided element with a host parent element to allow the element to be animated even if it exists outside of the DOM structure of the Angular application.
@@ -183,16 +183,6 @@ declare namespace angular.animate {
* see https://docs.angularjs.org/api/ngAnimate/#applying-directive-specific-styles-to-an-animation
*/
interface IAnimationOptions {
/**
* The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
*/
to?: Object;
/**
* The starting CSS styles (a key/value object) that will be applied at the start of the animation.
*/
from?: Object;
/**
* The DOM event (e.g. enter, leave, move). When used, a generated CSS class of ng-EVENT and
* ng-EVENT-active will be applied to the element during the animation. Multiple events can be provided when
@@ -200,6 +190,12 @@ declare namespace angular.animate {
*/
event?: string;
/**
* Indicates that the ng-prefix will be added to the event class. Setting to false or
* omitting will turn ng-EVENT and ng-EVENT-active in EVENT and EVENT-active. Unused if event is omitted.
*/
structural?: boolean;
/**
* The CSS easing value that will be applied to the transition or keyframe animation (or both).
*/
@@ -208,12 +204,22 @@ declare namespace angular.animate {
/**
* The raw CSS transition style that will be used (e.g. 1s linear all).
*/
transition?: string;
transitionStyle?: string;
/**
* The raw CSS keyframe animation style that will be used (e.g. 1s my_animation linear).
*/
keyframe?: string;
keyframeStyle?: string;
/**
* The starting CSS styles (a key/value object) that will be applied at the start of the animation.
*/
from?: Object;
/**
* The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
*/
to?: Object;
/**
* A space separated list of CSS classes that will be added to the element and spread across the animation.
@@ -250,11 +256,16 @@ declare namespace angular.animate {
/**
* The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item
* in the stagger; therefore when a stagger option value of 0.1 is used then there will be a stagger delay of 600ms)
* applyClassesEarly - Whether or not the classes being added or removed will be used when detecting the animation.
* This is set by $animate when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time.
* (Note that this will prevent any transitions from occuring on the classes being added and removed.)
*
*/
staggerIndex?: number;
/**
* Whether or not the provided from and to styles will be removed once the animation is closed. This is useful for
* when the styles are used purely for the sake of the animation and do not have a lasting visual effect on the element
* (e.g. a colapse and open animation). By default this value is set to false.
*/
cleanupStyles?: boolean;
}
interface IAnimateCssRunner {
+1 -1
View File
@@ -113,7 +113,7 @@ declare namespace angular.resource {
// 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;
new(dataOrParams? : any) : T & IResource<T>;
get: IResourceMethod<T>;
query: IResourceArrayMethod<T>;
+3 -1
View File
@@ -476,6 +476,8 @@ function test_angular_forEach() {
var element = angular.element("div.myApp");
var scope: ng.IScope = element.scope();
var isolateScope: ng.IScope = element.isolateScope();
isolateScope = element.find('div.foo').isolateScope();
isolateScope = element.children().isolateScope();
// $timeout signature tests
@@ -867,7 +869,7 @@ angular.module('docsTabsExample', [])
angular.module('componentExample', [])
.component('counter', {
require: ['^ctrl'],
require: {'ctrl': '^ctrl'},
bindings: {
count: '='
},
+77 -49
View File
@@ -81,7 +81,7 @@ declare namespace angular {
*
* If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*/
element: IAugmentedJQueryStatic;
element: JQueryStatic;
equals(value1: any, value2: any): boolean;
extend(destination: any, ...sources: any[]): any;
@@ -156,7 +156,7 @@ declare namespace angular {
noop(...args: any[]): void;
reloadWithDebugInfo(): void;
toJson(obj: any, pretty?: boolean): string;
toJson(obj: any, pretty?: boolean | number): string;
uppercase(str: string): string;
version: {
full: string;
@@ -986,7 +986,7 @@ declare namespace angular {
// DocumentService
// see http://docs.angularjs.org/api/ng.$document
///////////////////////////////////////////////////////////////////////////
interface IDocumentService extends IAugmentedJQuery {}
interface IDocumentService extends JQuery {}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
@@ -1249,15 +1249,15 @@ declare namespace angular {
// This corresponds to the "publicLinkFn" returned by $compile.
interface ITemplateLinkingFunction {
(scope: IScope, cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery;
(scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery;
}
// This corresponds to $transclude (and also the transclude function passed to link).
interface ITranscludeFunction {
// If the scope is provided, then the cloneAttachFn must be as well.
(scope: IScope, cloneAttachFn: ICloneAttachFunction): IAugmentedJQuery;
(scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery;
// If one argument is provided, then it's assumed to be the cloneAttachFn.
(cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery;
(cloneAttachFn?: ICloneAttachFunction): JQuery;
}
///////////////////////////////////////////////////////////////////////////
@@ -1683,7 +1683,7 @@ declare namespace angular {
* controller if passed as a string. Empty function by default.
* Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)
*/
controller?: string | Function | (string | Function)[];
controller?: string | Function | (string | Function)[] | IComponentController;
/**
* An identifier name for a reference to the controller. If present, the controller will be published to scope under
* the controllerAs name. If not present, this will default to be the same as the component name.
@@ -1716,11 +1716,52 @@ declare namespace angular {
* Whether transclusion is enabled. Enabled by default.
*/
transclude?: boolean | string | {[slot: string]: string};
require?: string | string[] | {[controller: string]: string};
require?: {[controller: string]: string};
}
interface IComponentTemplateFn {
( $element?: IAugmentedJQuery, $attrs?: IAttributes ): string;
( $element?: JQuery, $attrs?: IAttributes ): string;
}
/**
* Components have a well-defined lifecycle Each component can implement "lifecycle hooks". These are methods that
* will be called at certain points in the life of the component.
* @url https://docs.angularjs.org/guide/component
*/
interface IComponentController {
/**
* Called on each controller after all the controllers on an element have been constructed and had their bindings
* initialized (and before the pre & post linking functions for the directives on this element). This is a good
* place to put initialization code for your controller.
*/
$onInit?(): void;
/**
* Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
* { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as
* cloning the bound value to prevent accidental mutation of the outer value.
*/
$onChanges?(changesObj: {[property:string]: IChangesObject}): void;
/**
* Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources,
* watches and event handlers.
*/
$onDestroy?(): void;
/**
* Called after this controller's element and its children have been linked. Similar to the post-link function this
* hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain
* templateUrl directives will not have been compiled and linked since they are waiting for their template to load
* asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered
* analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather
* different in Angular 1 there is no direct mapping and care should be taken when upgrading.
*/
$postLink?(): void;
}
interface IChangesObject {
currentValue: any;
previousValue: any;
isFirstChange(): boolean;
}
///////////////////////////////////////////////////////////////////////////
@@ -1736,7 +1777,7 @@ declare namespace angular {
interface IDirectiveLinkFn {
(
scope: IScope,
instanceElement: IAugmentedJQuery,
instanceElement: JQuery,
instanceAttributes: IAttributes,
controller: {},
transclude: ITranscludeFunction
@@ -1750,7 +1791,7 @@ declare namespace angular {
interface IDirectiveCompileFn {
(
templateElement: IAugmentedJQuery,
templateElement: JQuery,
templateAttributes: IAttributes,
/**
* @deprecated
@@ -1759,7 +1800,7 @@ declare namespace angular {
* that is passed to the link function instead.
*/
transclude: ITranscludeFunction
): IDirectivePrePost;
): void | IDirectivePrePost;
}
interface IDirective {
@@ -1792,44 +1833,14 @@ declare namespace angular {
}
/**
* angular.element
* when calling angular.element, angular returns a jQuery object,
* augmented with additional methods like e.g. scope.
* see: http://docs.angularjs.org/api/angular.element
* These interfaces are kept for compatibility with older versions of these type definitions.
* Actually, Angular doesn't create a special subclass of jQuery objects. It extends jQuery.prototype
* like jQuery plugins do, that's why all jQuery objects have these Angular-specific methods, not
* only those returned from angular.element.
* See: http://docs.angularjs.org/api/angular.element
*/
interface IAugmentedJQueryStatic extends JQueryStatic {
(selector: string, context?: any): IAugmentedJQuery;
(element: Element): IAugmentedJQuery;
(object: {}): IAugmentedJQuery;
(elementArray: Element[]): IAugmentedJQuery;
(object: JQuery): IAugmentedJQuery;
(func: Function): IAugmentedJQuery;
(array: any[]): IAugmentedJQuery;
(): IAugmentedJQuery;
}
interface IAugmentedJQuery extends JQuery {
// TODO: events, how to define?
//$destroy
find(selector: string): IAugmentedJQuery;
find(element: any): IAugmentedJQuery;
find(obj: JQuery): IAugmentedJQuery;
controller(): any;
controller(name: string): any;
injector(): any;
scope(): IScope;
/**
* Overload for custom scope interfaces
*/
scope<T extends IScope>(): T;
isolateScope(): IScope;
inheritedData(key: string, value: any): JQuery;
inheritedData(obj: { [key: string]: any; }): JQuery;
inheritedData(key?: string): any;
}
interface IAugmentedJQueryStatic extends JQueryStatic {}
interface IAugmentedJQuery extends JQuery {}
///////////////////////////////////////////////////////////////////////////
// AUTO module (angular.js)
@@ -1931,3 +1942,20 @@ declare namespace angular {
(obj: Object): string;
}
}
interface JQuery {
// TODO: events, how to define?
//$destroy
find(element: any): JQuery;
find(obj: JQuery): JQuery;
controller(name?: string): any;
injector(): ng.auto.IInjectorService;
/** It's declared generic for custom scope interfaces */
scope<T extends ng.IScope>(): T;
isolateScope<T extends ng.IScope>(): T;
inheritedData(key: string, value: any): JQuery;
inheritedData(obj: { [key: string]: any; }): JQuery;
inheritedData(key?: string): any;
}
+67
View File
@@ -0,0 +1,67 @@
/// <reference path="apigee-access.d.ts"/>
import apigee from "apigee-access";
//Sample code from
// https://www.npmjs.com/package/apigee-access
var request: any = null;
// Variables
var val1 = apigee.getVariable(request, 'TestVariable');
apigee.setIntVariable(request, 'TestVariable', '123');
apigee.setIntVariable(request, 'TestVariable2', 42);
apigee.deleteVariable(request, 'TestVariable');
// Mode
console.log('The deployment mode is ' + apigee.getMode());
// Cache
var cache = apigee.getCache('cache');
var customCache = apigee.getCache('MyCustomCache',
{ resource: 'MyCustomrResource' });
cache.put('key2', 'Hello, World!', 120);
cache.put('key4', 'Hello, World!', function (err: any) {
});
cache.get('key', function (err: any, data: any) {
});
cache.remove('key');
// Secure Vault
var orgVault = apigee.getVault('vault1', 'organization');
orgVault.get('key1', function (err: any, secretValue: any) {
});
// Quota Service
var quota = apigee.getQuota();
quota.apply({ identifier: 'Foo', allow: 10, timeUnit: 'hour' },
function (err: any, result: any) {
console.log('Quota applied: %j', result);
});
quota.apply({
identifier: 'Foo',
timeUnit: 'hour',
allow: 100
}, quotaResult);
quota.apply({
identifier: 'Bar',
timeUnit: 'minute',
interval: 5,
allow: 500
}, quotaResult);
quota.apply({
identifier: 'Foo',
timeUnit: 'hour',
allow: 100,
weight: 10
}, quotaResult);
function quotaResult(err: any, r: any) {
if (err) { console.error('Quota failed'); }
}
+58
View File
@@ -0,0 +1,58 @@
// Type definitions for apigee-access
// Project: https://www.npmjs.com/package/apigee-access
// Definitions by: Casper Skydt <https://github.com/CasperSkydt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module ApigeeAccess {
function getVariable(request: any, name: string): string | number | boolean;
function setVariable(request: any, name: string, value: string | number | boolean ): void;
function setIntVariable(request: any, name: string, value: string | number): void;
function deleteVariable(request: any, name: string): void;
function getCache(name: string, options?: CacheOptions): any;
function getVault(name: string, scope?: "organization" | "environment"): SecureVault;
function getQuota(options?: any): QuotaService;
function getMode(): "apigee" | "standalone";
interface CacheOptions{
resource?: string;
scope?: "global" | "application" | "exclusive";
defaultTtl?: number;
timeout?: number;
}
interface Cache{
put(key: string, data: any, ttl?: number, callback?: (err: any) => void): void;
get(key: string, callback: (err: any, data: any) => void): void;
remove(key: string, callback?: (err: any) => void): void;
}
interface SecureVault{
getKeys(callback: (err: any, data: any) => void): void;
get(key: string, callback: (err: any, data: any) => void): void;
}
interface QuotaService{
apply(options?: QuotaServiceApplyOptions, callback?: (err: any, data: QuotaServiceApplyCallbackData) => void): void;
}
interface QuotaServiceApplyOptions{
identifier: string;
timeUnit: "minute" | "hour" | "day" | "week" | "month";
allow: number;
interval?: number;
weight?: number;
}
interface QuotaServiceApplyCallbackData{
used: number;
allowed: number;
isAllowed: boolean;
expiryTime: number;
timestamp: number;
}
}
declare module "apigee-access"{
export default ApigeeAccess;
}
@@ -27,7 +27,26 @@ var config: Microsoft.ApplicationInsights.IConfig = {
cookieDomain: ""
};
var appInsights = new Microsoft.ApplicationInsights.AppInsights(config);
var appInsights: Microsoft.ApplicationInsights.IAppInsights = {
config: config,
context: null,
queue: null,
startTrackPage(name?: string) { return null; },
stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; },
trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; },
startTrackEvent(name: string) { return null },
stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null },
trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null },
trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null },
trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null },
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null },
trackTrace(message: string, properties?: { [name: string]: string; }) { return null },
flush() { return null },
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null },
clearAuthenticatedUserContext() { return null },
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null }
};
// trackPageView
appInsights.trackPageView("page1");
@@ -68,7 +87,7 @@ appInsights.config.instrumentationKey = "<new key>";
// TelementryContext
var context = appInsights.context;
var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context;
context.application.ver = "v0.0.0";
context.application.build = "1.1.1";
@@ -93,4 +112,46 @@ var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data,
context.track(envelope);
context.addTelemetryInitializer((envelope) => false);
context.addTelemetryInitializer((envelope) => false);
// track event
var eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null);
var eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Event>(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj);
var eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
context.track(eventEnvelope);
// track exception
var exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), "handledAt", null, null, AI.SeverityLevel.Critical);
var exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Exception>(Microsoft.ApplicationInsights.Telemetry.Exception.dataType, exceptionObj);
var exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType);
context.track(exceptionEnvelope);
// track metric
var metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null);
var metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Metric>(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj);
var metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType);
context.track(metricEnvelope);
// track page view
var pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null);
var pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageView>(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj);
var pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType);
context.track(pageViewEnvelope);
// track page view performance
var pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null);
var pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageViewPerformance>(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerfObj);
var pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType);
context.track(pageViewPerfEnvelope);
// track remote dependency
var remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET");
var remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData>(Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, remoteDepObj);
var remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType);
context.track(pageViewPerfEnvelope);
// track trace
var traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null);
var traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Trace>(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj);
var traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
context.track(traceEnvelope);
File diff suppressed because it is too large Load Diff
+22
View File
@@ -341,9 +341,31 @@ interface Client {
trackMetric(name: string, value: number, count?:number, min?: number, max?: number, stdDev?: number, properties?: {
[key: string]: string;
}): void;
/**
* Log an incoming http request to your server. The request data will be tracked during the response "finish" event if it is successful or the request "error"
* event if it fails. The request duration is automatically calculated as the timespan between when the trackRequest method was called, and when the response "finish"
* or request "error" events were fired.
* @param request The http.ServerRequest object to track
* @param response The http.ServerResponse object for this request
* @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty.
*/
trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: {
[key: string]: string;
}): void;
/**
* Log an incoming http request to your server. The request data is tracked synchronously rather than waiting for the response "finish"" or request "error"" events.
* Use this if you need your request telemetry to respect custom app insights operation and user context (for example if you set any appInsights.client.context.tags).
* @param request The http.ServerRequest object to track
* @param response The http.ServerResponse object for this request
* @param ellapsedMilliseconds The duration for this request. Defaults to 0.
* @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty.
* @param error An error that was returned for this request if it was unsuccessful. Defaults to null.
*/
trackRequestSync(request: any /*http.ServerRequest */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: {
[key: string]: string;}, error?: any) : void;
/**
* Log information about a dependency of your app. Typically used to track the time database calls or outgoing http requests take from your server.
* @param name The name of the dependency (i.e. "myDatabse")
+1 -1
View File
@@ -55,7 +55,7 @@ declare namespace Atmosphere {
connectTimeout?: number;
reconnectInterval?: number;
dropHeaders?: boolean;
uuid?: number;
uuid?: string;
async?: boolean;
shared?: boolean;
readResponsesHeaders?: boolean;
+5
View File
@@ -797,3 +797,8 @@ declare module "avoscloud-sdk" {
export = AV;
}
declare module 'leanengine' {
import alias = require('avoscloud-sdk');
export = alias;
}
+26
View File
@@ -11,6 +11,32 @@ creds = new AWS.Credentials(str, str, str);
str = creds.accessKeyId;
/*
* ECS
*/
var ecs:AWS.ECS
ecs = new AWS.ECS();
ecs = new AWS.ECS({apiVersion: '2012-11-05'});
ecs.describeClusters({
clusters: ['STRING_VALUE', 'STRING_VALUE']
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
ecs.describeTasks({
cluster: 'STRING_VALUE',
tasks: ['STRING_VALUE', 'STRING_VALUE']
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
/*
* SQS
*/
+178 -4
View File
@@ -18,6 +18,10 @@ declare module "aws-sdk" {
accessKeyId: string;
}
export class EnvironmentCredentials extends Credentials {
constructor(profile: string);
}
export interface Logger {
write?: (chunk: any, encoding?: string, callback?: () => void) => void;
log?: (...messages: any[]) => void;
@@ -86,6 +90,8 @@ declare module "aws-sdk" {
export interface ClientConfigPartial extends Services {
credentials?: Credentials;
region?: string;
accessKeyId: string;
secretAccessKey: string;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
logger?: Logger;
@@ -138,9 +144,9 @@ declare module "aws-sdk" {
export class SNS {
constructor(options?: any);
public client: Sns.Client;
publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void;
}
export class SimpleWorkflow {
constructor(options?: any);
public client: Swf.Client;
@@ -152,13 +158,80 @@ declare module "aws-sdk" {
getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void;
}
export class ECS {
export class STS{
constructor(options?: any);
/**
* Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that you can use to access AWS resources that you might not normally have access to.
*/
assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: sts.AssumeRoleCallbackData) => void): void;
/**
* Returns a set of temporary security credentials for users who have been authenticated via a SAML authentication response.
*/
assumeRoleWithSAML(params: sts.AssumeRoleWithSAMLParams, callback: (err: any, data: any) => void): void;
/**
* Returns a set of temporary security credentials for users who have been authenticated in a mobile or web application with a web identity provider, such as Amazon Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible identity provider.
*/
assumeRoleWithWebIdentity(params: sts.AssumeRoleWithWebIdentityParams, callback: (err: any, data: any) => void): void;
/**
* Creates a credentials object from STS response data containing credentials information.
*/
credentialsFrom(params: sts.CredentialsFromParams, callback: (err: any, data: any) => void): void;
/**
* Decodes additional information about the authorization status of a request from an encoded message returned in response to an AWS request.
*/
decodeAuthorizationMessage(params: sts.DecodeAuthorizationMessageParams, callback: (err: any, data: any) => void): void;
/**
* Returns details about the IAM identity whose credentials are used to call the API.
*/
getCallerIdentity(params: {}, callback: (err: any, data: any) => void): void;
/**
* Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) for a federated user.
*/
getFederationToken(params: sts.GetFederationTokenParams, callback: (err: any, data: any) => void): void;
/**
* Returns a set of temporary credentials for an AWS account or IAM user.
*/
getSessionToken(params: sts.GetSessionTokenParams, callback: (err: any, data: any) => void): void;
}
export class ECS {
constructor(options?: any);
/**
* Runs and maintains a desired number of tasks from a specified task definition. If the number of tasks running in a service drops below desiredCount, Amazon ECS spawns another instantiation of the task in the specified cluster. To update an existing service, see UpdateService.
*/
createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void;
/**
* Describes one or more of your clusters.
*/
describeClusters(params: ecs.DescribeClustersParams, callback: (err: any, data: any) => void): void;
/**
* Describes the specified services running in your cluster.
*/
describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void;
/**
* Describes a specified task or tasks.
*/
describeTasks(params: ecs.DescribeTasksParams, callback: (err: any, data: any) => void): void;
/**
* Describes a task definition. You can specify a family and revision to find information about a specific task definition, or you can simply specify the family to find the latest ACTIVE revision in that family.
*/
describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void;
/**
* Registers a new task definition from the supplied family and containerDefinitions. Optionally, you can add data volumes to your containers with the volumes parameter. For more information about task definition parameters and defaults, see Amazon ECS Task Definitions in the Amazon EC2 Container Service Developer Guide.
*/
registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void;
/**
* Modifies the desired count, deployment configuration, or task definition used in a service.
*/
updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void;
}
@@ -1219,11 +1292,38 @@ declare module "aws-sdk" {
}
export interface DescribeServicesParams {
/**
* A list of services to describe.
*/
services: string[];
cluster: string;
/**
* The name of the cluster that hosts the service to describe. If you do not specify a cluster, the default cluster is assumed.
*/
cluster?: string;
}
export interface DescribeClustersParams {
/**
* A space-separated list of cluster names or full cluster Amazon Resource Name (ARN) entries. If you do not specify a cluster, the default cluster is assumed.
*/
clusters?: string[];
}
export interface DescribeTasksParams {
/**
* A space-separated list of task IDs or full Amazon Resource Name (ARN) entries.
*/
tasks: string[];
/**
* The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task to describe. If you do not specify a cluster, the default cluster is assumed.
*/
cluster?: string;
}
export interface DescribeTaskDefinitionParams {
/**
* The `family` for the latest `ACTIVE` revision, `family` and `revision` (`family:revision`) for a specific revision in the family, or full Amazon Resource Name (ARN) of the task definition to describe.
*/
taskDefinition: string;
}
@@ -1296,4 +1396,78 @@ declare module "aws-sdk" {
taskDefinition: string;
}
}
export module sts {
export interface AssumeRoleParams {
RoleArn: string;
RoleSessionName: string;
DurationSeconds?: number;
ExternalId?: string;
Policy?: string;
SerialNumber?: string;
TokenCode?: string;
}
export interface AssumeRoleCallbackData{
Credentials: TemporaryCredentials;
AssumedRoleUser: AssumedRoleUser;
PackedPolicySize: number;
}
export interface TemporaryCredentials{
AccessKeyId: string;
SecretAccessKey: string;
SessionToken: string;
Expiration: Date;
}
export interface AssumedRoleUser{
AssumedRoleId: string;
Arn: string;
}
export interface AssumeRoleWithSAMLParams {
PrincipalArn: string;
RoleArn: string;
SAMLAssertion: string;
DurationSeconds?: number;
Policy?: string;
}
export interface AssumeRoleWithWebIdentityParams {
RoleArn: string;
RoleSessionName: string;
WebIdentityToken: string;
DurationSeconds?: number;
Policy?: string;
ProviderId?: string;
}
export interface CredentialsFromParams {
/**
* Data retrieved from a call to AWS.STS.getFederatedToken, getSessionToken(), assumeRole(), or assumeRoleWithWebIdentity().
*/
Data: any;
/**
* An optional credentials object to fill instead of creating a new object. Useful when modifying an existing credentials object from a refresh call.
*/
Credentials?: Credentials
}
export interface DecodeAuthorizationMessageParams {
EncodedMessage: string;
}
export interface GetFederationTokenParams {
Name: string;
DurationSeconds?: number,
Policy?: string
}
export interface GetSessionTokenParams {
DurationSeconds: number,
SerialNumber: string;
TokenCode: string;
}
}
}
+6
View File
@@ -91,3 +91,9 @@ var repoSum = (repo1: Axios.AxiosXHR<Repository>, repo2: Axios.AxiosXHR<Reposito
};
axios.all<Repository, Repository>([getRepoDetails, getRepoDetails]).then(axios.spread(repoSum));
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = "AUTH_TOKEN";
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axiosInstance.defaults.headers.common['Authorization'] = "AUTH_TOKEN";
+17
View File
@@ -124,6 +124,18 @@ declare namespace Axios {
data?: T;
}
interface AxiosXHRConfigDefaults<T> extends AxiosXHRConfigBase<T> {
/**
* custom headers to be sent
*/
headers: {
common: {[index: string]: string};
patch: {[index: string]: string};
post: {[index: string]: string};
put: {[index: string]: string};
};
}
/**
* <T> - expected response type,
* <U> - request body data type
@@ -223,6 +235,11 @@ declare namespace Axios {
*/
interceptors: Interceptor;
/**
* Config defaults
*/
defaults: AxiosXHRConfigDefaults<any>;
/**
* equivalent to `Promise.all`
*/
+37 -3
View File
@@ -7,10 +7,11 @@ declare namespace Microsoft.WindowsAzure {
// MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx
interface MobileServiceClient {
new (applicationUrl: string, applicationKey: string): MobileServiceClient;
new (applicationUrl: string, applicationKey?: string): MobileServiceClient;
applicationUrl: string;
applicationKey: string;
currentUser: User;
push: Push;
//for provider:string use one of ProviderEnum: 'microsoftaccount', 'facebook', 'twitter', 'google'
login(provider: string, token: string, callback: (error: any, user: User) => void ): void;
login(provider: string, token: string): asyncPromise;
@@ -18,8 +19,40 @@ declare namespace Microsoft.WindowsAzure {
login(provider: string): asyncPromise;
logout(): void;
getTable(tableName: string): MobileServiceTable;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient;
invokeApi(apiName: string, options?:InvokeApiOptions): asyncPromise;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient;
/**
* Invokes the specified custom api and returns a response object.
*
* @param apiName The custom api to invoke.
* @param options Contains additional parameter information, valid values are:
* body: The body of the HTTP request.
* method: The HTTP method to use in the request, with the default being POST,
* parameters: Any additional query string parameters,
* headers: HTTP request headers, specified as an object.
* @param callback Optional callback accepting (error, results) parameters.
*/
invokeApi(apiName: string, options?: InvokeApiOptions, callback?: (error: any, results: any) => void): asyncPromise;
}
interface Push
{
/**
* Register a push channel with the Mobile Apps backend to start receiving notifications.
*
* @param platform The device platform being used - wns, gcm or apns.
* @param pushChannel The push channel identifier or URI.
* @param templates An object containing template definitions. Template objects should contain body, headers and tags properties.
* @param secondaryTiles An object containing template definitions to be used with secondary tiles when using WNS.
* @param callback Optional callback accepting (error, results) parameters.
*/
register(platform: string, pushChannel: string, templates?: any, secondaryTiles?: any, callback?: (error: any, results: any) => void): void;
/**
* Invokes the specified custom api and returns a response object.
*
* @param pushChannel The push channel identifier or URI.
* @param callback Optional callback accepting (error, results) parameters.
*/
unregister(pushChannel: string, callback?: (error: any, results: any) => void): void;
}
interface InvokeApiOptions
@@ -36,6 +69,7 @@ declare namespace Microsoft.WindowsAzure {
accessTokens: any; // { [providerName: string]: string; }
level: string; //for level:string use one of LevelEnum: 'admin','anonymous','authenticated'
userId: string;
mobileServiceAuthenticationToken: string;
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="babelify.d.ts" />
import babelify = require("babelify");
module BabelifyTest {
export function whatDidTheEs6Say(srcPath: string, opts?: babelify.BabelifyOptions) {
opts.extensions = opts.extensions || undefined;
opts.sourceMapsAbsolute = opts.sourceMapsAbsolute || false;
var dst: NodeJS.ReadWriteStream;
babelify(""); // 'opts' are optional
babelify(srcPath, opts).on("error", function (err: any) {
console.error("babelify error: ", err);
});
babelify.configure(opts)(srcPath).pipe(dst);
}
}
export = BabelifyTest;
+46
View File
@@ -0,0 +1,46 @@
// Type definitions for babelify v7.3.0
// Project: https://github.com/babel/babelify
// Definitions by: TeamworkGuy2 <https://github.com/TeamworkGuy2>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../babel-core/babel-core.d.ts" />
/** Browserify transform for Babel
*/
declare module 'babelify' {
import stream = require("stream");
import babel = require("babel-core");
function Babelify(filename: string, opts?: Babelify.BabelifyOptions): Babelify.BabelifyObject;
module Babelify {
export interface BabelifyConstructor {
(filename: string, opts: Babelify.BabelifyOptions): Babelify.BabelifyObject;
}
/** In addition to the various purposes documented here, all of the babelify options are passed to babel which passes them on to babel.transform() when each file is transformed */
export interface BabelifyOptions extends babel.TransformOptions {
/** These are passed to babel.util.canCompile() for each filename
* default: null
*/
extensions?: string | string[];
/** if true, a 'sourceFileName' property with a value equal to the current file being transformed is included with the options passed to babel.transform()
* default: false
*/
sourceMapsAbsolute?: boolean;
}
export class BabelifyObject extends stream.Transform {
_transform(buf: string | Buffer, encoding: string, callback: () => void): void;
_flush(callback: () => void): void;
}
export function configure(opts: Babelify.BabelifyOptions): (filename: string) => Babelify.BabelifyObject;
}
export = Babelify;
}
+62 -46
View File
@@ -147,7 +147,6 @@ declare namespace Backbone {
/*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model;
set(obj: any, options?: ModelSetOptions): Model;
change(): any;
changedAttributes(attributes?: any): any[];
clear(options?: Silenceable): any;
clone(): Model;
@@ -173,8 +172,12 @@ declare namespace Backbone {
invert(): any;
pick(keys: string[]): any;
pick(...keys: string[]): any;
pick(fn: (value: any, key: any, object: any) => any): any;
omit(keys: string[]): any;
omit(...keys: string[]): any;
omit(fn: (value: any, key: any, object: any) => any): any;
chain(): any;
isEmpty(): boolean;
}
class Collection<TModel extends Model> extends ModelBase {
@@ -209,8 +212,8 @@ declare namespace Backbone {
pluck(attribute: string): any[];
push(model: TModel, options?: AddOptions): TModel;
pop(options?: Silenceable): TModel;
remove(model: TModel, options?: Silenceable): TModel;
remove(models: TModel[], options?: Silenceable): TModel[];
remove(model: {}|TModel, options?: Silenceable): TModel;
remove(models: ({}|TModel)[], options?: Silenceable): TModel[];
reset(models?: TModel[], options?: Silenceable): TModel[];
set(models?: TModel[], options?: Silenceable): TModel[];
shift(options?: Silenceable): TModel;
@@ -223,58 +226,72 @@ declare namespace Backbone {
private _removeReference(model: TModel): void;
private _onModelEvent(event: string, model: TModel, collection: Collection<TModel>, options: any): void;
/**
* Return a shallow copy of this collection's models, using the same options as native Array#slice.
*/
slice(min: number, max?: number): TModel[];
// mixins from underscore
all(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[];
all(iterator?: _.ListIterator<TModel, boolean>, context?: any): boolean;
any(iterator?: _.ListIterator<TModel, boolean>, context?: any): boolean;
chain(): any;
contains(value: any): boolean;
countBy(iterator: (element: TModel, index: number) => any): _.Dictionary<number>;
countBy(attribute: string): _.Dictionary<number>;
detect(iterator: (item: any) => boolean, context?: any): any; // ???
drop(): TModel;
drop(n: number): TModel[];
each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any;
every(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
filter(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[];
find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel;
collect<TResult>(iterator: _.ListIterator<TModel, TResult>, context?: any): TResult[];
contains(value: TModel): boolean;
countBy(iterator?: _.ListIterator<TModel, any>): _.Dictionary<number>;
countBy(iterator: string): _.Dictionary<number>;
detect(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel;
difference(others: TModel[]): TModel[];
drop(n?: number): TModel[];
each(iterator: _.ListIterator<TModel, void>, context?: any): TModel[];
every(iterator: _.ListIterator<TModel, boolean>, context?: any): boolean;
filter(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel[];
find(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel;
findIndex(predicate: _.ListIterator<TModel, boolean>, context?: any): number;
findLastIndex(predicate: _.ListIterator<TModel, boolean>, context?: any): number;
first(): TModel;
first(n: number): TModel[];
foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any;
groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary<TModel[]>;
groupBy(attribute: string, context?: any): _.Dictionary<TModel[]>;
include(value: any): boolean;
indexOf(element: TModel, isSorted?: boolean): number;
foldl<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
foldr<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
forEach(iterator: _.ListIterator<TModel, void>, context?: any): TModel[];
groupBy(iterator: _.ListIterator<TModel, any>, context?: any): _.Dictionary<TModel[]>;
groupBy(iterator: string, context?: any): _.Dictionary<TModel[]>;
head(): TModel;
head(n: number): TModel[];
include(value: TModel): boolean;
includes(value: TModel): boolean;
indexBy(iterator: _.ListIterator<TModel, any>, context?: any): _.Dictionary<TModel>;
indexBy(iterator: string, context?: any): _.Dictionary<TModel>;
indexOf(value: TModel, isSorted?: boolean): number;
initial(): TModel;
initial(n: number): TModel[];
inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
isEmpty(object: any): boolean;
invoke(methodName: string, args?: any[]): any;
inject<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
invoke(methodName: string, ...args: any[]): any;
isEmpty(): boolean;
last(): TModel;
last(n: number): TModel[];
lastIndexOf(element: TModel, fromIndex?: number): number;
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;
select(iterator: any, context?: any): any[];
lastIndexOf(value: TModel, from?: number): number;
map<TResult>(iterator: _.ListIterator<TModel, TResult>, context?: any): TResult[];
max(iterator?: _.ListIterator<TModel, any>, context?: any): TModel;
min(iterator?: _.ListIterator<TModel, any>, context?: any): TModel;
partition(iterator: _.ListIterator<TModel, boolean>): TModel[][];
reduce<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
reduceRight<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
reject(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel[];
rest(n?: number): TModel[];
sample(): TModel;
sample(n: number): TModel[];
select(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel[];
shuffle(): TModel[];
size(): number;
shuffle(): any[];
slice(min: number, max?: number): TModel[];
some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[];
sortBy(attribute: string, context?: any): TModel[];
sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number;
reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[];
reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[];
rest(): TModel;
rest(n: number): TModel[];
tail(): TModel;
tail(n: number): TModel[];
toArray(): any[];
without(...values: any[]): TModel[];
some(iterator?: _.ListIterator<TModel, boolean>, context?: any): boolean;
sortBy<TSort>(iterator?: _.ListIterator<TModel, TSort>, context?: any): TModel[];
sortBy(iterator: string, context?: any): TModel[];
tail(n?: number): TModel[];
take(): TModel;
take(n: number): TModel[];
toArray(): TModel[];
without(...values: TModel[]): TModel[];
}
class Router extends Events {
@@ -370,7 +387,6 @@ declare namespace Backbone {
$(selector: any): JQuery;
render(): View<TModel>;
remove(): View<TModel>;
make(tagName: any, attributes?: any, content?: any): any;
delegateEvents(events?: EventsHash): any;
delegate(eventName: string, selector: string, listener: Function): View<TModel>;
undelegateEvents(): any;
+91
View File
@@ -90,6 +90,25 @@ function test_models() {
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
let strings: string[]
let value: any;
let values: any[];
let bool: boolean;
// underscore methods
strings = note.keys();
values = note.values();
values = note.pairs();
values = note.invert();
value = note.pick("foo");
value = note.pick("foo", "bar");
value = note.pick((value: any, key: any, object: any) => true);
value = note.omit("foo");
value = note.omit("foo", "bar");
value = note.omit((value: any, key: any, object: any) => true);
value = note.chain().pick().omit().value();
bool = note.isEmpty();
}
class Employee extends Backbone.Model {
@@ -161,6 +180,78 @@ function test_collection() {
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
let one: Book;
let models: Book[];
let bool: boolean;
let numDict: _.Dictionary<number>;
let modelDict: _.Dictionary<Book>;
let modelsDict: _.Dictionary<Book[]>;
let num: number;
models = books.slice(1);
models = books.slice(1, 3);
// underscore methods
bool = books.all((value: Book, index: number, list: Book[]) => true);
bool = books.any((value: Book, index: number, list: Book[]) => true);
bool = books.chain().any((value: Book, index: number, list: Book[]) => true).value();
models = books.collect((value: Book, index: number, list: Book[]) => value);
bool = books.contains(book1);
numDict = books.countBy((value: Book, index: number, list: Book[]) => true);
numDict = books.countBy("foo");
one = books.detect((value: Book, index: number, list: Book[]) => true);
models = books.difference([book1]);
models = books.drop();
models = books.each((value: Book, index: number, list: Book[]) => true);
bool = books.every((value: Book, index: number, list: Book[]) => true);
models = books.filter((value: Book, index: number, list: Book[]) => true);
one = books.find((value: Book, index: number, list: Book[]) => true);
num = books.findIndex((value: Book, index: number, list: Book[]) => true);
num = books.findLastIndex((value: Book, index: number, list: Book[]) => true);
one = books.first();
models = books.first(3);
models = books.foldl((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.foldr((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.forEach((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy("foo");
one = books.head();
models = books.head(3);
bool = books.include(book1);
bool = books.includes(book1);
modelDict = books.indexBy((value: Book, index: number, list: Book[]) => true);
modelDict = books.indexBy("foo");
num = books.indexOf(book1, true);
one = books.initial();
models = books.initial(3);
models = books.inject((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
one = books.invoke("at", 3);
bool = books.isEmpty();
one = books.last();
models = books.last(3);
num = books.lastIndexOf(book1, 3);
models = books.map((value: Book, index: number, list: Book[]) => value);
one = books.max((value: Book, index: number, list: Book[]) => value);
one = books.min((value: Book, index: number, list: Book[]) => value);
[models] = books.partition((value: Book, index: number, list: Book[]) => true);
models = books.reduce((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reduceRight((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reject((value: Book, index: number, list: Book[]) => true);
models = books.rest(3);
one = books.sample();
models = books.sample(3);
models = books.select((value: Book, index: number, list: Book[]) => true);
models = books.shuffle();
num = books.size();
bool = books.some((value: Book, index: number, list: Book[]) => true);
models = books.sortBy((value: Book, index: number, list: Book[]) => value);
models = books.sortBy("foo");
models = books.tail(3);
one = books.take();
models = books.take(3);
models = books.toArray();
models = books.without(book1, book1);
}
//////////
+91
View File
@@ -91,6 +91,25 @@ function test_models() {
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
let strings: string[]
let value: any;
let values: any[];
let bool: boolean;
// underscore methods
strings = note.keys();
values = note.values();
values = note.pairs();
values = note.invert();
value = note.pick("foo");
value = note.pick("foo", "bar");
value = note.pick((value: any, key: any, object: any) => true);
value = note.omit("foo");
value = note.omit("foo", "bar");
value = note.omit((value: any, key: any, object: any) => true);
value = note.chain().pick().omit().value();
bool = note.isEmpty();
}
class Employee extends Backbone.Model {
@@ -152,6 +171,78 @@ function test_collection() {
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
let one: Book;
let models: Book[];
let bool: boolean;
let numDict: _.Dictionary<number>;
let modelDict: _.Dictionary<Book>;
let modelsDict: _.Dictionary<Book[]>;
let num: number;
models = books.slice(1);
models = books.slice(1, 3);
// underscore methods
bool = books.all((value: Book, index: number, list: Book[]) => true);
bool = books.any((value: Book, index: number, list: Book[]) => true);
bool = books.chain().any((value: Book, index: number, list: Book[]) => true).value();
models = books.collect((value: Book, index: number, list: Book[]) => value);
bool = books.contains(book1);
numDict = books.countBy((value: Book, index: number, list: Book[]) => true);
numDict = books.countBy("foo");
one = books.detect((value: Book, index: number, list: Book[]) => true);
models = books.difference([book1]);
models = books.drop();
models = books.each((value: Book, index: number, list: Book[]) => true);
bool = books.every((value: Book, index: number, list: Book[]) => true);
models = books.filter((value: Book, index: number, list: Book[]) => true);
one = books.find((value: Book, index: number, list: Book[]) => true);
num = books.findIndex((value: Book, index: number, list: Book[]) => true);
num = books.findLastIndex((value: Book, index: number, list: Book[]) => true);
one = books.first();
models = books.first(3);
models = books.foldl((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.foldr((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.forEach((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy("foo");
one = books.head();
models = books.head(3);
bool = books.include(book1);
bool = books.includes(book1);
modelDict = books.indexBy((value: Book, index: number, list: Book[]) => true);
modelDict = books.indexBy("foo");
num = books.indexOf(book1, true);
one = books.initial();
models = books.initial(3);
models = books.inject((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
one = books.invoke("at", 3);
bool = books.isEmpty();
one = books.last();
models = books.last(3);
num = books.lastIndexOf(book1, 3);
models = books.map((value: Book, index: number, list: Book[]) => value);
one = books.max((value: Book, index: number, list: Book[]) => value);
one = books.min((value: Book, index: number, list: Book[]) => value);
[models] = books.partition((value: Book, index: number, list: Book[]) => true);
models = books.reduce((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reduceRight((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reject((value: Book, index: number, list: Book[]) => true);
models = books.rest(3);
one = books.sample();
models = books.sample(3);
models = books.select((value: Book, index: number, list: Book[]) => true);
models = books.shuffle();
num = books.size();
bool = books.some((value: Book, index: number, list: Book[]) => true);
models = books.sortBy((value: Book, index: number, list: Book[]) => value);
models = books.sortBy("foo");
models = books.tail(3);
one = books.take();
models = books.take(3);
models = books.toArray();
models = books.without(book1, book1);
}
//////////
+6
View File
@@ -0,0 +1,6 @@
/// <reference path="base64-js.d.ts" />
import * as base64js from 'base64-js';
const bytes: Uint8Array = base64js.toByteArray('shemp');
const decoded: string = base64js.fromByteArray(new Uint8Array(0));
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for base64-js v1.1.2
// Project: https://github.com/beatgammit/base64-js
// Definitions by: Peter Safranek <https://github.com/pe8ter>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'base64-js' {
export function toByteArray(encoded: string): Uint8Array;
export function fromByteArray(bytes: Uint8Array): string;
}
+8
View File
@@ -174,6 +174,7 @@ declare namespace Microsoft.Maps {
fixedMapPosition?: boolean;
height?: number;
inertiaIntensity?: number;
navigationBarMode?: number;
showBreadcrumb?: boolean;
showCopyright?: boolean;
showDashboard?: boolean;
@@ -216,6 +217,12 @@ declare namespace Microsoft.Maps {
getY(): number;
}
export enum NavigationBarMode {
default,
compact,
minified
}
export enum PixelReference {
control,
page,
@@ -307,6 +314,7 @@ declare namespace Microsoft.Maps {
getZIndex(): number;
setHtmlContent(content: string): void;
setLocation(location: Location): void;
setMap(map: Map): void;
setOptions(options: InfoboxOptions): void;
toString(): string;
}
+1269
View File
File diff suppressed because it is too large Load Diff
+15 -2
View File
@@ -18,11 +18,24 @@
declare var Promise: PromiseConstructor;
interface PromiseCancelHandlerSetter {
(handler: () => void): void;
}
interface PromiseConstructor {
/**
* 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.
* 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.
*
* If configured appropriately, it will also receive an `onCancel`
* function that can be used to configure a promise cancellation handler.
*/
new <T>(callback: (resolve: (thenableOrResult?: T | PromiseLike<T>) => void, reject: (error: any) => void) => void): Promise<T>;
new <T>(callback: (
resolve: (thenableOrResult?: T | PromiseLike<T>) => void,
reject: (error: any) => void,
onCancel?: PromiseCancelHandlerSetter
) => void): Promise<T>;
config(options: {
warnings?: boolean | {wForgottenReturn?: boolean};
+2 -2
View File
@@ -33,7 +33,7 @@ declare module "body-parser" {
/**
* passed to JSON.parse().
*/
receiver?: (key: string, value: any) => any;
reviver?: (key: string, value: any) => any;
/**
* parse extended syntax with the qs module. (default: true)
*/
@@ -65,7 +65,7 @@ declare module "body-parser" {
/**
* passed to JSON.parse().
*/
receiver?: (key: string, value: any) => any;
reviver?: (key: string, value: any) => any;
}): express.RequestHandler;
export function raw(options?: {
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -15,7 +15,7 @@
* http://bootstrap-datepicker.readthedocs.org/en/release/options.html
*/
interface DatepickerOptions {
format?: string;
format?: string | DatepickerCustomFormatOptions;
weekStart?: number;
startDate?: any;
endDate?: any;
@@ -38,6 +38,11 @@ interface DatepickerOptions {
assumeNearbyYear?: any;
}
interface DatepickerCustomFormatOptions {
toDisplay?(date: string, format: any, language: any): string;
toValue?(date: string, format: any, language: any): Date;
}
interface DatepickerEventObject extends JQueryEventObject {
date: Date;
format(format?: string): string;
+5
View File
@@ -44,3 +44,8 @@ $('.typeahead').typeahead({
});
$('#navbar').affix();
$('.item').emulateTransitionEnd(2000);
$.support.transition = false;
console.log(($.support.transition as TransitionEventNames).end === "transitionend");
+11 -1
View File
@@ -53,7 +53,7 @@ interface PopoverOptions {
}
interface CollapseOptions {
parent?: any;
parent?: any;
toggle?: boolean;
}
@@ -79,6 +79,10 @@ interface AffixOptions {
target?: any;
}
interface TransitionEventNames {
end: string;
}
interface JQuery {
modal(options?: ModalOptions): JQuery;
modal(options?: ModalOptionsBackdropString): JQuery;
@@ -114,6 +118,12 @@ interface JQuery {
typeahead(options?: TypeaheadOptions): JQuery;
affix(options?: AffixOptions): JQuery;
emulateTransitionEnd(duration: number): JQuery;
}
interface JQuerySupport {
transition: boolean | TransitionEventNames;
}
declare module "bootstrap" {
+1 -1
View File
@@ -883,7 +883,7 @@ function test_config() {
o = config.getAdapter("myInterfaceName", "myAdapterName");
o = config.getAdapterInstance("myInterfaceName", "myAdapterName");
config.initializeAdapterInstance("myInterfaceName", "myAdapterName", true);
config.initializeAdapterInstances({ x: 3, y: "not" });
config.initializeAdapterInstances({ ajax: "", dataService: "" });
s = config.interfaceInitialized.type;
o = config.interfaceRegistry;
o = config.objectRegistry;
+167 -129
View File
@@ -11,21 +11,22 @@
// Updated Jan 16 2015 for Breeze 1.4.17 to add support for noimplicitany - Kevin Wilson ( www.kwilson.me.uk )
// Updated Jan 20 2015 for Breeze 1.5.2 and merging changes from DefinitelyTyped
// Updated Feb 28 2015 add any/all clause on Predicate
// Updated Jun 27 2016 - Marcel Good (www.ideablade.com)
declare namespace breeze.core {
interface ErrorCallback {
export interface ErrorCallback {
(error: Error): void;
}
interface IEnum {
export interface IEnum {
contains(object: any): boolean;
fromName(name: string): EnumSymbol;
getNames(): string[];
getSymbols(): EnumSymbol[];
}
class Enum implements IEnum {
export class Enum implements IEnum {
constructor(name: string, methodObj?: any);
addSymbol(propertiesObj?: any): EnumSymbol;
@@ -37,14 +38,14 @@ declare namespace breeze.core {
resolveSymbols(): void;
}
class EnumSymbol {
export class EnumSymbol {
parentEnum: IEnum;
getName(): string;
toString(): string;
}
class Event {
export class Event {
constructor(name: string, publisher: any, defaultErrorCallback?: ErrorCallback);
static enable(eventName: string, target: any): void;
@@ -91,25 +92,27 @@ declare namespace breeze.core {
declare namespace breeze {
interface Entity {
export interface Entity {
entityAspect: EntityAspect;
entityType: EntityType;
}
interface ComplexObject {
export interface ComplexObject {
complexAspect: ComplexAspect;
complexType: ComplexType;
}
interface IProperty {
export interface IProperty {
name: string;
nameOnServer: string;
displayName: string;
parentType: IStructuralType;
validators: Validator[];
isDataProperty: boolean;
isNavigationProperty: boolean;
}
interface IStructuralType {
export interface IStructuralType {
complexProperties: DataProperty[];
dataProperties: DataProperty[];
name: string;
@@ -119,13 +122,13 @@ declare namespace breeze {
validators: Validator[];
}
class AutoGeneratedKeyType {
export class AutoGeneratedKeyType {
static Identity: AutoGeneratedKeyType;
static KeyGenerator: AutoGeneratedKeyType;
static None: AutoGeneratedKeyType;
}
class ComplexAspect {
export class ComplexAspect {
complexObject: ComplexObject;
getEntityAspect(): EntityAspect;
parent: Object;
@@ -134,7 +137,7 @@ declare namespace breeze {
originalValues: Object;
}
class ComplexType implements IStructuralType {
export class ComplexType implements IStructuralType {
complexProperties: DataProperty[];
dataProperties: DataProperty[];
name: string;
@@ -146,7 +149,7 @@ declare namespace breeze {
getProperties(): DataProperty[];
}
class DataProperty implements IProperty {
export class DataProperty implements IProperty {
complexTypeName: string;
concurrencyMode: string;
dataType: DataTypeSymbol;
@@ -162,13 +165,14 @@ declare namespace breeze {
maxLength: number;
name: string;
nameOnServer: string;
displayName: string;
parentType: IStructuralType;
relatedNavigationProperty: NavigationProperty;
validators: Validator[];
constructor(config: DataPropertyOptions);
}
interface DataPropertyOptions {
export interface DataPropertyOptions {
complexTypeName?: string;
concurrencyMode?: string;
custom?: any;
@@ -185,7 +189,7 @@ declare namespace breeze {
validators?: Validator[];
}
class DataService {
export class DataService {
adapterInstance: DataServiceAdapter;
adapterName: string;
hasServerMetadata: boolean;
@@ -197,7 +201,7 @@ declare namespace breeze {
using(config: DataServiceOptions): DataService;
}
interface DataServiceOptions {
export interface DataServiceOptions {
serviceName?: string;
adapterName?: string;
uriBuilderName?: string;
@@ -206,7 +210,7 @@ declare namespace breeze {
useJsonp?: boolean;
}
class DataServiceAdapter {
export class DataServiceAdapter {
checkForRecomposition(interfaceInitializedArgs: { interfaceName: string; isDefault: boolean }): void;
initialize(): void;
fetchMetadata(metadataStore: MetadataStore, dataService: DataService): breeze.promises.IPromise<any>;
@@ -215,7 +219,7 @@ declare namespace breeze {
JsonResultsAdapter: JsonResultsAdapter;
}
class JsonResultsAdapter {
export class JsonResultsAdapter {
name: string;
extractResults: (data: {}) => {};
visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: boolean; };
@@ -226,24 +230,24 @@ declare namespace breeze {
});
}
interface QueryContext {
export interface QueryContext {
url: string;
query: any; // how to also say it could be an EntityQuery or a string
query: EntityQuery | string;
entityManager: EntityManager;
dataService: DataService;
queryOptions: QueryOptions;
}
interface NodeContext {
export interface NodeContext {
nodeType: string;
}
class DataTypeSymbol extends breeze.core.EnumSymbol {
export class DataTypeSymbol extends breeze.core.EnumSymbol {
defaultValue: any;
isNumeric: boolean;
isDate: boolean;
}
interface DataType extends breeze.core.IEnum {
export interface DataType extends breeze.core.IEnum {
Binary: DataTypeSymbol;
Boolean: DataTypeSymbol;
Byte: DataTypeSymbol;
@@ -259,16 +263,36 @@ declare namespace breeze {
String: DataTypeSymbol;
Time: DataTypeSymbol;
Undefined: DataTypeSymbol;
toDataType(typeName: string): DataTypeSymbol;
parseDateFromServer(date: any): Date;
defaultValue: any;
isNumeric: boolean;
}
var DataType: DataType;
isInteger: boolean;
class EntityActionSymbol extends breeze.core.EnumSymbol {
/** Function to convert a value from string to this DataType. Note that this will be called each time a property is changed, so make it fast. */
parse: (val: any, sourceTypeName: string) => any;
/** Function to format this DataType for OData queries. */
fmtOData: (val: any) => any;
/** Optional function to get the next value for key generation, if this datatype is used as a key. Uses an internal table of previous values. */
getNext?: () => any;
/** Optional function to normalize a data value for comparison, if its value cannot be used directly. Note that this will be called each time a property is changed, so make it fast. */
normalize?: (val: any) => any;
/** Optional function to get the next value when the datatype is used as a concurrency property. */
getConcurrencyValue?: (val: any) => any;
/** Optional function to convert a raw (server) value from string to this DataType. */
parseRawValue?: (val: any) => any;
}
interface EntityAction extends breeze.core.IEnum {
export var DataType: DataType;
export class EntityActionSymbol extends breeze.core.EnumSymbol {
}
export interface EntityAction extends breeze.core.IEnum {
AcceptChanges: EntityActionSymbol;
Attach: EntityActionSymbol;
AttachOnImport: EntityActionSymbol;
@@ -282,9 +306,9 @@ declare namespace breeze {
PropertyChange: EntityActionSymbol;
RejectChanges: EntityActionSymbol;
}
var EntityAction: EntityAction;
export var EntityAction: EntityAction;
class EntityAspect {
export class EntityAspect {
entity: Entity;
entityManager: EntityManager;
entityState: EntityStateSymbol;
@@ -318,8 +342,6 @@ declare namespace breeze {
removeValidationError(validator: Validator, property: NavigationProperty): void;
removeValidationError(validationError: ValidationError): void;
/** Sets the entity to an EntityState of 'Added'. This is NOT the equivalent of calling {{#crossLink "EntityManager/addEntity"}}{{/crossLink}}
because no key generation will occur for autogenerated keys as a result of this operation. */
setAdded(): void;
setDeleted(): void;
setDetached(): void;
@@ -333,7 +355,7 @@ declare namespace breeze {
validateProperty(property: NavigationProperty, context?: any): boolean;
}
class PropertyChangedEventArgs {
export class PropertyChangedEventArgs {
entity: Entity;
property: IProperty;
propertyName: string;
@@ -342,21 +364,21 @@ declare namespace breeze {
parent: any;
}
class PropertyChangedEvent extends breeze.core.Event {
export class PropertyChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: PropertyChangedEventArgs) => void): number;
}
class ValidationErrorsChangedEventArgs {
export class ValidationErrorsChangedEventArgs {
entity: Entity;
added: ValidationError[];
removed: ValidationError[];
}
class ValidationErrorsChangedEvent extends breeze.core.Event {
export class ValidationErrorsChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void): number;
}
class EntityKey {
export class EntityKey {
constructor(entityType: EntityType, keyValue: any);
constructor(entityType: EntityType, keyValues: any[]);
@@ -366,17 +388,17 @@ declare namespace breeze {
values: any[];
}
interface EntityByKeyResult {
export interface EntityByKeyResult {
entity: Entity;
entityKey: EntityKey;
fromCache: boolean;
}
interface ExportEntitiesOptions {
export interface ExportEntitiesOptions {
asString: boolean; // default true
includeMetadata: boolean; // default true
}
class EntityManager {
export class EntityManager {
dataService: DataService;
keyGeneratorCtor: Function;
metadataStore: MetadataStore;
@@ -392,7 +414,7 @@ declare namespace breeze {
constructor(config?: EntityManagerOptions);
constructor(config?: string);
acceptChanges(): void;
acceptChanges(): void;
addEntity(entity: Entity): Entity;
attachEntity(entity: Entity, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity;
clear(): void;
@@ -447,7 +469,7 @@ declare namespace breeze {
setProperties(config: EntityManagerProperties): void;
}
interface EntityManagerOptions {
export interface EntityManagerOptions {
serviceName?: string;
dataService?: DataService;
metadataStore?: MetadataStore;
@@ -457,7 +479,7 @@ declare namespace breeze {
keyGeneratorCtor?: Function;
}
interface EntityManagerProperties {
export interface EntityManagerProperties {
serviceName?: string;
dataService?: DataService;
metadataStore?: MetadataStore;
@@ -467,19 +489,19 @@ declare namespace breeze {
keyGeneratorCtor?: Function;
}
interface ExecuteQuerySuccessCallback {
export interface ExecuteQuerySuccessCallback {
(data: QueryResult): void;
}
interface ExecuteQueryErrorCallback {
export interface ExecuteQueryErrorCallback {
(error: { query: EntityQuery; httpResponse: HttpResponse; entityManager: EntityManager; message?: string; stack?:string }): void;
}
interface SaveChangesSuccessCallback {
export interface SaveChangesSuccessCallback {
(saveResult: SaveResult): void;
}
interface EntityError {
export interface EntityError {
entity: Entity;
errorMessage: string;
errorName: string;
@@ -487,7 +509,7 @@ declare namespace breeze {
propertyName: string;
}
interface SaveChangesErrorCallback {
export interface SaveChangesErrorCallback {
(error: {
entityErrors: EntityError[];
httpResponse: HttpResponse;
@@ -497,26 +519,26 @@ declare namespace breeze {
}): void;
}
class EntityChangedEventArgs {
export class EntityChangedEventArgs {
entity: Entity;
entityAction: EntityActionSymbol;
args: Object;
}
class EntityChangedEvent extends breeze.core.Event {
export class EntityChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: EntityChangedEventArgs) => void): number;
}
class HasChangesChangedEventArgs {
export class HasChangesChangedEventArgs {
entityManager: EntityManager;
hasChanges: boolean;
}
class HasChangesChangedEvent extends breeze.core.Event {
export class HasChangesChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: HasChangesChangedEventArgs) => void): number;
}
class EntityQuery {
export class EntityQuery {
entityManager: EntityManager;
orderByClause: OrderByClause;
parameters: Object;
@@ -573,10 +595,10 @@ declare namespace breeze {
toJSON(): string;
}
interface OrderByClause {
export interface OrderByClause {
}
class EntityStateSymbol extends breeze.core.EnumSymbol {
export class EntityStateSymbol extends breeze.core.EnumSymbol {
isAdded(): boolean;
isAddedModifiedOrDeleted(): boolean;
isDeleted(): boolean;
@@ -585,16 +607,16 @@ declare namespace breeze {
isUnchanged(): boolean;
isUnchangedOrModified(): boolean;
}
interface EntityState extends breeze.core.IEnum {
export interface EntityState extends breeze.core.IEnum {
Added: EntityStateSymbol;
Deleted: EntityStateSymbol;
Detached: EntityStateSymbol;
Modified: EntityStateSymbol;
Unchanged: EntityStateSymbol;
}
var EntityState: EntityState;
export var EntityState: EntityState;
class EntityType implements IStructuralType {
export class EntityType implements IStructuralType {
autoGeneratedKeyType: AutoGeneratedKeyType;
baseEntityType: EntityType;
complexProperties: DataProperty[];
@@ -630,7 +652,7 @@ declare namespace breeze {
toString(): string;
}
interface EntityTypeOptions {
export interface EntityTypeOptions {
shortName?: string;
namespace?: string;
autoGeneratedKeyType?: AutoGeneratedKeyType;
@@ -639,24 +661,24 @@ declare namespace breeze {
navigationProperties?: NavigationProperty[];
}
interface EntityTypeProperties {
export interface EntityTypeProperties {
autoGeneratedKeyType?: AutoGeneratedKeyType;
defaultResourceName?: string;
serializerFn?: (dataProperty: DataProperty, value: any) => any;
}
class FetchStrategySymbol extends breeze.core.EnumSymbol {
export class FetchStrategySymbol extends breeze.core.EnumSymbol {
private foo; // to distinguish this class from MergeStrategySymbol
}
interface FetchStrategy extends breeze.core.IEnum {
export interface FetchStrategy extends breeze.core.IEnum {
FromLocalCache: FetchStrategySymbol;
FromServer: FetchStrategySymbol;
}
var FetchStrategy: FetchStrategy;
export var FetchStrategy: FetchStrategy;
class FilterQueryOpSymbol extends breeze.core.EnumSymbol {
export class FilterQueryOpSymbol extends breeze.core.EnumSymbol {
}
interface FilterQueryOp extends breeze.core.IEnum {
export interface FilterQueryOp extends breeze.core.IEnum {
Contains: FilterQueryOpSymbol;
EndsWith: FilterQueryOpSymbol;
Equals: FilterQueryOpSymbol;
@@ -670,9 +692,9 @@ declare namespace breeze {
Any: FilterQueryOpSymbol;
All: FilterQueryOpSymbol;
}
var FilterQueryOp: FilterQueryOp;
export var FilterQueryOp: FilterQueryOp;
class LocalQueryComparisonOptions {
export class LocalQueryComparisonOptions {
static caseInsensitiveSQL: LocalQueryComparisonOptions;
static defaultInstance: LocalQueryComparisonOptions;
@@ -681,17 +703,17 @@ declare namespace breeze {
setAsDefault(): void;
}
class MergeStrategySymbol extends breeze.core.EnumSymbol {
export class MergeStrategySymbol extends breeze.core.EnumSymbol {
}
interface MergeStrategy extends breeze.core.IEnum {
export interface MergeStrategy extends breeze.core.IEnum {
OverwriteChanges: MergeStrategySymbol;
PreserveChanges: MergeStrategySymbol;
SkipMerge: MergeStrategySymbol;
Disallowed: MergeStrategySymbol;
}
var MergeStrategy: MergeStrategy;
export var MergeStrategy: MergeStrategy;
class MetadataStore {
export class MetadataStore {
constructor();
constructor(config?: MetadataStoreOptions);
namingConvention: NamingConvention;
@@ -707,7 +729,7 @@ declare namespace breeze {
static importMetadata(exportedString: string): MetadataStore;
importMetadata(exportedString: string, allowMerge?: boolean): MetadataStore;
isEmpty(): boolean;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) => void, noTrackingFn?: (entity: Entity) => Entity): void;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) => void, noTrackingFn?: (node: Object, entityType: EntityType) => Object): void;
trackUnmappedType(entityCtor: Function, interceptor?: Function): void;
setEntityTypeForResourceName(resourceName: string, entityType: EntityType): void;
setEntityTypeForResourceName(resourceName: string, entityTypeName: string): void;
@@ -715,12 +737,12 @@ declare namespace breeze {
setProperties(config: { name?: string; serializerFn?: Function }): void;
}
interface MetadataStoreOptions {
export interface MetadataStoreOptions {
namingConvention?: NamingConvention;
localQueryComparisonOptions?: LocalQueryComparisonOptions;
}
class NamingConvention {
export class NamingConvention {
static camelCase: NamingConvention;
static defaultInstance: NamingConvention;
static none: NamingConvention;
@@ -736,12 +758,12 @@ declare namespace breeze {
setAsDefault(): NamingConvention;
}
interface NamingConventionOptions {
export interface NamingConventionOptions {
serverPropertyNameToClient?: (name: string) => string;
clientPropertyNameToServer?: (name: string) => string;
}
class NavigationProperty implements IProperty {
export class NavigationProperty implements IProperty {
associationName: string;
entityType: EntityType;
foreignKeyNames: string[];
@@ -750,6 +772,8 @@ declare namespace breeze {
isNavigationProperty: boolean;
isScalar: boolean;
name: string;
nameOnServer: string;
displayName: string;
parentType: IStructuralType;
relatedDataProperties: DataProperty[];
validators: Validator[];
@@ -757,7 +781,7 @@ declare namespace breeze {
constructor(config: NavigationPropertyOptions);
}
interface NavigationPropertyOptions {
export interface NavigationPropertyOptions {
name?: string;
nameOnServer?: string;
entityTypeName: string;
@@ -768,15 +792,21 @@ declare namespace breeze {
validators?: Validator[];
}
class Predicate {
export interface IRecursiveArray<T> {
[i: number]: T | IRecursiveArray<T>;
}
export class Predicate {
constructor();
constructor(property: string, operator: string, value: any);
constructor(property: string, operator: FilterQueryOpSymbol, value: any);
constructor(property: string, operator: string, value: { value: any; isLiteral?: boolean; dataType?: breeze.DataType });
constructor(property: string, operator: FilterQueryOpSymbol, value: { value: any; isLiteral?: boolean; dataType?: breeze.DataType });
constructor(property: string, filterop: FilterQueryOpSymbol, property2: string, filterop2: FilterQueryOpSymbol, value: any); // for any/all clauses
constructor(property: string, filterop: string, property2: string, filterop2: string, value: any); // for any/all clauses
/** Create predicate from an expression tree */
constructor(tree: Object);
constructor(passthru: string);
constructor(predicate: Predicate);
constructor(anArray: IRecursiveArray<string | number | FilterQueryOpSymbol | Predicate>);
and: PredicateMethod;
static and: PredicateMethod;
@@ -798,7 +828,7 @@ declare namespace breeze {
toJSON(): string;
}
interface PredicateMethod {
export interface PredicateMethod {
(predicates: Predicate[]): Predicate;
(...predicates: Predicate[]): Predicate;
(property: string, operator: string, value: any, valueIsLiteral?: boolean): Predicate;
@@ -807,7 +837,7 @@ declare namespace breeze {
(property: string, filterop: string, property2: string, filterop2: string, value: any): Predicate; // for any/all clauses
}
class QueryOptions {
export class QueryOptions {
static defaultInstance: QueryOptions;
fetchStrategy: FetchStrategySymbol;
mergeStrategy: MergeStrategySymbol;
@@ -822,12 +852,12 @@ declare namespace breeze {
using(config: FetchStrategySymbol): QueryOptions;
}
interface QueryOptionsConfiguration {
export interface QueryOptionsConfiguration {
fetchStrategy?: FetchStrategySymbol;
mergeStrategy?: MergeStrategySymbol;
}
interface HttpResponse {
export interface HttpResponse {
config: any;
data: Entity[];
error?: any;
@@ -836,7 +866,7 @@ declare namespace breeze {
getHeaders(headerName: string): string
}
interface QueryResult {
export interface QueryResult {
/** Top level entities returned */
results: Entity[];
/** Query that was executed */
@@ -851,33 +881,33 @@ declare namespace breeze {
retrievedEntities?: Entity[]
}
class SaveOptions {
export class SaveOptions {
allowConcurrentSaves: boolean;
resourceName: string;
dataService: DataService;
tag: Object;
static defaultInstance: SaveOptions;
constructor(config?: { allowConcurrentSaves?: boolean; resourceName?: string; dataService?: DataService; tag?: any});
constructor(config?: { allowConcurrentSaves?: boolean; resourceName?: string; dataService?: DataService; tag?: any });
setAsDefault(): SaveOptions;
using(config: SaveOptionsConfiguration): SaveOptions;
}
interface SaveOptionsConfiguration {
export interface SaveOptionsConfiguration {
allowConcurrentSaves?: boolean;
resourceName?: string;
dataService?: DataService;
tag?: Object;
}
interface SaveResult {
export interface SaveResult {
entities: Entity[];
keyMappings: any;
XHR: XMLHttpRequest;
}
class ValidationError {
export class ValidationError {
key: string;
context: any;
errorMessage: string;
@@ -889,7 +919,7 @@ declare namespace breeze {
constructor(validator: Validator, context: any, errorMessage: string, key: string);
}
class ValidationOptions {
export class ValidationOptions {
static defaultInstance: ValidationOptions;
validateOnAttach: boolean;
validateOnPropertyChange: boolean;
@@ -902,14 +932,14 @@ declare namespace breeze {
using(config: ValidationOptionsConfiguration): ValidationOptions;
}
interface ValidationOptionsConfiguration {
export interface ValidationOptionsConfiguration {
validateOnAttach?: boolean;
validateOnSave?: boolean;
validateOnQuery?: boolean;
validateOnPropertyChange?: boolean;
}
class Validator {
export class Validator {
/** Map of standard error message templates keyed by validator name.*/
static messageTemplates: any;
context: any;
@@ -962,7 +992,7 @@ declare namespace breeze {
/** Creates a regular expression validator with a fixed expression. */
static makeRegExpValidator(validatorName: string, expression: RegExp, defaultMessage: string, context?: any): Validator;
/** Run this validator against the specified value.
/** Run this validator against the specified value.
@param value {Object} Value to validate
@param additionalContext {Object} Any additional contextual information that the Validator can make use of.
@return {ValidationError|null} A ValidationError if validation fails, null otherwise */
@@ -972,11 +1002,11 @@ declare namespace breeze {
getMessage(): string;
}
interface ValidatorFunction {
export interface ValidatorFunction {
(value: any, context: ValidatorFunctionContext): void;
}
interface ValidatorFunctionContext {
export interface ValidatorFunctionContext {
value: any;
validatorName: string;
displayName: string;
@@ -984,84 +1014,89 @@ declare namespace breeze {
message?: string;
}
var metadataVersion: string;
var remoteAccess_odata: string;
var remoteAccess_webApi: string;
var version: string;
export var metadataVersion: string;
export var remoteAccess_odata: string;
export var remoteAccess_webApi: string;
export var version: string;
}
declare namespace breeze.config {
var ajax: string;
var dataService: string;
var functionRegistry: Object;
export var ajax: string;
export var dataService: string;
export var functionRegistry: Object;
/**
Returns the ctor function used to implement a specific interface with a specific adapter name.
@method getAdapter
@param interfaceName {String} One of the following interface names "ajax", "dataService" or "modelLibrary"
@param [adapterName] {String} The name of any previously registered adapter. If this parameter is omitted then
@param adapterName {String} The name of any previously registered adapter. If this parameter is omitted then
this method returns the "default" adapter for this interface. If there is no default adapter, then a null is returned.
@return {Function|null} Returns either a ctor function or null.
@returns {Function|null} Returns either a ctor function or null.
**/
export function getAdapter(interfaceName: string, adapterName?: string): Function;
/**
Returns the adapter instance corresponding to the specified interface and adapter names.
@method getAdapterInstance
@param interfaceName {String} The name of the interface.
@param [adapterName] {String} - The name of a previously registered adapter. If this parameter is
@param adapterName {String} - The name of a previously registered adapter. If this parameter is
omitted then the default implementation of the specified interface is returned. If there is
no defaultInstance of this interface, then the first registered instance of this interface is returned.
@return {an instance of the specified adapter}
**/
export function getAdapterInstance(interfaceName: string, adapterName?: string): Object;
/**
Initializes a single adapter implementation. Initialization means either newing a instance of the
Initializes a single adapter implementation. Initialization means either newing a instance of the
specified interface and then calling "initialize" on it or simply calling "initialize" on the instance
if it already exists.
@method initializeAdapterInstance
@param interfaceName {String} The name of the interface to which the adapter to initialize belongs.
@param adapterName {String} - The name of a previously registered adapter to initialize.
@param [isDefault=true] {Boolean} - Whether to make this the default "adapter" for this interface.
@param isDefault=true {Boolean} - Whether to make this the default "adapter" for this interface.
@return {an instance of the specified adapter}
**/
export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault?: boolean): void;
export interface AdapterInstancesConfig {
/** the name of a previously registered "ajax" adapter */
ajax?: string;
/** the name of a previously registered "dataService" adapter */
dataService?: string;
/** the name of a previously registered "modelLibrary" adapter */
modelLibary?: string;
/** the name of a previously registered "uriBuilder" adapter */
uriBuilder?: string;
}
/**
Initializes a collection of adapter implementations and makes each one the default for its corresponding interface.
@method initializeAdapterInstances
@param config {Object}
@param [config.ajax] {String} - the name of a previously registered "ajax" adapter
@param [config.dataService] {String} - the name of a previously registered "dataService" adapter
@param [config.modelLibrary] {String} - the name of a previously registered "modelLibrary" adapter
@param [config.uriBuilder] {String} - the name of a previously registered "uriBuilder" adapter
@param config {AdapterInstancesConfig}
@return [array of instances]
**/
export function initializeAdapterInstances(config: Object): Object[];
var interfaceInitialized: Event;
var interfaceRegistry: Object;
var objectRegistry: Object;
export function initializeAdapterInstances(config: AdapterInstancesConfig): Object[];
export var interfaceInitialized: Event;
export var interfaceRegistry: Object;
export var objectRegistry: Object;
/**
Method use to register implementations of standard breeze interfaces. Calls to this method are usually
made as the last step within an adapter implementation.
@method registerAdapter
made as the last step within an adapter implementation.
@param interfaceName {String} - one of the following interface names "ajax", "dataService" or "modelLibrary"
@param adapterCtor {Function} - an ctor function that returns an instance of the specified interface.
@param adapterCtor {Function} - an ctor function that returns an instance of the specified interface.
**/
export function registerAdapter(interfaceName: string, adapterCtor: Function): void;
export function registerFunction(fn: Function, fnName: string): void;
export function registerType(ctor: Function, typeName: string): void;
//static setProperties(config: Object): void; //deprecated
/**
/**
Set the promise implementation, if Q.js is not found.
@param q - implementation of promise. @see http://wiki.commonjs.org/wiki/Promises/A
*/
export function setQ(q: breeze.promises.IPromiseService): void;
var stringifyPad: string;
var typeRegistry: Object;
export var stringifyPad: string;
export var typeRegistry: Object;
}
/** Promises interface used by Breeze. Usually implemented by Q (https://github.com/kriskowal/q) or angular.$q using breeze.config.setQ(impl) */
declare namespace breeze.promises {
interface IPromise<T> {
export interface IPromise<T> {
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => U): IPromise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason: any) => U): IPromise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => IPromise<U>): IPromise<U>;
@@ -1071,13 +1106,13 @@ declare namespace breeze.promises {
finally(finallyCallback: () => any): IPromise<T>;
}
interface IDeferred<T> {
export interface IDeferred<T> {
promise: IPromise<T>;
resolve(value: T): void;
reject(reason: any): void;
}
interface IPromiseService {
export interface IPromiseService {
defer<T>(): IDeferred<T>;
reject(reason?: any): IPromise<any>;
resolve<T>(object: T): IPromise<T>;
@@ -1085,3 +1120,6 @@ declare namespace breeze.promises {
}
}
declare module "breeze" {
export = breeze;
}
+33
View File
@@ -0,0 +1,33 @@
/// <reference path="browser-pack.d.ts" />
import browserPack = require("browser-pack");
module BrowserPackTest {
export function packIt(opts?: BrowserPack.Options) {
var packOpts: BrowserPack.Options = {
basedir: opts.basedir || "./",
externalRequireName: opts.externalRequireName || "require",
hasExports: opts.hasExports || false,
prelude: opts.prelude || undefined,
preludePath: opts.preludePath || undefined,
raw: opts.raw || false,
sourceMapPrefix: opts.sourceMapPrefix || '//#',
standalone: opts.standalone || undefined,
standaloneModule: opts.standaloneModule || undefined,
};
var res = browserPack(); // 'opts' are optional
var res2 = browserPack(packOpts);
// ensure return value is a stream
var res3 = res.pipe(res2);
res.on("error", function (err: any) {
console.error("browser-pack error: ", err);
});
}
}
export = BrowserPackTest;
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for browser-pack v6.0.1
// Project: https://github.com/substack/browser-pack
// Definitions by: TeamworkGuy2 <https://github.com/TeamworkGuy2>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/** pack node-style source files from a json stream into a browser bundle
*/
declare module BrowserPack {
export interface Options {
/** Whether the bundle should include require= (or the opts.externalRequireName) so that
* require() is available outside the bundle
*/
hasExports?: boolean;
/** A string to use in place of 'require' if opts.hasExports is specified, default is 'require'
*/
externalRequireName?: string;
/** Specify a custom prelude, but know what you're doing first. See the prelude.js file in
* this repo for the default prelude. If you specify a custom prelude, you must also specify
* a valid opts.preludePath to the prelude source file for sourcemaps to work
*/
prelude?: string;
/** prelude.js path if a custom opts.prelude is specified
*/
preludePath?: string;
/** Used if opts.preludePath is undefined, this is used to resolve the prelude.js file location, default: 'process.cwd()'
*/
basedir?: string;
/** if given, the writable end of the stream will expect objects to be written to
* it instead of expecting a stream of json text it will need to parse, default false
*/
raw?: boolean;
/** External string name to use for UMD, if not provided, UMD declaration is not wrapped around output
*/
standalone?: string;
/** Sets the internal module name to export for standalone
*/
standaloneModule?: string;
/** If given and source maps are computed, the opts.sourceMapPrefix string will be used instead of default: '//#'
*/
sourceMapPrefix?: string;
}
}
declare module "browser-pack" {
/** pack node-style source files from a json stream into a browser bundle
*/
function browserPack(opts?: BrowserPack.Options): NodeJS.ReadWriteStream;
export = browserPack;
}
+39
View File
@@ -0,0 +1,39 @@
/// <reference path="./browser-resolve.d.ts" />
import * as browserResolve from 'browser-resolve';
function basic_test_async(callback: (err?: Error, resolved?: string) => void) {
browserResolve('typescript', function(error, resolved) {
if (error) {
return callback(error);
}
callback(null, resolved);
});
}
function basic_test_sync() {
var resolved = browserResolve.sync('typescript');
}
function options_test_async() {
browserResolve('typescript', {
browser: 'jsnext:main',
filename: './browser-resolve/browser-resolve.js',
modules: {
fs: './fs-shim.js'
}
}, function(error, resolved) {
if (error) {
console.error(error);
return;
}
console.log(resolved);
});
}
function options_test_sync() {
var resolved = browserResolve.sync('typescript', {
filename: './browser-resolve/browser-resolve.js',
modules: {}
});
}
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for browser-resolve
// Project: https://github.com/defunctzombie/node-browser-resolve
// Definitions by: Mario Nebl <https://github.com/marionebl/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../resolve/resolve.d.ts" />
declare module 'browser-resolve' {
import * as resolve from 'resolve';
/**
* Callback invoked when resolving asynchronously
*
* @param error
* @param resolved Absolute path to resolved identifier
*/
type resolveCallback = (err?: Error, resolved?: string) => void;
/**
* Resolve a module path and call cb(err, path [, pkg])
*
* @param id Identifier to resolve
* @param callback
*/
function browserResolve(id: string, cb: resolveCallback): void;
/**
* Resolve a module path and call cb(err, path [, pkg])
*
* @param id Identifier to resolve
* @param options Options to use for resolving, optional.
* @param callback
*/
function browserResolve(id: string, opts: browserResolve.AsyncOpts, cb: resolveCallback): void;
/**
* Returns a module path
*
* @param id Identifier to resolve
* @param options Options to use for resolving, optional.
*/
function browserResolveSync(id: string, opts?: browserResolve.SyncOpts): string;
namespace browserResolve {
interface Opts {
// the 'browser' property to use from package.json (defaults to 'browser')
browser?: string;
// the calling filename where the require() call originated (in the source)
filename?: string;
// modules object with id to path mappings to consult before doing manual resolution (use to provide core modules)
modules?: any;
}
export interface AsyncOpts extends resolve.AsyncOpts, Opts {}
export interface SyncOpts extends resolve.SyncOpts, Opts {}
export var sync: typeof browserResolveSync;
}
export = browserResolve
}
+6 -1
View File
@@ -23,6 +23,11 @@ declare class ByteBuffer
*/
static DEFAULT_CAPACITY: number;
/**
* Default endianess of false for big endian.
*/
static DEFAULT_ENDIAN: boolean;
/**
* Default no assertions flag of false.
*/
@@ -96,7 +101,7 @@ declare class ByteBuffer
/**
* Allocates a new ByteBuffer backed by a buffer of the specified capacity.
*/
static allocate( capacity?: number, littleEndian?: number, noAssert?: boolean ): ByteBuffer;
static allocate( capacity?: number, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a base64 encoded string to binary like window.atob does.
+4 -2
View File
@@ -8,9 +8,11 @@ console.log(bytes(104857, { thousandsSeparator: ' ' }));
console.log(bytes.format(104857));
console.log(bytes.format(104857, { thousandsSeparator: ' ' }));
console.log(bytes.format(104857, { decimalPlaces: 2 }));
console.log(bytes.format(104857, { fixedDecimals: true }));
console.log(bytes.format(104857, { unitSeparator: '-' }));
console.log(bytes('1024kb'));
console.log(bytes(1024));
console.log(bytes.parse('1024kb'));
console.log(bytes.parse(1024));
console.log(bytes.parse(1024));
+9 -4
View File
@@ -1,10 +1,15 @@
// Type definitions for bytes v2.1.0
// Type definitions for bytes v2.4.0
// Project: https://github.com/visionmedia/bytes.js
// Definitions by: Zhiyuan Wang <https://github.com/danny8002/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'bytes' {
interface BytesOptions {
decimalPlaces?: number,
thousandsSeparator?: string,
unitSeparator?: string,
fixedDecimals?: boolean
}
/**
*Convert the given value in bytes into a string.
*
@@ -15,7 +20,7 @@ declare module 'bytes' {
*
* @returns {string}
*/
function bytes(value: number, options?: { thousandsSeparator: string }): string;
function bytes(value: number, options?: BytesOptions): string;
/**
*Parse string to an integer in bytes.
@@ -37,7 +42,7 @@ declare module 'bytes' {
* @param {BytesFormatOptions} [options]
*/
function format(value: number, options?: { thousandsSeparator: string }): string;
function format(value: number, options?: BytesOptions): string;
/**
* Just return the input number value.
+51
View File
@@ -0,0 +1,51 @@
/// <reference path="cache-manager.d.ts" />
import * as cacheManager from 'cache-manager'
const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });
const ttl = 5;
memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {
if (err) {
throw err;
}
memoryCache.get('foo', (err, result) => {
// console.log(result);
memoryCache.del('foo', (err) => {
});
});
});
function getUser(id: number, cb: Function) {
cb(null, { id: id, name: 'Bob' });
}
const userId = 123;
const key = 'user_' + userId;
// Note: ttl is optional in wrap()
memoryCache.wrap<{ id: number, name: string }>(key, (cb) => {
getUser(userId, cb);
}, { ttl: ttl }, (err, user) => {
//console.log(user);
// Second time fetches user from memoryCache
memoryCache.wrap<{ id: number, name: string }>(key, (cb) => {
getUser(userId, cb);
}, (err, user) => {
//console.log(user);
});
});
+36
View File
@@ -0,0 +1,36 @@
// Type definitions for cache-manager v1.2.0
// Project: https://github.com/BryanDonovan/node-cache-manager
// Definitions by: Simon Gausmann <https://github.com/GausSim/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'cache-manager' {
interface CachingConfig {
ttl: number;
}
interface StoreConfig extends CachingConfig {
store: string;
max?: number;
isCacheableValue?: (value: any) => boolean;
}
interface Cache {
set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;
set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, options: CachingConfig, callback: (error: any, result: T) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, callback: (error: any, result: T) => void): void;
get<T>(key: string, callback: (error: any, result: T) => void): void;
del(key: string, callback?: (error: any) => void): void;
}
module cacheManager {
function caching(ICongig: StoreConfig): Cache;
function multiCaching(Caches: Cache[]): Cache;
}
export = cacheManager;
}
+761
View File
@@ -0,0 +1,761 @@
// Type definitions for nodejs-driver v0.8.2
// Project: https://github.com/datastax/nodejs-driver
// Definitions by: Marc Fisher <http://github.com/Svjard>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../long/long.d.ts" />
declare module "cassandra-driver" {
type Callback = Function;
type ResultCallback = (err: Error, result: types.ResultSet) => void;
import * as events from "events";
import * as stream from "stream";
import _Long = require("long");
namespace policies {
namespace addressResolution {
var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic;
interface AddressTranslator {
translate(address: string, port: number, callback: Callback): void;
}
interface EC2MultiRegionTranslatorStatic {
new(): EC2MultiRegionTranslator;
}
interface EC2MultiRegionTranslator extends AddressTranslator {
logError(address: string, err: Error): void;
}
}
namespace loadBalancing {
var DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic;
var RoundRobinPolicy: RoundRobinPolicyStatic;
var TokenAwarePolicy: TokenAwarePolicyStatic;
var WhiteListPolicy: WhiteListPolicyStatic;
interface LoadBalancingPolicy {
init(client: Client, hosts: HostMap, callback: Callback): void;
getDistance(host: Host): types.distance;
newQueryPlan(keyspace: string, queryOptions: any, callback: Callback): void;
}
interface DCAwareRoundRobinPolicyStatic {
new(localDc?: string, usedHostsPerRemoteDc?: number): DCAwareRoundRobinPolicy;
}
interface DCAwareRoundRobinPolicy extends LoadBalancingPolicy {
localHostsArray: Array<Host>;
remoteHostsArray: Array<Host>;
}
interface RoundRobinPolicyStatic {
new(): RoundRobinPolicy;
}
interface RoundRobinPolicy extends LoadBalancingPolicy {}
interface TokenAwarePolicyStatic {
new(childPolicy: LoadBalancingPolicy): TokenAwarePolicy;
}
interface TokenAwarePolicy extends LoadBalancingPolicy {}
interface WhiteListPolicyStatic {
new(childPolicy: LoadBalancingPolicy, whiteList: Array<string>): WhiteListPolicy;
}
interface WhiteListPolicy extends LoadBalancingPolicy {}
}
namespace reconnection {
var ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic;
var ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic;
interface ReconnectionPolicy {
newSchedule(): {next: Function};
}
interface ConstantReconnectionPolicyStatic {
new(delay: number): ConstantReconnectionPolicy;
}
interface ConstantReconnectionPolicy extends ReconnectionPolicy {}
interface ExponentialReconnectionPolicyStatic {
new(baseDelay: number, maxDelay: number, startWithNoDelay: boolean): ExponentialReconnectionPolicy;
}
interface ExponentialReconnectionPolicy extends ReconnectionPolicy {}
}
namespace retry {
var RetryPolicy: RetryPolicyStatic;
interface DecisionInfo {
decision: number;
consistency: number;
}
interface RequestInfo {
request: any,
nbRetry: number
}
enum retryDecision {
rethrow = 0,
retry,
ignore
}
interface RetryPolicyStatic {
new (): RetryPolicy;
retryDecision: any;
}
interface RetryPolicy {
onReadTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, isDataPresent: boolean): DecisionInfo;
onUnavailable(requestInfo: RequestInfo, consistency: types.consistencies, required: number, alive: number): DecisionInfo;
onWriteTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, writeType: string): DecisionInfo;
rethrowResult(): { decision: retryDecision };
retryResult(): { decision: retryDecision, consistency: types.consistencies, useCurrentHost: boolean };
}
}
}
namespace types {
var BigDecimal: BigDecimalStatic;
var InetAddress: InetAddressStatic;
var Integer: IntegerStatic;
var LocalDate: LocalDateStatic;
var LocalTime: LocalTimeStatic;
var Long: _Long;
var ResultSet: ResultSetStatic;
var ResultStream: ResultStreamStatic;
var Row: RowStatic;
var TimeUuid: TimeUuidStatic;
var Tuple: TupleStatic;
var Uuid: UuidStatic;
enum consistencies {
any = 0,
one,
two,
three,
quorum,
all,
localQuorm,
eachQuorum,
serial,
localSerial,
localOne
}
enum dataTypes {
custom = 0,
ascii,
bigint,
blob,
boolean,
counter,
decimal,
double,
float,
int,
text,
timestamp,
uuid,
varchar,
varint,
timeuuid,
inet,
date,
time,
smallint,
tinyint,
list,
map,
set,
udt,
tuple
}
enum distance {
local = 0,
remote,
ignored
}
interface responseErrorCodes { [key:string]:number; }
interface unset { unset: boolean; }
function generateTimestamp(date?: Date, microseconds?: number): _Long;
function timeuuid(options?: {msecs: number | Date, node: Buffer, clockseq: number, nsecs: number}, buffer?: Buffer, offset?: number): string;
interface BigDecimalStatic {
new (unscaledValue: number, scale: number): BigDecimal;
fromBuffer(buf: Buffer): BigDecimal;
toBuffer(value: BigDecimal): Buffer;
fromString(value: string): BigDecimal;
fromNumber(value: number): BigDecimal;
}
interface BigDecimal {
equals(other: BigDecimal): boolean;
inspect(): string;
notEquals(other: BigDecimal): boolean;
compare(other: BigDecimal): number;
subtract(other: BigDecimal): BigDecimal;
add(other: BigDecimal): BigDecimal;
greaterThan(other: BigDecimal): boolean;
isNegative(): boolean;
isZero(): boolean;
toString(): string;
toNumber(): number;
toJSON(): string;
}
interface InetAddressStatic {
new(buffer: Buffer): InetAddress;
fromString(value: string): InetAddress;
}
interface InetAddress {
equals(other: InetAddress): boolean;
getBuffer(): Buffer;
inspect(): string;
toString(): string;
toJSON(): string;
length: number;
version: number;
}
interface IntegerStatic {
new(bits: Array<number>, sign: number): Integer;
fromInt(value: number): Integer;
fromNumber(value: number): Integer;
fromBits(bits: Array<number>): Integer;
fromString(str: string, opt_radix?: number): Integer;
fromBuffer(bits: Buffer): Integer;
toBuffer(value: Integer): Buffer;
ZERO: Integer;
ONE: Integer;
}
interface Integer {
toInt(): number;
toNumber(): number;
toString(opt_radix?: number): string;
getBits(index: number): number;
getBitsUnsigned(index: number): number;
getSign(): number;
isZero(): boolean;
isNegative(): boolean;
isOdd(): boolean;
equals(other: Integer): boolean;
notEquals(other: Integer): boolean;
greaterThan(other: Integer): boolean;
greaterThanOrEqual(other: Integer): boolean;
lessThan(other: Integer): boolean;
lessThanOrEqual(other: Integer): boolean;
compare(other: Integer): number;
shorten(numBits: number): Integer;
negate(): Integer;
add(other: Integer): Integer;
subtract(other: Integer): Integer;
multiply(other: Integer): Integer;
divide(other: Integer): Integer;
modulo(other: Integer): Integer;
not(): Integer;
and(other: Integer): Integer;
or(other: Integer): Integer;
xor(other: Integer): Integer;
shiftLeft(numBits: number): Integer;
shiftRight(numBits: number): Integer;
inspect(): string;
abs(): Integer;
toJSON(): string;
}
interface LocalDateStatic {
new(year: number, month: number, day: number): LocalDate;
now(): LocalDate;
utcNow(): LocalDate;
fromDate(date: Date): LocalDate;
fromString(value: string): LocalDate;
fromBuffer(buffer: Buffer): LocalDate;
}
interface LocalDate {
_value: number;
year: number;
month: number;
day: number;
equals(other: LocalDate): boolean;
inspect(): string;
toBuffer(): Buffer;
toString(): string;
toJSON(): string;
}
interface LocalTimeStatic {
new (totalNanoseconds: _Long): LocalTime;
fromString(value: string): LocalTime;
now(nanoseconds?: number): LocalTime;
fromDate(date: Date, nanoseconds: number): LocalTime;
fromMilliseconds(milliseconds: number, nanoseconds?: number): LocalTime;
fromBuffer(value: Buffer): LocalTime;
}
interface LocalTime {
hour: number;
minute: number;
second: number;
nanosecond: number;
compare(other: LocalTime): boolean;
equals(other: LocalTime): boolean;
getTotalNanoseconds(): _Long;
inspect(): string;
toBuffer(): Buffer;
toString(): string;
toJSON(): string;
}
interface ResultSetStatic {
new(response: any, host: string, triedHost: { [key:string]: any }, consistency: consistencies): ResultSet;
}
interface ResultSet {
info: {
queriedHost: Host,
triedHosts: { [key:string]:string; },
achievedConsistency: consistencies,
traceId: Uuid,
warnings: Array<string>,
customPayload: any
};
rows: Array<Row>;
rowLength: number;
columns: Array<{ [key:string]:string; }>;
pageState: string;
nextPage: any; // function
first(): Row;
getPageState(): string;
getColumns(): Array<{ [key:string]:string; }>;
}
interface ResultStreamStatic {
new (opt: any): ResultSet;
}
interface ResultStream extends stream.Readable {
buffer: Buffer;
paused: boolean;
_read(): void;
_valve(readNext: Function): void;
add(chunk: Buffer): void;
}
interface RowStatic {
new(columns: Array<{ [key:string]:string; }>): Row;
}
interface Row {
get(columnName: string|number): { [key:string]:any; };
values(): Array<{ [key:string]:any; }>;
keys(): Array<string>;
forEach(callback: Callback): void;
}
interface TimeUuidStatic {
new (value?: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid;
fromDate(date: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid;
fromString(value: string): TimeUuid;
min(date: Date, ticks?: number): TimeUuid;
max(date: Date, ticks?: number): TimeUuid;
now(nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid;
}
interface TimeUuid extends Uuid {
getDatePrecision(): { date: Date, ticks: number };
getDate(): Date;
getNodeId(): Buffer;
getNodeIdString(): string;
}
interface TupleStatic {
new (...arguments: Array<any>): Tuple;
fromArray(elements: Array<any>): Tuple;
}
interface Tuple {
elements: Array<any>;
length: number;
get(index: number): any;
toString(): string;
toJSON(): string;
values(): Array<any>;
}
interface UuidStatic {
new (buffer: Buffer): Uuid;
fromString(value: string): Uuid;
random(): Uuid;
}
interface Uuid {
buffer: Buffer;
getBuffer(): Buffer;
equals(other: types.Uuid): boolean;
toString(): string;
inspect(): string;
toJSON(): string;
}
}
var Client: ClientStatic;
var Host: HostStatic;
var HostMap: HostMapStatic;
var Encoder: EncoderStatic;
interface ClientOptions {
contactPoints: Array<string>,
keyspace: string,
policies?: {
addressResolution?: policies.addressResolution.AddressTranslator,
loadBalancing?: policies.loadBalancing.LoadBalancingPolicy,
reconnection?: policies.reconnection.ReconnectionPolicy,
retry?: policies.retry.RetryPolicy
},
queryOptions?: QueryOptions,
pooling?: {
heartBeatInterval: number,
coreConnectionsPerHost: { [key:number]:number; },
warmup: boolean;
},
protocolOptions?: {
port: number,
maxSchemaAgreementWaitSeconds: number,
maxVersion: number
},
socketOptions?: {
connectTimeout: number,
defunctReadTimeoutThreshold: number,
keepAlive: boolean,
keepAliveDelay: number,
readTimeout: number,
tcpNoDelay: boolean,
coalescingThreshold: number
},
authProvider?: auth.AuthProvider,
sslOptions?: any,
encoding?: {
map: Function,
set: Function,
copyBuffer: boolean,
useUndefinedAsUnset: boolean
}
}
interface QueryOptions {
autoPage?: boolean;
captureStackTrace?: boolean;
consistency: number;
customPayload?: any;
fetchSize?: number;
hints: Array<string> | Array<Array<string>>;
logged?: boolean;
pageState?: Buffer|string;
prepare?: boolean;
readTimeout?: number;
retry?: policies.retry.RetryPolicy;
retryOnTimeout?: boolean;
routingIndexes?: Array<number>;
routingKey?: Buffer | Array<Buffer>;
routingNames?: Array<string>;
serialConsistency?: number;
timestamp?: number | _Long;
traceQuery?: boolean;
}
interface ClientStatic {
new(options?: ClientOptions): Client;
}
interface Client extends events.EventEmitter {
hosts: HostMap;
keyspace: string;
metadata: metadata.Metadata;
batch(queries: Array<string>|Array<{query: string, params?: any}>, options: QueryOptions, callback: ResultCallback): void;
connect(callback: Callback): void;
eachRow(query: string, params?: any, options?: QueryOptions, rowCallback?: Callback, callback?: Callback): void;
execute(query: string, params?: any, options?: QueryOptions, callback?: ResultCallback): void;
getReplicas(keyspace: string, token: Buffer): Array<any>; // TODO: Should this be a more explicit return?
shutdown(callback?: Callback): void;
stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): void;
}
interface HostStatic {
new(address: string, protocolVersion: number, options: ClientOptions): Host;
}
interface Host extends events.EventEmitter {
address: string;
cassandraVersion: string;
dataCenter: string;
rack: string;
tokens: Array<string>;
canBeConsideredAsUp(): boolean;
getCassandraVersion(): Array<number>;
isUp(): boolean;
}
interface HostMapStatic {
new (): HostMap;
}
interface HostMap extends events.EventEmitter {
length: number;
forEach(callback: Callback): void;
get(key: string): Host;
keys(): Array<string>;
remove(key: string): void;
removeMultiple(keys: Array<string>): void;
set(key: string, value: Host): void;
values(): Array<Host>;
}
interface EncoderStatic {
new(protocolVersion: number, options: ClientOptions) : Encoder;
}
interface Encoder {
decode(buffer: Buffer, type: {code: number, info?: any}): void;
encode(value: any, typeInfo?: string|number|{code: number, info?: any}): Buffer;
}
namespace auth {
var Authenticator: AuthenticatorStatic;
var PlainTextAuthProvider: PlainTextAuthProviderStatic;
interface AuthenticatorStatic {
new (): Authenticator;
}
interface Authenticator {
evaluateChallenge(challenge: Buffer, callback: Callback): void;
initialResponse(callback: Callback): void;
onAuthenticationSuccess(token?: Buffer): void;
}
interface AuthProvider {
newAuthenticator(endpoint: string, name: string): void;
}
interface PlainTextAuthProviderStatic {
new (username: string, password: string): PlainTextAuthProvider;
}
interface PlainTextAuthProvider extends AuthProvider {
newAuthenticator(endpoint: string, name: string): void;
}
}
namespace errors {
abstract class DriverError {
constructor(message: string, constructor?: any);
}
class ArgumentError extends DriverError {
constructor(message: string);
}
class AuthenticationError extends DriverError {
constructor(message: string);
}
class DriverInternalError extends DriverError {
constructor(message: string);
}
class NoHostAvailableError extends DriverError {
constructor(innerErrors: any, message?: string);
}
class NotSupportedError extends DriverError {
constructor(message: string);
}
class OperationTimedOutError extends DriverError {}
class ResponseError extends DriverError {
constructor(code: number, message: string);
}
}
namespace metadata {
var Aggregate: AggregateStatic;
var Index: IndexStatic;
var MaterializedView: MaterializedViewStatic;
var Metadata: MetadataStatic;
var SchemaFunction: SchemaFunctionStatic;
var TableMetadata: TableMetadataStatic;
type caching = "all" | "keys_only" | "rows_only" | "none";
interface AggregateStatic {
new (): Aggregate;
}
interface Aggregate {
argumentTypes: Array<{ code: number, info: any}>;
finalFunction: string;
initCondition: string;
keyspaceName: string,
returnType: string;
signature: Array<string>;
stateFunction: string;
stateType: string;
}
interface DataTypeInfo {
code: number,
info: string | DataTypeInfo | Array<DataTypeInfo>,
options: {
frozen: boolean,
reversed: boolean
}
}
interface ColumnInfo {
name: string,
type: DataTypeInfo
}
interface DataCollection {
bloomFilterFalsePositiveChance: number;
caching: caching;
clusterKeys: Array<{ c: ColumnInfo, index: number, order: string }>;
clusteringOrder: Array<string>;
columns: Array<ColumnInfo>;
columnsByName: { [key: string]: ColumnInfo };
comment: string;
compactionClass: string;
compactionOptions: any;
compression: any;
crcCheckChange?: number;
defaultTtl: number;
extensions: any;
gcGraceSeconds: number;
localReadRepairChance: number;
maxIndexInterval?: number;
minIndexInterval?: number;
name: string;
partitionKeys: Array<{ c: ColumnInfo, index: number }>
populateCacheOnFlush: boolean;
readRepairChance: number;
speculateRetry: string;
}
enum IndexType {
custom = 0,
keys,
composites
}
interface IndexStatic {
new (name: string, target: string, kind: IndexType, options: Object): Index;
fromRows(indexRows: Array<types.Row>): Array<Index>;
fromColumnRows(columnRows: Array<types.Row>, columnsByName: { [key:string]: ColumnInfo }): Array<Index>;
}
interface Index {
kind: IndexType;
name: string;
options: Object;
target: string;
isCompositesKind(): boolean;
isCustomKind(): boolean;
isKeysKind(): boolean;
}
interface MaterializedViewStatic {
new (name: string): MaterializedView;
}
interface MaterializedView extends DataCollection {}
interface MetadataStatic {
new (options: ClientOptions, controlConnection: any): Metadata;
}
interface Metadata {
clearPrepared(): void;
getAggregate(keyspaceName: string, name: string, signature: Array<string> | Array<{ code: number, info: any }>, callback: Callback): void;
getAggregates(keyspaceName: string, name: string, callback: Callback): void;
getFunction(keyspaceName: string, name: string, signature: Array<string> | Array<{ code: number, info: any }>, callback: Callback): void;
getFunctions(keyspaceName: string, name: string, callback: Callback): void;
getMaterializedView(keyspaceName: string, name: string, callback: Callback): void;
getReplicas(keyspaceName: string, tokenBuffer: Buffer): Array<any>;
getTable(keyspaceName: string, name: string, callback: Callback): void;
getTrace(traceId: types.Uuid, callback: Callback): void;
getUdt(keyspaceName: string, name: string, callback: Callback): void;
refreshKeyspace(name: string, callback?: Callback): void;
refreshKeyspaces(callback?: Callback): void;
}
interface SchemaFunctionStatic {
new (): SchemaFunction;
}
interface SchemaFunction {
argumentNames: Array<string>;
argumentTypes: Array<{ code: number, info: any}>;
body: string;
calledOnNullInput: boolean;
keyspaceName: string,
language: string;
name: string;
returnType: string;
signature: Array<string>;
}
interface TableMetadataStatic {
new (name: string): TableMetadata;
}
interface TableMetadata extends DataCollection {
indexes: Array<Index>;
indexInterval?: number;
isCompact: boolean;
memtableFlushPeriod: number;
replicateOnWrite: boolean;
}
}
}
@@ -0,0 +1,11 @@
/// <reference path="cassandra-driver.d.ts" />
import * as cassandra from 'cassandra-driver';
import * as util from 'util';
var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'});
var query = 'SELECT email, last_name FROM user_profiles WHERE key=?';
client.execute(query, ['guy'], function(err, result) {
console.log('got user profile with email ' + result.rows[0].email);
});
+5 -5
View File
@@ -1,7 +1,7 @@
// Type definitions for chai-things
// Project: https://github.com/chaijs/chai-things
// Definitions by: David Broder-Rodgers <https://github.com/DavidBR-SW/>
// Definitions: https://github.com/DavidBR-SW/DefinitelyTyped
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../chai/chai.d.ts" />
@@ -25,14 +25,14 @@ declare namespace Chai {
interface Anything extends Assertion {
(): any;
that: Assertion
with: Assertion
that: Assertion;
with: Assertion;
}
interface Something extends Assertion {
(): any;
that: Assertion
with: Assertion
that: Assertion;
with: Assertion;
}
interface Item {
+18
View File
@@ -1930,6 +1930,24 @@ suite('assert', () => {
}, 'expected 5 to be below 5');
});
test('isAtLeast', () => {
assert.isAtLeast(5, 3);
assert.isAtLeast(5, 5);
err(() => {
assert.isAtLeast(3, 5);
}, 'expected 3 to be greater than or equal to 5');
});
test('isAtMost', () => {
assert.isAtMost(3, 5);
assert.isAtMost(5, 5);
err(() => {
assert.isAtMost(5, 3);
}, 'expected 5 to be less than or equal to 3');
});
test('extensible', () => { assert.extensible({}); });
test('isExtensible', () => { assert.isExtensible({}); });
test('notExtensible', () => { assert.notExtensible(Object.preventExtensions({})); });
+3
View File
@@ -271,6 +271,9 @@ declare namespace Chai {
isAbove(val: number, abv: number, msg?: string): void;
isBelow(val: number, blw: number, msg?: string): void;
isAtMost(val: number, atmst: number, msg?: string): void;
isAtLeast(val: number, atlst: number, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
+13
View File
@@ -378,7 +378,20 @@ declare namespace Chai {
}
export interface Config {
/**
* Default: false
*/
includeStack: boolean;
/**
* Default: true
*/
showDiff: boolean;
/**
* Default: 40
*/
truncateThreshold: number;
}
export class AssertionError {
+1 -1
View File
@@ -105,7 +105,7 @@ declare namespace Chartist {
plugins?: Array<any>; // all of these plugins seem to be functions with options, but keeping type any for now
update(data: Object, options?: T, override?: boolean): void;
detatch(): void;
detach(): void;
/**
* Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
+1 -1
View File
@@ -641,7 +641,7 @@ declare namespace CKEDITOR {
filebrowserImageBrowseLinkUrl?: string;
filebrowserImageBrowseUrl?: string;
filebrowserImageUploadUrl?: string;
filebrowserUploadUr?: string;
filebrowserUploadUrl?: string;
filebrowserWindowFeatures?: string;
filebrowserWindowHeight?: number | string;
filebrowserWindowWidth?: number | string;
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for cliff 0.1.10
// Project: https://github.com/flatiron/cliff
// Definitions by: bryn austin bellomy <https://github.com/brynbellomy>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "cliff" {
export function inspect(obj:any): string;
export function stringifyRows(rows:string[][], colors?:string[]): string;
export function stringifyObjectRows(rows:Array<{}>, keys:string[], colors?:string[]): string;
export function putRows(level:string, rows:string[][], colors?:string[]): void;
export function putObjectRows(level:string, rows:Array<{}>, keys:string[], colors?:string[]): void;
export function putObject(level:string, object:any, rewriters?:any, padding?:any): void;
}
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="../node/node.d.ts" />
/// <reference path="co-views.d.ts" />
import views = require('co-views');
const render = views('views', {
map: {
html: 'swig'
},
default: 'jade'
});
const fileName = 'xxx'; // template file name
const locals = {}; // template locals data
async function test() {
const html = await render(fileName, locals);
console.log(html);
}
// or use generator
// function* test() {
// const html = yield render(fileName, locals);
// console.log(html);
// }
+68
View File
@@ -0,0 +1,68 @@
// Type definitions for co-views v2.1
// Project: https://github.com/tj/co-views/
// Definitions by: devlee <https://github.com/devlee/>
// Definitions: https://github.com/devlee/DefinitelyTyped
/* =================== USAGE ===================
import views = require('co-views');
const render = views('views', {
map: {
html: 'swig'
},
default: 'jade'
});
=============================================== */
declare module "co-views" {
interface EngineMap {
/**
* use for .html files
*/
html: string
}
interface CoViewsOptions {
/**
* default extname
*/
ext?: string,
/**
* default extname
*/
default?: string,
/**
* engine map
*/
map?: EngineMap,
/**
* proxy partials
*/
partials?: Object,
/**
* cache compiled templates
*/
cache?: boolean,
/**
* common locals data
*/
locals?: Object
}
/**
* Pass views `dir` and `opts` to return a render function.
*/
function views(dir?: string, opts?: CoViewsOptions): {
(view: string, locals?: Object): any
};
export = views;
}
+10 -8
View File
@@ -220,14 +220,7 @@ declare namespace CodeMirror {
/** Get an { left , top , width , height , clientWidth , clientHeight } object that represents the current scroll position, the size of the scrollable area,
and the size of the visible area(minus scrollbars). */
getScrollInfo(): {
left: any;
top: any;
width: any;
height: any;
clientWidth: any;
clientHeight: any;
}
getScrollInfo(): CodeMirror.ScrollInfo;
/** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor.
The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */
@@ -609,6 +602,15 @@ declare namespace CodeMirror {
text: string;
}
interface ScrollInfo {
left: any;
top: any;
width: any;
height: any;
clientWidth: any;
clientHeight: any;
}
interface TextMarker {
/** Remove the mark. */
clear(): void;
+73
View File
@@ -0,0 +1,73 @@
// Type definitions for Commangular Mock 0.9.0
// Project: http://commangular.org
// Definitions by: Hiraash Thawfeek <https://github.com/hiraash>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module commangular {
///////////////////////////////////////////////////////////////////////////
// Commangular Static
// see http://commangular.org/docs/#commangular-namespace
///////////////////////////////////////////////////////////////////////////
interface ICommAngularStatic {
/**
* Mock dispatch function for testing commands.
*/
dispatch( ec: ICommandCall, callback: Function ): void;
}
interface ICommandCall {
/**
* Name of the command that needs to
* execute
*/
command: string;
/**
* Data that needs to be passed to the command
*/
data?: any;
}
/**
* Object type expected to be passed into the callback function
* of the dispatch() function
*/
interface ICommandInfo {
/**
* The data that was passed into the command
* @param key The property name that is in the object that was passed
*/
dataPassed( key : string ) : any;
/**
* The data that was returned by the command
* @param key The result key that was defined in the command. If no result
* was defined use 'lastResult' as the key
*/
resultKey( key: string ): any;
/**
* Indicates if the command execution was cancelled.
*/
canceled( ): boolean;
/**
* Indicates if the command was executed????
*/
commandExecuted( ): boolean;
}
}
/**
* Mock dispatch function for testing commands.
* @param ec an ICommandCall object
* @param callback The function that will be called upon the completion of the command
* function should expecte an ICommandInfo paramter.
*/
declare function dispatch( ec: commangular.ICommandCall, callback: Function ): void;
+273
View File
@@ -0,0 +1,273 @@
// Type definitions for Commangular 0.9.0
// Project: http://commangular.org
// Definitions by: Hiraash Thawfeek <https://github.com/hiraash>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../angularjs/angular.d.ts' />
declare var commangular: commangular.ICommAngularStatic;
declare module commangular {
///////////////////////////////////////////////////////////////////////////
// Commangular Static
// see http://commangular.org/docs/#commangular-namespace
///////////////////////////////////////////////////////////////////////////
interface ICommAngularStatic {
/**
* Use this function to create and register a command with Commangular
*
* @param commandName It's the name of the command you are creating. It's useful to reference the command from the command provider.
* @param commandFunction It's the command class that will be executed when commangular runs this command.
* It has to be something that implements ICommand. Same as angular syntax
* @param commandConfig It's and object with paramaters to configure the command execution.
*/
create (commandName: string, commandFunction: Function, commandConfig?:ICommandConfig) : void;
command (commandName: string, commandFunction: Function, commandConfig?:ICommandConfig) : void;
/**
* This function allows you to hijack the execution before or after and
* execute some cross cutting functionality.
* see http://commangular.org/docs/#command-aspects
* @param aspectDescriptor The interceptor descriptor has two parts 'Where' and 'What'.
* Where do you want to intercept? you've 5 options :
* - @Before : The interceptor will be executed before the command. You will be able to
* cancel the command or modify the data that will be injected in the command or do
* some other operation you need before the command execution.
* - @After : The interceptor will be executed just after the command and before any other next
* command. You can get the lastResult from the command, cancel execution etc etc.
* - @AfterExecution : This intercetor is executed just after the command execute method and
* it can get the result from the command and update it before the onResult method is executed.
* - @AfterThrowing : This interceptor will be executed if the command or any interceptor of
* the command throws an exception. You can get the error throwed injected to do what you need.
* - @Around : The interceptor is executed around a command.That means that a especial
* object 'processor' will be injected in the interceptor and you can invoke the command
* or the next interceptor. It will be better explained below.
* @param aspectFunction It's the command class execute function that will be run for the given aspect.
* @param order You can chain any number of interceptors to the same command, so if you need to executed
* the interceptor in a specific order you can indicate it here. An order of 0 is assigned by default.
*/
aspect ( aspectDescriptor: string, aspectFunction: ICommand, order: number ) : void;
/**
* Event aspects work the same way command aspects do, but they intercept all the command groups instead,
* so you can run some function before the command group starts it's execution , after or when any
* command or interceptor in the group throw an exception.
* see http://commangular.org/docs/#event-aspects
* @param aspectDescriptor The interceptor descriptor has two parts 'Where' and 'What'.
* Where do you want to intercept? you've 3 options :
* - @Before : The interceptor will be executed before the command. You will be able to
* cancel the command or modify the data that will be injected in the command or do
* some other operation you need before the command execution.
* - @After : The interceptor will be executed just after the command and before any other next
* command. You can get the lastResult from the command, cancel execution etc etc.
* - @AfterThrowing : This interceptor will be executed if the command or any interceptor of
* the command throws an exception. You can get the error throwed injected to do what you need.
* @param aspectFunction It's the command class execute function that will be run for the given aspect.
* @param order You can chain any number of interceptors to the same command, so if you need to executed
* the interceptor in a specific order you can indicate it here. An order of 0 is assigned by default.
*/
eventAspect( aspectDescriptor: string, aspectFunction: ICommand, order: number ) : void;
/**
* TBD
*/
resolver( commandName: string, resolverFunction : Function ) : void;
/**
* Clears all commands and aspects registered with commangular.
*/
reset() : void;
/**
* Can be used to enable/disable debug
*/
debug( enableDebug : boolean ) : void;
/**
* TBD
*/
build() : void;
}
/**
* The command function/object
* see http://commangular.org/docs/#commangular-namespace
*/
interface ICommand {
/**
* This function is what gets called when the command executes.
* It can take parameters in as injected by angular
*/
execute() : any;
}
interface IResultCommand extends ICommand{
/**
* Is executed after the execute method and the interception chain and can receive
* the result from the execute method of the same command.
*
* @param result Value/object returned by the execution.
*/
onResult ( result: any ) : void;
/**
* Is executed when the executed method ends with an error. Can receive the error throw by the execute method.
* @param error The error that occured during execution
*/
onError ( error: Error ) : void;
}
/**
* The result object expected in the promise returned by the dispatch function
* This must be extended to add custom result keys
* see http://commangular.org/docs/#returning-result-from-commands
*/
interface ICommandResult {
/**
* By defualt the result of the command will be found in this property
*/
lastResult : any;
}
/**
* Command creation configuration
* see http://commangular.org/docs/#the-command-config-object
*/
interface ICommandConfig {
/**
* This property instruct commangular to keep the value returned by the command in the value
* key passed in 'resultKey'. It has to be a string. It means that after the execution of this
* commands you will be able to inject on the next command using that key and the result of the command will be injected.
*/
resultKey : string;
}
/**
* All the command configuration of your application is done in an angular config block and
* with the $commangularProvider. The provider is responsible to build the command strutures and
* map them to the desired event names. You can create multiple configs blocks in angular, so you
* can have multiple command config blocks to separate functional parts of your application.
* see http://commangular.org/docs/#using-the-provider
*/
interface ICommAngularProvider {
/**
* This function lets you map a even name to a command sequence
* @param eventName An event that will be watched by commangular
*/
mapTo( eventName: string ) : ICommAngularDescriptor;
/**
* Used along with mapTo function. Creates a sequence of commands that
* execute after one and other
* see http://commangular.org/docs/#building-command-sequences
*/
asSequence(): ICommAngularDescriptor;
/**
* Used along with mapTo function. Maps commands to be executed parallel
* see http://commangular.org/docs/#building-parallel-commands
*/
asParallel(): ICommAngularDescriptor;
/**
* A command flow is a decision point inside the command group.You can have any number
* of flows inside a command group and nesting them how you perfer.
* see http://commangular.org/docs/#building-command-flows
*/
asFlow(): ICommAngularDescriptor;
findCommand( eventName: string ): ICommAngularDescriptor;
}
/**
* The service that enables the execution of commands
* see http://commangular.org/docs/#dispatching-events
*/
interface ICommAngularService {
/**
* This function executes the given command sequence.
* see http://commangular.org/docs/#dispatching-events
* @param eventName Name of the even that will trigger a command sequence
* @param data Data of any type that will be passed to the command.
*/
dispatch( eventName: string, data?: any ) : ng.IPromise<any>;
}
interface ICommAngularDescriptor {
/**
* Used along with mapTo function. Creates a sequence of commands that
* execute after one and other
* see http://commangular.org/docs/#building-command-sequences
*/
asSequence (): ICommAngularDescriptor;
/**
* Used along with mapTo function. Maps commands to be executed parallel
* see http://commangular.org/docs/#building-parallel-commands
*/
asParallel(): ICommAngularDescriptor;
/**
* A command flow is a decision point inside the command group.You can have any number
* of flows inside a command group and nesting them how you perfer.
* see http://commangular.org/docs/#building-command-flows
*/
asFlow(): ICommAngularDescriptor;
/**
* Add commands to a descriptor.
* @param command The name that was used to create the command.
*/
add ( command: string ): ICommAngularDescriptor;
/**
* Add descriptor to a descriptor.
* @param descriptor Another descriptor attached to a sequnce of commands.
*/
add ( descriptor: ICommAngularDescriptor ): ICommAngularDescriptor;
/**
* This is to be used with flowing commands to attach an expression that
* evaluates using Angular $parse.
* see http://commangular.org/docs/#building-command-flows
* @param expression A string form expression that can make use of services to validate conditions.
* @param services A comma seperated list of services that are used in the above expression
*/
link ( expression: string, services?: string ): ICommAngularDescriptor;
/**
* Works with the <code>link</code> function to attach a command to the flow if the
* expression becomes truthy.
* see http://commangular.org/docs/#building-command-flows
* @param command The name that was used to create the command.
*/
to ( command: string ): ICommAngularDescriptor;
}
}
/**
* Extending the angular rootScope to include the dispatch function in all scopes.
*/
declare module angular {
interface IRootScopeService {
/**
* Commangular method to execute a command.
* @param eventName Name of the even that will trigger a command sequence
* @param data Data of any type that will be passed to the command.
*/
dispatch( eventName: string, data?: any ) : ng.IPromise<any>;
}
}
+156
View File
@@ -0,0 +1,156 @@
/// <reference path="common-tags.d.ts" />
import * as commonTags from 'common-tags';
/* Test Built-in Tags */
commonTags.commaLists `
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
commonTags.commaListsAnd`
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
commonTags.commaListsOr`
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
let fruits = ['apple', 'orange', 'watermelon'];
commonTags.html`
<div class="list">
<ul>
${fruits.map(fruit => `<li>${fruit}</li>`)}
${'<li>kiwi</li>\n<li>guava</li>'}
</ul>
</div>
`;
commonTags.codeBlock`
<div class="list">
<ul>
${fruits.map(fruit => `<li>${fruit}</li>`)}
${'<li>kiwi</li>\n<li>guava</li>'}
</ul>
</div>
`;
commonTags.source`
<div class="list">
<ul>
${fruits.map(fruit => `<li>${fruit}</li>`)}
${'<li>kiwi</li>\n<li>guava</li>'}
</ul>
</div>
`;
commonTags.oneLine`
foo
bar
baz
`;
commonTags.oneLineTrim`
https://news.com/article
?utm_source=designernews.co
`;
commonTags.oneLineCommaLists`
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
commonTags.oneLineCommaListsOr`
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
commonTags.oneLineCommaListsAnd`
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
commonTags.inlineLists`
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
commonTags.oneLineInlineLists`
I like ${['apples', 'bananas', 'watermelons']}
They're good!
`;
let verb = 'notice';
commonTags.stripIndent`
This is a multi-line string.
You'll ${verb} that it is indented.
We don't want to output this indentation.
But we do want to keep this line indented.
`;
commonTags.stripIndents`
This is a multi-line string.
You'll ${verb} that it is indented.
We don't want to output this indentation.
We don't want to keep this line indented either.
`;
/* Test Tag Constructor */
new commonTags.TemplateTag();
const substitutionReplacer = (oldValue : string, newValue : string) => ({
onSubstitution(substitution : string, resultSoFar : string) {
if (substitution === oldValue) {
return newValue;
}
return substitution;
}
});
new commonTags.TemplateTag(substitutionReplacer('fizz', 'buzz'));
new commonTags.TemplateTag(
substitutionReplacer('fizz', 'buzz'),
substitutionReplacer('foo', 'bar')
);
new commonTags.TemplateTag([
substitutionReplacer('fizz', 'buzz'),
substitutionReplacer('foo', 'bar')
]);
new commonTags.TemplateTag({});
new commonTags.TemplateTag({
onEndResult: endResult => `${endResult}!`
});
new commonTags.TemplateTag({
onSubstitution: substitution => `${substitution}!`,
onEndResult: endResult => `${endResult}!`
});
/* Tests Built-in Transformers */
new commonTags.TemplateTag(commonTags.trimResultTransformer());
new commonTags.TemplateTag(commonTags.trimResultTransformer('left'));
new commonTags.TemplateTag(commonTags.trimResultTransformer('right'));
new commonTags.TemplateTag(commonTags.stripIndentTransformer());
new commonTags.TemplateTag(commonTags.stripIndentTransformer('initial'));
new commonTags.TemplateTag(commonTags.stripIndentTransformer('all'));
new commonTags.TemplateTag(commonTags.replaceResultTransformer('foo', 'bar'));
new commonTags.TemplateTag(commonTags.inlineArrayTransformer());
new commonTags.TemplateTag(commonTags.inlineArrayTransformer({}));
new commonTags.TemplateTag(commonTags.inlineArrayTransformer({separator: 'foo'}));
new commonTags.TemplateTag(commonTags.inlineArrayTransformer({conjunction: 'bar'}));
new commonTags.TemplateTag(commonTags.splitStringTransformer('foo'));
+62
View File
@@ -0,0 +1,62 @@
// Type definitions for common-tags v1.2.1
// Project: https://github.com/declandewet/common-tags
// Definitions by: Viktor Zozuliak <https://github.com/zuzusik>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'common-tags' {
type TemplateTag = (literals: string[], ...placeholders: any[]) => string;
type TemplateTransformer = {
onSubstitution?: (substitution: string, resultSoFar: string) => string;
onEndResult?: (endResult : string) => string;
}
/* Built-in Tags */
export var commaLists: TemplateTag;
export var commaListsAnd: TemplateTag;
export var commaListsOr: TemplateTag;
export var html: TemplateTag;
export var codeBlock: TemplateTag;
export var source: TemplateTag;
export var oneLine: TemplateTag;
export var oneLineTrim: TemplateTag;
export var oneLineCommaLists: TemplateTag;
export var oneLineCommaListsOr: TemplateTag;
export var oneLineCommaListsAnd: TemplateTag;
export var inlineLists: TemplateTag;
export var oneLineInlineLists: TemplateTag;
export var stripIndent: TemplateTag;
export var stripIndents: TemplateTag;
/* New Tag Constructor */
export var TemplateTag: {
new(): TemplateTag;
new(...transformers: TemplateTransformer[]): TemplateTag;
new(transformers: TemplateTransformer[]): TemplateTag;
};
/* Built-in Transformers */
export var trimResultTransformer: (side?: 'left'|'right') => TemplateTransformer;
export var stripIndentTransformer: (type?: 'initial'|'all') => TemplateTransformer;
export var replaceResultTransformer: (replaceWhat: string, replaceWith: string) => TemplateTransformer;
export var inlineArrayTransformer: (opts?: {separator?: string, conjunction?: string}) => TemplateTransformer;
export var splitStringTransformer: (splitBy: string) => TemplateTransformer;
}
@@ -0,0 +1,52 @@
/// <reference path='../node/node.d.ts' /> // only for require
/// <reference path='component-emitter.d.ts' />
// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016
// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016
var Emitter = require('component-emitter');
var emitter = new Emitter;
emitter.emit('something');
var user = { name: 'tobi' };
Emitter(user);
(<Emitter>user).emit('im a user');
// this example modified from the one on https://www.npmjs.com/package/component-emitter
var User = Object.create({
someUserFunction: () => {console.log('someUserFunction called!')}
})
var another_user = Emitter(User);
another_user.someUserFunction()
another_user.on('hi', () => {console.log('Hi called')})
another_user.emit('hi')
// Additional sample code for this test
function handleSomeRecurringEvent(event_data: any) {
console.log('handle some-recurring-event')
}
emitter.on('some-recurring-event', handleSomeRecurringEvent)
emitter.once('some-single-shot-event', (event_data: any) => {console.log('handle some-single-shot-event')})
emitter.off()
emitter.off('some-recurring-event')
emitter.off('some-recurring-event', handleSomeRecurringEvent)
var event_data = {some: 'data'}
emitter.emit('some-recurring-event')
emitter.emit('some-recurring-event', event_data)
emitter.listeners('some-recurring-event')
emitter.hasListeners('some-recurring-event')
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for component-emitter v1.2.1
// Project: https://www.npmjs.com/package/component-emitter
// Definitions by: Peter Snider <https://github.com/psnider/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/emitter-component
interface Emitter {
(obj?: Object): Emitter;
on(event: string, listener: Function): Emitter;
once(event: string, listener: Function): Emitter;
off(event?: string, listener?: Function): Emitter;
emit(event: string, ...args: any[]): boolean;
listeners(event: string): Function[];
hasListeners(event: string): boolean;
}
declare module 'component-emitter' {
var Emitter: Emitter;
}
+7
View File
@@ -0,0 +1,7 @@
/// <reference path="./connect-redis.d.ts" />
/// <reference path="../express-session/express-session.d.ts" />
import * as connectRedis from "connect-redis";
import * as session from "express-session";
let RedisStore = connectRedis(session);
+43
View File
@@ -0,0 +1,43 @@
// Type definitions for connect-redis
// Project: https://npmjs.com/package/connect-redis
// Definitions by: Xavier Stouder <https://github.com/xstoudi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
/// <reference path="../express-session/express-session.d.ts" />
/// <reference path="../redis/redis.d.ts" />
declare module "connect-redis" {
import * as express from "express";
import * as session from "express-session";
import * as redis from "redis";
function s(options: (options?: session.SessionOptions) => express.RequestHandler): s.RedisStore;
namespace s {
interface RedisStore extends session.Store {
new (options: RedisStoreOptions): session.Store;
}
interface RedisStoreOptions {
client?: redis.RedisClient;
host?: string;
port?: number;
socket?: string;
url?: string;
ttl?: number;
disableTTL?: boolean;
db?: number;
pass?: string;
prefix?: string;
unref?: boolean;
serializer?: Serializer | JSON;
}
interface Serializer {
stringify: Function;
parse: Function;
}
}
export = s;
}
+11 -37
View File
@@ -1,47 +1,21 @@
/// <reference path="content-type.d.ts" />
/// <reference path="../express/express.d.ts" />
import MediaType = require('content-type');
import contentType = require('content-type');
import express = require('express');
// 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";
var obj = contentType.parse('image/svg+xml; charset=utf-8');
q.q = 1;
q.toString() === 'application/json;q=1;profile="http://example.com/schema.json"';
}
console.log(obj.type); // => 'image/svg+xml'
console.log(obj.parameters.charset); // => 'utf-8'
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 req: express.Request;
obj = contentType.parse(req);
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',
];
var res: express.Response;
obj = contentType.parse(res);
console.log('Formats:\n\t' + representations.map(MediaType.parseMedia).join('\n\t'));
var str: string = contentType.format({type: 'image/svg+xml'});
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());
}
+15 -23
View File
@@ -1,32 +1,24 @@
// 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/DefinitelyTyped/DefinitelyTyped
// Type definitions for content-type v1.0.1
// Project: https://www.npmjs.com/package/content-type
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module ContentType {
interface StaticFunctions {
parse(string: string): MediaType;
parse(req: { headers: any; }): MediaType;
parse(res: { getHeader(key: string): string; }): MediaType;
format(obj: MediaType): string;
}
declare namespace 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;
parameters?: any;
}
}
declare module "content-type" {
var x: ContentType.MediaTypeStatic;
var x: ContentType.StaticFunctions;
export = x;
}
+3 -1
View File
@@ -16,7 +16,8 @@ declare namespace BeaconPlugin {
export interface LocationManager {
delegate: Delegate;
BeaconRegion: BeaconRegion;
onDomDelegateReady(): void;
Region: Region;
onDomDelegateReady(): Q.Promise<void>;
startMonitoringForRegion(region: Region): Q.Promise<void>;
stopMonitoringForRegion(region: Region): Q.Promise<void>;
requestStateForRegion(region: Region): Q.Promise<void>;
@@ -49,6 +50,7 @@ declare namespace BeaconPlugin {
beacons: Beacon[];
authorizationStatus: string;
state: string;
error: string;
}
export interface Delegate {
@@ -9,6 +9,18 @@ interface Plugins {
declare module SocialSharingPlugin {
interface ShareOptions {
message: string;
subject?: string;
files?: string | string[];
url?: string;
}
interface ShareResult {
completed: boolean;
app: any;
}
export interface SocialSharing {
/**
@@ -23,6 +35,8 @@ declare module SocialSharingPlugin {
share(message: string, subject?: string, fileOrFileArray?: string | string[], url?: string, successCallback?: (succeeded: boolean) => void, errorCallback?: (errormsg: string) => void): void;
shareWithOptions(options: ShareOptions, successCallback?: (result: ShareResult) => void, errorCallback?: (errormsg: string) => void): void;
shareViaTwitter(message: string, file?: string, url?: string, successCallback?: (succeeded: boolean) => void, errorCallback?: (errormsg: string) => void): void;
shareViaFacebook(message: string, fileOrFileArray?: string | string[], url?: string, successCallback?: (succeeded: boolean) => void, errorCallback?: (errormsg: string) => void): void;
@@ -47,4 +61,4 @@ declare module SocialSharingPlugin {
saveToPhotoAlbum(fileOrFileArray: string | string[], successCallback?: (succeeded: boolean) => void, errorCallback?: (errormsg: string) => void): void;
}
}
}
+14 -2
View File
@@ -29,8 +29,20 @@ declare namespace cucumber {
}
interface HookScenario{
attach(text: string, mimeType?: string, callback?: (err?:any) => void): void;
isFailed() : boolean;
getKeyword():string;
getName():string;
getDescription():string;
getUri():string;
getLine():number;
getTags():string[];
getException():Error;
getAttachments():any[];
attach(data:any, mimeType?:string, callback?:(err?:any) => void):void;
isSuccessful():boolean;
isFailed():boolean;
isPending():boolean;
isUndefined():boolean;
isSkipped():boolean;
}
interface HookCode {
Vendored
+21 -9
View File
@@ -292,17 +292,17 @@ declare namespace d3 {
*/
datum(): Datum;
/**
* Set the data item for each node in the selection.
* @param value the constant element to use for each node
*/
datum<NewDatum>(value: NewDatum): Update<NewDatum>;
/**
* Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute.
* @param value the function to compute data for each node
*/
datum<NewDatum>(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update<NewDatum>;
/**
* Set the data item for each node in the selection.
* @param value the constant element to use for each node
*/
datum<NewDatum>(value: NewDatum): Update<NewDatum>;
/**
* Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted.
@@ -1078,11 +1078,16 @@ declare namespace d3 {
* Return the min and max simultaneously.
*/
export function extent<T>(array: T[], accessor: (datum: T, index: number) => string): [string, string];
/**
* Return the min and max simultaneously.
*/
export function extent<T>(array: T[], accessor: (datum: T, index: number) => Date): [Date, Date];
/**
* Return the min and max simultaneously.
*/
export function extent<T, U extends Numeric>(array: U[], accessor: (datum: T, index: number) => U): [U | Primitive, U | Primitive];
export function extent<T, U extends Numeric>(array: T[], accessor: (datum: T, index: number) => U): [U | Primitive, U | Primitive];
/**
* Compute the sum of an array of numbers.
@@ -1097,6 +1102,12 @@ declare namespace d3 {
export function mean(array: number[]): number;
export function mean<T>(array: T[], accessor: (datum: T, index: number) => number): number;
/**
* Compute the median of an array of numbers (the 0.5-quantile).
*/
export function median(array: number[]): number;
export function median<T>(datum: T[], accessor: (datum: T, index: number) => number): number;
export function quantile(array: number[], p: number): number;
export function variance(array: number[]): number;
@@ -1105,8 +1116,7 @@ declare namespace d3 {
export function deviation(array: number[]): number;
export function deviation<T>(array: T[], accessor: (datum: T, index: number) => number): number;
export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number;
export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number;
export function bisectLeft<T>(array: T[], x: T, lo?: number, hi?: number): number;
export var bisect: typeof bisectRight;
@@ -3058,6 +3068,8 @@ declare namespace d3 {
}
export interface Partition<T extends partition.Node> {
(root: T): T[];
nodes(root: T): T[];
links(nodes: T[]): partition.Link<T>[];
+1112
View File
File diff suppressed because it is too large Load Diff
+155
View File
@@ -0,0 +1,155 @@
// Type definitions for d3Kit v1.1.0
// Project: https://www.npmjs.com/package/d3kit
// Definitions by: Morgan Benton <https://github.com/morphatic/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../d3/d3.d.ts" />
declare namespace d3kit {
export interface ChartMargin {
top?: number;
right?: number;
bottom?: number;
left?: number;
}
export interface ChartOptions {
margin?: ChartMargin;
offset?: [number,number];
initialWidth?: number;
initialHeight?: number;
[name: string]: any;
}
export interface ChartMixin {
[name: string]: any;
}
export class Skeleton {
constructor(selector: string|Element, options?: ChartOptions, customEvents?: Array<string>);
// Getters
getCustomEventNames(): Array<string>;
getDispatcher(): any; // should be d3.Dispatch but this throws error for user-created events
getInnerWidth(): number;
getInnerHeight(): number;
getLayerOrganizer(): LayerOrganizer;
getRootG(): d3.Selection<any>;
getSvg(): d3.Selection<any>;
// Getter/Setters
data(): any;
data(data?: any, doNotDispatch?: boolean): Skeleton;
options(): any; // wish this could be ChartOptions
options(options: ChartOptions, doNotDispatch?: boolean): Skeleton;
margin(): ChartMargin;
margin(margin: ChartMargin, doNotDispatch?: boolean): Skeleton;
offset(): [number, number];
offset(offset: Array<number>, doNotDispatch?: boolean): Skeleton;
width(): number;
width(value: number|string, doNotDispatch?: boolean): Skeleton;
height(): number;
height(value: number|string, doNotDispatch?: boolean): Skeleton;
dimension(): [number, number];
dimension(dimension: [number|string, number|string], doNotDispatch?: boolean): Skeleton;
autoResize(mode?: string|boolean): string|boolean|void;
autoResizeDetection(method?:string): string|void;
autoResizeToAspectRatio(ratio?: number|boolean): number|boolean|void;
// Other functions
on(eventName: string, listener: (...args: Array<any>) => void): void;
hasData(): boolean;
hasNonZeroArea(): boolean;
mixin(fn: ChartMixin): void;
resizeToFitContainer(mode: string|boolean, doNotDispatch?: boolean): void;
resizeToAspectRatio(ratio: number, doNotDispatch?: boolean): void;
}
interface ChartletPropertyCallback {
(datum?: any, datum_index?: number): any;
}
export interface ChartletEventFunction {
(sel?: d3.Selection<any>, done?: string): (sel: d3.Selection<any>) => void;
}
export class Chartlet {
constructor(
enterFunction?: ChartletEventFunction,
updateFunction?: ChartletEventFunction,
exitFunction?: ChartletEventFunction,
customEventName?: Array<string>);
// Getter functions
getDispatcher(): d3.Dispatch;
getCustomEventNames(): Array<string>;
getPropertyValue(name: string, datum: any, datum_index: number): any;
// Getter/Setter functions
property(name: string): ChartletPropertyCallback;
property(name: string, value: any): Chartlet;
// Enter/Update/Exit functions
enter( sel?: d3.Selection<any>, done?: string): (sel: d3.Selection<any>) => void;
update(sel?: d3.Selection<any>, done?: string): (sel: d3.Selection<any>) => void;
exit( sel?: d3.Selection<any>, done?: string): (sel: d3.Selection<any>) => void;
// Inheritance functions
inheritPropertyFrom(parent_chartlet: Chartlet, parent_property_name: string, child_property_name?: string): void;
inheritPropertiesFrom(parent_chartlet: Chartlet, parent_property_names: Array<string>, child_property_names?: Array<string>): void;
publishEventsTo(dispatcher: d3.Dispatch): Chartlet;
// Events
on(eventName: string, handlerFunction: ChartletEventFunction): void;
}
interface LayerConfig {
name?: string,
names?: Array<string>,
sublayers?: LayerConfig
}
export class LayerOrganizer {
constructor(container: d3.Selection<any>, tag?: string);
create(config: string|Array<string>|LayerConfig|Array<LayerConfig>): d3.Selection<any>|Array<d3.Selection<any>>;
get(name: string): d3.Selection<any>;
has(name: string): boolean;
}
export namespace factory {
export function createChart(
defaultOptions: ChartOptions,
customEvents: Array<string>,
constructor: (skeleton: Skeleton) => void
): (selector: string|Element, options?: ChartOptions, customEvents?: Array<string>) => Skeleton;
}
export namespace helper {
export function debounce(fn: (...args: Array<any>) => void, wait: number, immediate: boolean): (...args: Array<any>) => void;
export function extend(target: Object, ...args: Object[]): Object;
export function deepExtend(target: Object, ...args: Object[]): Object;
export function bindMouseEventsToDispatcher(selection: d3.Selection<any>, dispatch: d3.Dispatch, prefix: string): void;
export function removeAllChildren(selection: d3.Selection<any>, noTransition: boolean): d3.Selection<any>;
export function on(element: Element, type: string, listener: (...args: Array<any>) => void): void;
export function off(element: Element, type: string, listener: (...args: Array<any>) => void): void;
export function trim(str: string, characters: string): string;
export function dasherize(str: string): string;
export function $(s: Element|string): Element;
export function $$(s: Array<Node>|NodeList): Array<Element>;
export function isArray(value: any): boolean;
export function isNumber(value: any): boolean;
export function isObject(value: any): boolean;
export function isElement(o: any): boolean;
export function isFunction(functionToCheck: any): boolean;
}
}
declare module 'd3kit' {
export = d3kit;
}
+146
View File
@@ -0,0 +1,146 @@
/// <reference path='d3pie.d.ts' />
let chart = new d3pie('test',
{
header: {
title: {
text: '',
color: '#333333',
fontSize: 18,
font: 'arial'
},
subtitle: {
color: '#666666',
fontSize: 14,
font: 'arial'
},
location: 'top-center',
titleSubtitlePadding: 8
},
footer: {
text: '',
color: '#666666',
fontSize: 14,
font: 'arial',
location: 'left'
},
size: {
canvasHeight: 500,
canvasWidth: 500,
pieInnerRadius: 0,
pieOuterRadius: null
},
data: {
sortOrder: 'none',
smallSegmentGrouping: {
enabled: false,
value: 1,
valueType: 'percentage',
label: 'Other',
color: '#cccccc'
},
content: []
},
labels: {
outer: {
format: 'label',
hideWhenLessThanPercentage: null,
pieDistance: 30
},
inner: {
format: 'percentage',
hideWhenLessThanPercentage: null
},
mainLabel: {
color: '#333333',
font: 'arial',
fontSize: 10
},
percentage: {
color: '#dddddd',
font: 'arial',
fontSize: 10,
decimalPlaces: 0
},
value: {
color: '#cccc44',
font: 'arial',
fontSize: 10
},
lines: {
enabled: true,
style: 'curved',
color: 'segment' // 'segment' or a hex color
}
},
effects: {
load: {
effect: 'default', // none / default
speed: 1000
},
pullOutSegmentOnClick: {
effect: 'bounce', // none / linear / bounce / elastic / back
speed: 300,
size: 10
},
highlightSegmentOnMouseover: true,
highlightLuminosity: -0.2
},
tooltips: {
enabled: false,
type: 'placeholder', // caption|placeholder
string: '',
placeholderParser: null,
styles: {
fadeInSpeed: 250,
backgroundColor: '#000000',
backgroundOpacity: 0.5,
color: '#efefef',
borderRadius: 2,
font: 'arial',
fontSize: 10,
padding: 4
}
},
misc: {
colors: {
background: null, // transparent
segments: [
'#2484c1', '#65a620', '#7b6888', '#a05d56', '#961a1a',
'#d8d23a', '#e98125', '#d0743c', '#635222', '#6ada6a',
'#0c6197', '#7d9058', '#207f33', '#44b9b0', '#bca44a',
'#e4a14b', '#a3acb2', '#8cc3e9', '#69a6f9', '#5b388f',
'#546e91', '#8bde95', '#d2ab58', '#273c71', '#98bf6e',
'#4daa4b', '#98abc5', '#cc1010', '#31383b', '#006391',
'#c2643f', '#b0a474', '#a5a39c', '#a9c2bc', '#22af8c',
'#7fcecf', '#987ac6', '#3d3b87', '#b77b1c', '#c9c2b6',
'#807ece', '#8db27c', '#be66a2', '#9ed3c6', '#00644b',
'#005064', '#77979f', '#77e079', '#9c73ab', '#1f79a7'
],
segmentStroke: '#ffffff'
},
gradient: {
enabled: false,
percentage: 95,
color: '#000000'
},
canvasPadding: {
top: 5,
right: 5,
bottom: 5,
left: 5
},
pieCenterOffset: {
x: 0,
y: 0
},
cssPrefix: null
},
callbacks: {
onload: null,
onMouseoverSegment: null,
onMouseoutSegment: null,
onClickSegment: null
}
})
+146
View File
@@ -0,0 +1,146 @@
// Type definitions for d3pie 0.1.9
// Project: https://github.com/benkeen/d3pie
// Definitions by: Petryshyn Sergii <https://github.com/mc-petry>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace d3pie {
interface ID3PieChart {
redraw(): void
openSegment(index: number): void
closeSegment(index: void): void
getOpenSegment(): any
updateProp(propKey: string, value: any): void
destroy(): void
}
interface ID3PieStyleOptions {
color?: string
fontSize?: number
font?: string
}
interface ID3PieTextOptions extends ID3PieStyleOptions {
text?: string
}
interface ID3PieLabelsOptions {
format?: 'label' | 'value' | 'percentage' | 'label-value1' | 'label-value2' | 'label-percentage1' | 'label-percentage2'
hideWhenLessThanPercentage?: number
}
interface ID3PieOptions {
header?: {
title?: ID3PieTextOptions
subtitle?: ID3PieTextOptions
location?: 'top-center' | 'top-left' | 'pie-center'
titleSubtitlePadding?: number
}
footer?: { location?: 'left' } & ID3PieTextOptions
size?: {
canvasHeight?: number
canvasWidth?: number
pieOuterRadius?: string | number
pieInnerRadius?: string | number
}
data: {
sortOrder?: 'none' | 'random' | 'value-asc' | 'value-desc' | 'label-asc' | 'label-desc'
smallSegmentGrouping?: {
enabled?: boolean
value?: number
valueType?: 'percentage' | 'value'
label?: string
color?: string
}
content: {
label: string
value: number
color?: string
}[]
}
labels?: {
outer?: { pieDistance?: number } & ID3PieLabelsOptions
inner?: ID3PieLabelsOptions
mainLabel?: ID3PieStyleOptions
percentage?: { decimalPlaces?: number } & ID3PieStyleOptions
value?: ID3PieStyleOptions
lines?: {
enabled?: boolean
style?: 'curved' | 'straight'
color?: string
}
truncation?: {
enabled?: boolean
truncateLength?: number
}
formatter?: (context: {
section: 'outer' | 'inner'
value: number
label: string
}) => string
}
effects?: {
load?: {
effect?: 'none' | 'default'
speed?: number
}
pullOutSegmentOnClick?: {
effect?: 'none' | 'linear' | 'bounce' | 'elastic' | 'back'
speed?: number
size?: number
}
highlightSegmentOnMouseover?: boolean
highlightLuminosity?: number
}
tooltips?: {
enabled?: boolean
type?: 'placeholder' | 'caption'
string?: string
placeholderParser?: (index: number, data: { label?: string, percentage?: number, value?: number }) => void
styles?: {
fadeInSpeed?: number
backgroundColor?: string
backgroundOpacity?: number
color?: string
borderRadius?: number
font?: string
fontSize?: number
padding?: number
}
}
misc?: {
colors?: {
background?: string
segments?: string[]
segmentStroke?: string
}
gradient?: {
enabled?: boolean
percentage?: number
color?: string
}
canvasPadding?: {
top?: number
right?: number
bottom?: number
left?: number
}
pieCenterOffset?: {
x?: number
y?: number
}
cssPrefix?: string
}
callbacks?: {
onload?: Function
onMouseoverSegment?: Function
onMouseoutSegment?: Function
onClickSegment?: Function
}
}
interface ID3PieClass {
new (id: string | HTMLElement, options: ID3PieOptions): ID3PieChart
}
}
declare const d3pie: d3pie.ID3PieClass
+3
View File
@@ -11,6 +11,9 @@ namespace DagreD3Tests {
predecessors["a"] = graph.predecessors("a");
successors["a"] = graph.successors("a");
graph.transition = (selection: d3.Selection<any>) => {
return d3.transition();
};
const render = new dagreD3.render();
const svg = d3.select("svg");
+2
View File
@@ -19,6 +19,8 @@ declare namespace Dagre {
height: number;
predecessors(id: string): string[];
successors(id: string): string[];
// see source of http://cpettitt.github.io/project/dagre-d3/latest/demo/interactive-demo.html
transition?(selection: d3.Selection<any>): d3.Transition<any>;
width: number;
}
@@ -1,4 +1,4 @@
/// <reference path="DataStream.js.d.ts" />
/// <reference path="datastream.js.d.ts" />
var buf = new ArrayBuffer(100);
var ds = new DataStream(buf);
+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/DefinitelyTyped/DefinitelyTyped
declare namespace 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;
}
+15
View File
@@ -0,0 +1,15 @@
DevExpress ASP.NET/MVC TypeScript definitions
=============================================
You can use these TypeScript definitions for your web projects, which contain
DevExpress ASP.NET or MVC controls. For this, simply add at the top of your
code `<reference path="TypeScript/devexpress-web.d.ts" />`.
The API enclosed into the DevExpress ASP.NET/MVC TypeScript definition file
fully corresponds to the API described in the DevExpress ASP.NET/MVC
Documentation:
[Reference](https://documentation.devexpress.com/#AspNet/DevExpressWebScripts).
If you have any issues while using the DevExpress ASP.NET/MVC TypeScript
definitions, please refer to our [Support
Center](https://www.devexpress.com/Support/Center/Question/List/1).
+414 -59
View File
@@ -1,75 +1,430 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="devexpress-web.d.ts" />
namespace Tests.Globals {
function ASPxTest(): void {
ASPx.RunStartupScripts();
}
declare var hiddenField: ASPxClientHiddenField;
declare var mainCallbackPanel: ASPxClientCallbackPanel;
declare var loginPopup: ASPxClientPopupControl;
declare var searchButton: ASPxClientButton;
declare var searchComboBox: ASPxClientComboBox;
declare var roomsNumberSpinEdit: ASPxClientSpinEdit;
declare var adultsNumberSpinEdit: ASPxClientSpinEdit;
declare var childrenNumberSpinEdit: ASPxClientSpinEdit;
declare var checkInDateEdit: ASPxClientDateEdit;
declare var checkOutDateEdit: ASPxClientDateEdit;
declare var backSlider: ASPxClientImageSlider;
declare var locationComboBox: ASPxClientComboBox;
declare var nightyRateTrackBar: ASPxClientTrackBar;
declare var customerRatingTrackBar: ASPxClientTrackBar;
declare var ourRatingCheckBoxList: ASPxClientCheckBoxList;
declare var startFilterPopupControl: ASPxClientPopupControl;
declare var imagePopupControl: ASPxClientPopupControl;
declare var emailTextBox: ASPxClientTextBox;
declare var creditCardEmailTextBox: ASPxClientTextBox;
declare var accountEmailTextBox: ASPxClientTextBox;
declare var bookingPageControl: ASPxClientPageControl;
declare var paymentTypePageControl: ASPxClientPageControl;
declare var offerFormPopup: ASPxClientPopupControl;
declare var roomsSpinEdit: ASPxClientSpinEdit;
declare var adultsSpinEdit: ASPxClientSpinEdit;
declare var childrenSpinEdit: ASPxClientSpinEdit;
declare var hotelDetailsCallbackPanel: ASPxClientCallbackPanel;
declare var leftPanel: ASPxClientPanel;
declare var menuButton: ASPxClientButton;
declare var aboutWindow: ASPxClientPopupControl;
declare var offersZone: ASPxClientDockZone;
function ASPxClientControlTest(): void {
ASPxClientControl.AdjustControls();
let controls: DevExpress.Web.Scripts.ASPxClientControlCollection = ASPxClientControl.GetControlCollection();
controls.GetByName("myControl");
module DXDemo {
function showPage(page: string, params: { [key: string]: any }, skipHistory?: boolean): void {
var queryString = getQueryString(params || {});
hiddenField.Set("page", page);
hiddenField.Set("parameters", queryString);
hideMenu();
var uri = queryString.length ? (page + "?" + queryString) : page;
try {
if (!skipHistory && window.history && window.history.pushState)
window.history.pushState(uri, "", uri || "Default.aspx");
} catch (e) { }
mainCallbackPanel.PerformCallback(uri);
};
let elements: DevExpress.Web.Scripts.ASPxClientControl[] = controls.elements;
for (let element of elements) {
let name: string = element.name;
element.AdjustControl();
let mainElement = element.GetMainElement();
if (mainElement) {
mainElement.focus();
}
let isVisible: boolean = element.GetVisible();
let inCallback: boolean = element.InCallback();
element.SetWidth(600);
element.SetHeight(400);
let initEventHandler: (s: DevExpress.Web.Scripts.ASPxClientControl, e: DevExpress.Web.Scripts.ASPxClientEventArgs) => void = (s: DevExpress.Web.Scripts.ASPxClientControl, e: DevExpress.Web.Scripts.ASPxClientEventArgs) => { };
element.Init.AddHandler(initEventHandler);
element.Init.RemoveHandler(initEventHandler);
element.Init.ClearHandlers();
export function onMainMenuItemClick(s: ASPxClientMenu, e: ASPxClientMenuItemClickEventArgs): void {
switch (e.item.name) {
case "login":
hideMenu();
setTimeout(function () { loginPopup.ShowAtElementByID("MainCallbackPanel_ContentPane"); }, 300);
break;
case "offers":
showPage("SpecialOffers", {});
break;
default:
hideMenu();
setTimeout(function () { showAboutWindow(); }, 300);
break;
}
}
};
function ASPxClientUtilsTest(): void {
ASPxClientUtils.AttachEventToElement(document.getElementById("btnSubmit"), "click", () => { });
export function onLoginButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void {
loginPopup.Hide();
showAboutWindow();
};
let htmlEvent: Event;
let x: number = ASPxClientUtils.GetEventX(htmlEvent);
let y: number = ASPxClientUtils.GetEventY(htmlEvent);
export function onSearchButtonClick(): void {
if (ASPxClientEdit.ValidateGroup("DateEditors")) {
showPage("ShowHotels", {
location: searchComboBox.GetValue(),
checkin: getFormattedDate(<Date>checkInDateEdit.GetValue()),
checkout: getFormattedDate(<Date>checkOutDateEdit.GetValue()),
rooms: roomsNumberSpinEdit.GetValue() || 1,
adults: adultsNumberSpinEdit.GetValue() || 1,
children: childrenNumberSpinEdit.GetValue() || 0
});
}
};
let control: DevExpress.Web.Scripts.ASPxClientControl;
let controlExists: boolean = ASPxClientUtils.IsExists(control);
}
export function onSearchComboBoxIndexChanged(s: ASPxClientComboBox, e: ASPxClientProcessingModeEventArgs): void {
hideMenu();
$("#IndexContent").addClass("search-extend");
searchButton.AdjustControl();
};
function MVCxClientGlobalEventsTest(): void {
ASPxClientGlobalEvents.AddControlsInitializedEventHandler((s: any, e: DevExpress.Web.Scripts.ASPxClientControlsInitializedEventArgs) => {});
}
export function onIndexOfferCloseClick(index: number): void {
var panel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("OfferDockPanel" + index);
var sibPanel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("OfferDockPanel" + (index == 1 ? 2 : 1));
panel.Hide();
sibPanel.MakeFloat();
sibPanel.SetWidth(offersZone.GetWidth());
sibPanel.Dock(offersZone);
};
function ASPxClientEditTest(): void {
let editorsValid: boolean = ASPxClientEdit.AreEditorsValid();
export function onLogoClick(): void {
showPage("", null, false);
};
let container: HTMLElement = document.getElementById("form1");
let editorsInContainerGroupValid: boolean = ASPxClientEdit.AreEditorsValid(container, "group1", false);
export function onMenuNavButtonCheckedChanged(s: ASPxClientCheckBox, e: ASPxClientProcessingModeEventArgs): void {
var mainContainer = mainCallbackPanel.GetMainElement();
if (s.GetChecked()) {
backSlider.Pause();
showMenu();
}
else {
hideMenu();
backSlider.Play();
}
};
ASPxClientEdit.ClearEditorsInContainer(container, "group1", false);
ASPxClientEdit.ClearGroup("group1", false);
export function onBackNavButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void {
var params = getCurrentQueryParams();
switch (getCurrentPage()) {
case "PrintInvoice":
showPage("Booking", params, false);
break;
case "Booking":
if (bookingPageControl.GetActiveTabIndex() > 0)
bookingPageControl.SetActiveTabIndex(bookingPageControl.GetActiveTabIndex() - 1);
else
showPage("ShowRooms", params, false);
break;
case "ShowRooms":
showPage("ShowHotels", params, false);
break;
case "ShowDetails":
showPage("ShowHotels", params, false);
break;
case "ShowHotels":
case "SpecialOffers":
showPage("", null, false);
break;
}
};
let editorsInContainerValid: boolean = ASPxClientEdit.ValidateEditorsInContainer(container, "group1", false);
let editorsInGroupValid: boolean =ASPxClientEdit.ValidateGroup("group1", false);
}
}
export function updateSearchResults(): void {
var params = getCurrentQueryParams();
params["location"] = locationComboBox.GetValue();
params["minprice"] = nightyRateTrackBar.GetPositionStart();
params["maxprice"] = nightyRateTrackBar.GetPositionEnd();
params["custrating"] = customerRatingTrackBar.GetPosition();
params["ourrating"] = ourRatingCheckBoxList.GetSelectedValues().join(",");
showPage("ShowHotels", params);
};
namespace Tests.Controls {
declare var comboBox: DevExpress.Web.Scripts.ASPxClientComboBox;
export function onBookHotelButtonClick(hotelID: string): void {
var queryParams = getCurrentQueryParams();
queryParams["hotelID"] = hotelID;
showPage("ShowRooms", queryParams);
};
function ASPxClientComboBoxTest() {
let selectedIndex: number = comboBox.GetSelectedIndex();
comboBox.SetSelectedIndex(1);
export function onDetailsHotelButtonClick(hotelID: string): void {
var queryParams = getCurrentQueryParams();
queryParams["hotelID"] = hotelID;
showPage("ShowDetails", queryParams);
};
let selectedIndexChangedEventHandler: (s: DevExpress.Web.Scripts.ASPxClientControl, e: DevExpress.Web.Scripts.ASPxClientEventArgs) => void = (s: DevExpress.Web.Scripts.ASPxClientControl, e: DevExpress.Web.Scripts.ASPxClientEventArgs) => { };
comboBox.SelectedIndexChanged.AddHandler(selectedIndexChangedEventHandler);
comboBox.SelectedIndexChanged.RemoveHandler(selectedIndexChangedEventHandler);
comboBox.SelectedIndexChanged.ClearHandlers();
}
}
export function onShowStartFilterButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void {
startFilterPopupControl.ShowAtElementByID("MainCallbackPanel_ContentPane");
};
export function onChangeStartFilterButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void {
if (ASPxClientEdit.ValidateGroup("DateEditors")) {
var params = getCurrentQueryParams();
params["checkin"] = getFormattedDate(<Date>checkInDateEdit.GetValue());
params["checkout"] = getFormattedDate(<Date>checkOutDateEdit.GetValue());
params["rooms"] = roomsNumberSpinEdit.GetValue() || 1;
params["adults"] = adultsNumberSpinEdit.GetValue() || 1;
params["children"] = childrenNumberSpinEdit.GetValue() || 0;
startFilterPopupControl.Hide();
showPage(hiddenField.Get("page").toString(), params);
}
};
export function onBookRoomButtonClick(roomID: string): void {
var params = getCurrentQueryParams();
params["roomID"] = roomID;
showPage("Booking", params);
};
export function onShowRoomsButtonClick(): void {
var queryParams = getCurrentQueryParams();
showPage("ShowRooms", queryParams);
};
export function onShowDetailsButtonClick(): void {
var queryParams = getCurrentQueryParams();
showPage("ShowDetails", queryParams);
};
export function onRoomImageNavItemClick(roomID: string, pictureName: string): void {
setTimeout(function () {
imagePopupControl.PerformCallback(roomID + "|" + pictureName);
imagePopupControl.ShowAtElementByID("MainCallbackPanel_ContentPane");
}, 500);
};
export function onRoomsNavBarExpandedChanged(s: ASPxClientNavBar, e: ASPxClientNavBarGroupEventArgs): void {
ASPxClientControl.AdjustControls(s.GetMainElement());
};
export function onNextBookingStepButtonClick(step: number): void {
var valid = true;
var validationGroup = "";
if (step == 1)
validationGroup = "Account";
if (step == 2)
validationGroup = "RoomDetails";
if (step == 3)
validationGroup = "PaymentDetails";
switch (step) {
case 1:
valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "Account");
if (valid) {
emailTextBox.SetValue(accountEmailTextBox.GetValue());
creditCardEmailTextBox.SetValue(accountEmailTextBox.GetValue());
showPage("Booking", getCurrentQueryParams());
return;
}
break;
case 2:
valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "RoomDetails");
emailTextBox.SetValue(accountEmailTextBox.GetValue());
break;
case 3:
var paymentType = paymentTypePageControl.GetActiveTabIndex();
if (paymentType == 0)
valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "CreditCard");
else if (paymentType == 1)
valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "Cash");
else if (paymentType == 2)
valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "PayPal");
break;
}
if (valid) {
bookingPageControl.GetTab(step).SetEnabled(true);
bookingPageControl.SetActiveTabIndex(step);
}
};
export function onAccountCaptchaHiddenFieldInit(s: ASPxClientHiddenField, e: ASPxClientEventArgs): void {
if (s.Get("IsCaptchaValid")) {
bookingPageControl.GetTab(1).SetEnabled(true);
bookingPageControl.SetActiveTabIndex(1);
}
};
export function onFinishBookingStepButtonClick(): void {
showAboutWindow();
};
export function OnPrintInvoiceButtonClick(): void {
showPage("PrintInvoice", getCurrentQueryParams());
};
export function onOfferClick(offerID: string): void {
offerFormPopup.SetContentHtml("");
offerFormPopup.PerformCallback(offerID);
var panel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("DockPanel" + offerID);
var panelElement = <HTMLElement>panel.GetMainElement();
if (panelElement.offsetWidth < 330 || panelElement.offsetHeight < 250) {
offerFormPopup.SetWidth(400);
offerFormPopup.SetHeight(280);
offerFormPopup.ShowAtElementByID("SpecialOffersContainer");
}
else {
offerFormPopup.SetWidth(panelElement.offsetWidth);
offerFormPopup.SetHeight(panelElement.offsetHeight);
offerFormPopup.ShowAtElement(panelElement);
}
};
export function onSpecialOfferCheckButtonClick(hotelID: string, locationID: string): void {
if (ASPxClientEdit.ValidateGroup("DateEditors")) {
var queryParams: { [key: string]: any } = {
location: locationID,
hotelID: hotelID,
checkin: getFormattedDate(<Date>checkInDateEdit.GetValue()),
checkout: getFormattedDate(<Date>checkOutDateEdit.GetValue()),
rooms: roomsSpinEdit.GetValue() || 1,
adults: adultsSpinEdit.GetValue() || 1,
children: childrenSpinEdit.GetValue() || 0
};
showPage("ShowRooms", queryParams);
}
};
export function onIndexOfferClick(): void {
showPage("SpecialOffers", {});
};
export function onControlsInit(): void {
ASPxClientUtils.AttachEventToElement(window, 'popstate', onHistoryPopState);
var pathParts = document.location.href.split("/");
var url = pathParts[pathParts.length - 1];
try {
if (window.history)
window.history.replaceState(url, "");
} catch (e) { }
ASPxClientUtils.AttachEventToElement(window, "resize", onWindowResize);
if (ASPxClientUtils.iOSPlatform) {
$("form :input").blur(function () {
$('html, body').animate({ scrollTop: 0 }, 0);
});
}
};
export function updateRatingLabels(ratingControl: ASPxClientTrackBar) {
$("#cpLeftLabelID").html(ratingControl.GetPositionStart().toString());
$("#cpRightLabelID").html(ratingControl.GetPositionEnd().toString());
};
export function onAboutWindowCloseUp(): void {
$(mainCallbackPanel.GetMainElement()).removeClass("show-about");
};
export function onRatingControlItemClick(s: ASPxClientRatingControl, e: ASPxClientRatingControlItemClickEventArgs): void {
hotelDetailsCallbackPanel.PerformCallback(s.GetValue().toString());
};
export function onInputKeyDown(s: ASPxClientTextBox, e: ASPxClientEditKeyEventArgs): void {
var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent);
if (keyCode == 13) {
(<any>jQuery).event.fix(e.htmlEvent).preventDefault();
(<HTMLElement>s.GetInputElement()).blur();
}
};
function getCurrentPage(): string {
var hfPage = <string>hiddenField.Get("page");
if (hfPage)
return hfPage;
var pathParts = document.location.pathname.split("/");
return pathParts[pathParts.length - 1];
};
function showAboutWindow(): void {
$(mainCallbackPanel.GetMainElement()).addClass("show-about");
aboutWindow.ShowAtElementByID("MainCallbackPanel_ContentPane");
};
function hideMenu(): void {
leftPanel.Collapse();
if (menuButton.GetMainElement() && menuButton.GetChecked())
menuButton.SetChecked(false);
};
function showMenu(): void {
leftPanel.Expand();
};
var _resizeSpecialOffersTimeoutID = -1;
function onWindowResize(): void {
switch (<string>hiddenField.Get("page")) {
case "SpecialOffers":
if (_resizeSpecialOffersTimeoutID == -1)
_resizeSpecialOffersTimeoutID = setTimeout(resizeSpecialOffers, 200);
break;
}
hidePopups("AboutWindow", "StartFilterPopupControl", "LoginPopup", "OfferFormPopup", "ImagePopupControl");
};
function hidePopups(...names: string[]): void {
for (var i = 0; i < names.length; i++) {
var popupControl = <ASPxClientPopupControl>ASPxClientControl.GetControlCollection().GetByName(names[i]);
popupControl.Hide();
}
};
function resizeSpecialOffers(): void {
for (var i = 1; i <= 4; i++) {
var panel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("DockPanel" + i);
if (panel && panel.IsVisible()) {
var zone = panel.GetOwnerZone();
zone.SetWidth((<HTMLElement>(<HTMLElement>zone.GetMainElement()).parentNode).offsetWidth)
}
}
_resizeSpecialOffersTimeoutID = -1;
};
function getFormattedDate(date: Date): string {
return (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear();
};
function getCurrentQueryParams(): { [key:string]: any } {
var hfParams = <string>hiddenField.Get("parameters");
if (hfParams)
return getParamsByQueryString(hfParams);
var query = document.location.search;
if (query[0] === "?")
query = query.substr(1);
return getParamsByQueryString(query);
};
function getQueryString(params: { [key:string]: any }): string {
var queryItems: any[] = [];
for (var key in params) {
if (!params.hasOwnProperty(key)) continue;
queryItems.push(key + "=" + params[key]);
}
if (queryItems.length > 0)
return queryItems.join("&");
return "";
};
function getParamsByQueryString(queryString: string): { [key: string]: string } {
var result: { [key: string]: any } = {};
if (queryString) {
var queryStringArray = queryString.split("&");
for (var i = 0; i < queryStringArray.length; i++) {
var part = queryStringArray[i].split('=');
if (part.length != 2) continue;
result[part[0]] = decodeURIComponent(part[1].replace(/\+/g, " "));
}
}
return result;
};
function onHistoryPopState(evt: any): void {
if (evt.state !== null && evt.state !== undefined) {
var uriParts = evt.state.split("?");
showPage(uriParts[0], getParamsByQueryString(uriParts[1]), true);
}
};
}
+26968 -550
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -39,6 +39,10 @@ declare class Dexie {
static shallowClone(obj: Object): Object;
static deepClone(obj: Object): Object;
static delete(databaseName : string): Dexie.Promise<void>;
static exists(databaseName : string): Dexie.Promise<boolean>;
version(versionNumber: Number): Dexie.Version
+5 -1
View File
@@ -30,4 +30,8 @@ gantt.load("/data/events");
//events
gantt.attachEvent("onBeforeLightbox", function (id?: string) {
gantt.showTask(id);
});
});
//gantt enterprise
var gantt2 = Gantt.getGanttInstance();
gantt2.config.api_date = "format";

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