Merge pull request #1 from DefinitelyTyped/master

merge from upstream
This commit is contained in:
Dmitry A. Efimenko
2016-08-14 18:31:22 -07:00
committed by GitHub
1160 changed files with 350604 additions and 31604 deletions
+52
View File
@@ -0,0 +1,52 @@
/// <reference path="3d-bin-packing.d.ts" />
import packer = require("3d-bin-packing");
import samchon = require("samchon-framework");
function main(): void
{
///////////////////////////
// CONSTRUCT OBJECTS
///////////////////////////
let wrapperArray: bws.packer.WrapperArray = new packer.WrapperArray();
let instanceArray: bws.packer.InstanceArray = new packer.InstanceArray();
// Wrappers
wrapperArray.push
(
new packer.Wrapper("Large", 1000, 40, 40, 15, 0),
new packer.Wrapper("Medium", 700, 20, 20, 10, 0),
new packer.Wrapper("Small", 500, 15, 15, 8, 0)
);
///////
// Each Instance is repeated #15
///////
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Eraser", 1, 2, 5));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Book", 15, 30, 3));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Drink", 3, 3, 10));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Umbrella", 5, 5, 20));
// Wrappers also can be packed into another Wrapper.
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Notebook-Box", 2000, 30, 40, 4, 2));
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Tablet-Box", 2500, 20, 28, 2, 0));
///////////////////////////
// BEGINS PACKING
///////////////////////////
// CONSTRUCT PACKER
let my_packer: bws.packer.Packer = new packer.Packer(wrapperArray, instanceArray);
///////
// PACK (OPTIMIZE)
let result: bws.packer.WrapperArray = my_packer.optimize();
///////
///////////////////////////
// TRACE PACKING RESULT
///////////////////////////
let xml: samchon.library.XML = result.toXML();
console.log(xml.toString());
}
main();
+1500
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -695,7 +695,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](heap/heap.d.ts) [heap](https://github.com/qiao/heap.js) by [Ryan McNamara](https://github.com/ryan10132)
* [:link:](heatmap.js/heatmap.d.ts) [heatmap.js](https://github.com/pa7/heatmap.js) by [Yang Guan](https://github.com/lookuptable)
* [:link:](hellojs/hellojs.d.ts) [hello.js](http://adodson.com/hello.js) by [Pavel Zika](https://github.com/PavelPZ)
* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher)
* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher), [Evan Hahn](https://github.com/EvanHahn)
* [:link:](highcharts/highcharts.d.ts) [Highcharts](http://www.highcharts.com) by [Damiano Gambarotto](http://github.com/damianog), [Dan Lewi Harkestad](http://github.com/baltie)
* [:link:](highcharts-ng/highcharts-ng.d.ts) [highcharts-ng](https://github.com/pablojim/highcharts-ng) by [Scott Hatcher](https://github.com/scatcher)
* [:link:](highland/highland.d.ts) [Highland](http://highlandjs.org) by [Bart van der Schoor](https://github.com/Bartvds)
@@ -1123,10 +1123,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](moment/moment.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware)
* [:link:](moment-range/moment-range.d.ts) [Moment.js](https://github.com/gf3/moment-range) by [Bart van den Burg](https://github.com/Burgov), [Wilgert Velinga](https://github.com/wilgert)
* [:link:](mongodb/mongodb.d.ts) [MongoDB](https://github.com/mongodb/node-mongodb-native/tree/2.1) by [Federico Caselli](https://github.com/CaselIT)
* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [horiuchi](https://github.com/horiuchi)
* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [simonxca](https://github.com/simonxca), [horiuchi](https://github.com/horiuchi)
* [:link:](mongoose-auto-increment/mongoose-auto-increment.d.ts) [mongoose-auto-increment](https://github.com/codetunnel/mongoose-auto-increment) by [Aya Morisawa](https://github.com/AyaMorisawa)
* [:link:](mongoose-deep-populate/mongoose-deep-populate.d.ts) [mongoose-deep-populate](https://github.com/buunguyen/mongoose-deep-populate) by [Aya Morisawa](https://github.com/AyaMorisawa)
* [:link:](mongoose-mock/mongoose-mock.d.ts) [mongoose-mock](https://github.com/JohanObrink/mongoose-mock) by [jt000](https://github.com/jt000)
* [:link:](mongoose-promise/mongoose-promise.d.ts) [mongoose-promise](http://mongoosejs.com/docs/api.html#promise-js) by [simonxca](https://github.com/simonxca)
* [:link:](morgan/morgan.d.ts) [morgan](https://github.com/expressjs/morgan) by [James Roland Cabresos](https://github.com/staticfunction)
* [:link:](mousetrap/mousetrap-global-bind.d.ts) [Mousetrap 1.4.6's global-bind extension](http://craig.is/killing/mice#extensions.global) by [Andrew Bradley](https://github.com/cspotcode)
* [:link:](mousetrap/mousetrap.d.ts) [Mousetrap 1.5.x](http://craig.is/killing/mice) by [Dániel Tar](https://github.com/qcz)
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="CybozuLabs-md5.d.ts" />
var hash: string;
hash = CybozuLabs.MD5.calc("abc");
hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII);
hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_UTF16);
var version: string;
version = CybozuLabs.MD5.VERSION;
+11
View File
@@ -0,0 +1,11 @@
// Type definitions for CybozuLabs.MD5
// Project: http://labs.cybozu.co.jp/blog/mitsunari/2007/07/md5js_1.html
// Definitions by: MIZUNE Pine <https://github.com/pine613>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace CybozuLabs.MD5 {
var VERSION: string;
var BY_ASCII: number;
var BY_UTF16: number;
function calc(str: string, option?: number): string;
}
+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");
+11 -1
View File
@@ -12,4 +12,14 @@ var config : adal.Config = {
var auth = new AuthenticationContext(config);
var userName: string = auth.getCachedUser().userName;
Logging.log = (message: string) => {
console.log(message);
}
Logging.level = 4;
auth.info("Logging message");
var userName: string = auth.getCachedUser().userName;
var postLogoutRedirectUrl = auth.config.postLogoutRedirectUri;
var isValidRequest = auth.getRequestInfo('hash').valid;
+43 -20
View File
@@ -4,37 +4,51 @@
// 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 {
interface Config {
tenant?: string,
clientId: string,
redirectUri?: string,
cacheLocation?: string,
displayCall?: (urlNavigate: string) => any,
correlationId?: string,
loginResource?: string,
resource?: string
endpoints?: any // If you need to send CORS api requests.
extraQueryParameter?: string
tenant?: string;
clientId: string;
redirectUri?: string;
cacheLocation?: string;
displayCall?: (urlNavigate: string) => any;
correlationId?: string;
loginResource?: string;
resource?: string;
endpoints?: any; // If you need to send CORS api requests.
extraQueryParameter?: string;
postLogoutRedirectUri?: string; // redirect url after succesful logout operation
}
interface User {
userName: string,
profile: any
userName: string;
profile: any;
}
interface RequestInfo {
valid: boolean,
parameters: any,
stateMatch: boolean,
stateResponse: string,
requestType: string
valid: boolean;
parameters: any;
stateMatch: boolean;
stateResponse: string;
requestType: string;
}
interface Logging {
log: (message: string) => void;
level: LoggingLevel;
}
enum LoggingLevel {
ERROR = 0,
WARNING = 1,
INFO = 2,
VERBOSE = 3
}
interface AuthenticationContextStatic {
@@ -51,6 +65,10 @@ declare namespace adal {
* Saves the resulting Idtoken in localStorage.
*/
login(): void;
/**
* Indicates whether login is in progress now or not.
*/
loginInProgress(): boolean;
/**
@@ -118,9 +136,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.
@@ -134,6 +152,11 @@ declare namespace adal {
*/
getResourceForEndpoint(endpoint: string): string;
/**
* Handles redirection after login operation.
* Gets access token from url and saves token to the (local/session) storage
* or saves error in case unsuccessful login.
*/
handleWindowCallback(): void;
log(level: number, message: string, error: any): void;
+74
View File
@@ -0,0 +1,74 @@
/// <reference path="ajv.d.ts" />
import * as Ajv from 'ajv';
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile({});
var valid = validate({});
if (!valid) console.log(validate.errors);
var valid = ajv.validate({}, {});
if (!valid) console.log(ajv.errors);
ajv.addSchema({}, 'mySchema');
var valid = ajv.validate('mySchema', {});
if (!valid) console.log(ajv.errorsText());
ajv.addKeyword('range', {
type: 'number', compile: function (sch, parentSchema) {
var min: any = sch[0];
var max: any = sch[1];
return parentSchema.exclusiveRange === true
? function (data) { return data > min && data < max; }
: function (data) { return data >= min && data <= max; }
}
});
var schema = { "range": [2, 4], "exclusiveRange": true };
var validate = ajv.compile(schema);
console.log(validate(2.01)); // true
console.log(validate(3.99)); // true
console.log(validate(2)); // false
console.log(validate(4)); // false
declare var request: any;
function loadSchema(uri: any, callback: any) {
request.json(uri, function (err: any, res: any, body: any) {
if (err || res.statusCode >= 400)
callback(err || new Error('Loading error: ' + res.statusCode));
else
callback(null, body);
});
}
var ajv = new Ajv({ loadSchema: loadSchema });
ajv.compileAsync(schema, function (err, validate) {
if (err) return;
var valid = validate({});
});
declare var knex: any;
function checkIdExists(schema: any, data: any) {
return knex(schema.table)
.select('id')
.where('id', data)
.then(function (rows: any) {
return true;
});
}
var validate = ajv.compile(schema);
(validate({ userId: 1, postId: 19 }) as PromiseLike<boolean>)
.then(function (valid) {
// "valid" is always true here
console.log('Data is valid');
}, function (err) {
if (!(err instanceof Ajv.ValidationError)) throw err;
// data is invalid
console.log('Validation errors:', err.errors);
});
var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' });
var validate = ajv.compile(schema); // transpiled es7 async function
(validate({}) as PromiseLike<any>).then(() => { }, () => { });
+112
View File
@@ -0,0 +1,112 @@
// Type definitions for ajv
// Project: https://github.com/epoberezkin/ajv
// Definitions by: York Yao <https://github.com/plantain-00/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "ajv" {
class Ajv {
/**
* Create Ajv instance.
*/
constructor(options?: Ajv.AjvOptions);
/**
* Generate validating function and cache the compiled schema for future use.
*/
compile(schema: any): Ajv.AjvValidate;
/**
* Asyncronous version of compile method that loads missing remote schemas using asynchronous function in options.loadSchema.
*/
compileAsync(schema: any, callback: (error: Error, validate: Ajv.AjvValidate) => void): void;
/**
* Validate data using passed schema (it will be compiled and cached).
*/
validate(schema: any, data: any): boolean | PromiseLike<boolean>;
errors: Ajv.ValidationError[];
/**
* Add schema(s) to validator instance.
*/
addSchema(schema: any, key: string): void;
/**
* Adds meta schema(s) that can be used to validate other schemas.
* That function should be used instead of addSchema because there may be instance options that would compile a meta schema incorrectly (at the moment it is removeAdditional option).
*/
addMetaSchema(schema: any, key: string): void;
/**
* Validates schema.
* This method should be used to validate schemas rather than validate due to the inconsistency of uri format in JSON-Schema standard.
*/
validateSchema(schema: any): Boolean;
/**
* Retrieve compiled schema previously added with addSchema by the key passed to addSchema or by its full reference (id).
* Returned validating function has schema property with the reference to the original schema.
*/
getSchema(key: string): Ajv.AjvValidate;
/**
* Remove added/cached schema.
* Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
*/
removeSchema(schema: any): void;
/**
* Add custom format to validate strings. It can also be used to replace pre-defined formats for Ajv instance.
*/
addFormat(name: string, format: any): void;
/**
* Add custom validation keyword to Ajv instance.
*/
addKeyword(keyword: string, definition: Ajv.AjxKeywordDefinition): void;
errorsText(): any;
static ValidationError: Function;
}
namespace Ajv {
type AjvOptions = {
v5?: boolean;
allErrors?: boolean;
verbose?: boolean;
jsonPointers?: boolean;
uniqueItems?: boolean;
unicode?: boolean;
format?: string;
formats?: any;
schemas?: any;
missingRefs?: boolean;
loadSchema?(uri: string, callback: (error: Error, body: any) => void): void;
removeAdditional?: boolean;
useDefaults?: boolean;
coerceTypes?: boolean;
async?: any;
transpile?: string;
meta?: boolean;
validateSchema?: boolean;
addUsedSchema?: boolean;
inlineRefs?: boolean;
passContext?: boolean;
loopRequired?: number;
ownProperties?: boolean;
multipleOfPrecision?: boolean;
errorDataPath?: string,
messages?: boolean;
beautify?: boolean;
cache?: any;
}
type AjvValidate = ((data: any) => boolean | PromiseLike<boolean>) & {
errors: ValidationError[];
}
type AjxKeywordDefinition = {
async?: boolean;
type: string;
compile?: (schema: any, parentsSchema: any) => ((data: any) => boolean | PromiseLike<boolean>);
validate?: (schema: any, data: any) => boolean;
}
type ValidationError = {
keyword: string;
dataPath: string;
schemaPath: string;
params: any;
message: string;
schema: any;
parentSchema: any;
data: any;
}
}
export = Ajv;
}
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="../node/node.d.ts"/>
/// <reference path="./alexa-sdk.d.ts" />
import * as Alexa from "alexa-sdk";
exports.handler = function(event: Alexa.RequestBody, context: Alexa.Context, callback: Function) {
let alexa = Alexa.handler(event, context);
alexa.registerHandlers(handlers);
alexa.execute();
};
let handlers: Alexa.Handlers = {
'LaunchRequest': function () {
var self: Alexa.Handler = this;
self.emit('SayHello');
},
'HelloWorldIntent': function () {
var self: Alexa.Handler = this;
self.emit('SayHello');
},
'SayHello': function () {
var self: Alexa.Handler = this;
self.emit(':tell', 'Hello World!');
}
};
+132
View File
@@ -0,0 +1,132 @@
// Type definitions for Alexa SDK for Node.js v1.0.3
// Project: https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs
// Definitions by: Pete Beegle <https://github.com/petebeegle>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'alexa-sdk' {
export function handler(event: RequestBody, context: Context, callback?: Function): AlexaObject;
export function CreateStateHandler(state: string, obj: any): any;
export var StateString: string;
interface AlexaObject {
_event: any;
_context: any;
_callback: any;
state: any;
appId: any;
response: any;
dynamoDBTableName: any;
saveBeforeResponse: boolean;
registerHandlers: (...handlers: Handlers[]) => any;
execute: () => void;
}
interface Handlers {
[intent: string]: () => void;
}
interface Handler {
on: any;
emit(event: string, ...args: any[]): boolean;
emitWithState: any;
state: any;
handler: any;
event: RequestBody;
attributes: any;
context: any;
name: any;
isOverriden: any;
}
interface Context {
callbackWaitsForEmptyEventLoop: boolean;
logGroupName: string;
logStreamName: string;
functionName: string;
memoryLimitInMB: string;
functionVersion: string;
invokeid: string;
awsRequestId: string;
}
interface RequestBody {
version: string;
session: Session;
request: LaunchRequest | IntentRequest | SessionEndedRequest;
}
interface Session {
new: boolean;
sessionId: string;
attributes: any;
application: SessionApplication;
user: SessionUser;
}
interface SessionApplication {
applicationId: string;
}
interface SessionUser {
userId: string;
accessToken: string;
}
interface LaunchRequest extends IRequest {}
interface IntentRequest extends IRequest {
intent: Intent;
}
interface Intent {
name: string;
slots: any;
}
interface SessionEndedRequest extends IRequest{
reason: string;
}
interface IRequest {
type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest";
requestId: string;
timeStamp: string;
}
interface ResponseBody {
version: string;
sessionAttributes?: any;
response: Response;
}
interface Response {
outputSpeech?: OutputSpeech;
card?: Card;
reprompt?: Reprompt;
shouldEndSession: boolean;
}
interface OutputSpeech {
type: "PlainText" | "SSML";
text?: string;
ssml?: string;
}
interface Card {
type: "Simple" | "Standard" | "LinkAccount";
title?: string;
content?: string;
text?: string;
image?: Image;
}
interface Image {
smallImageUrl: string;
largeImageUrl: string;
}
interface Reprompt {
outputSpeech: OutputSpeech;
}
}
+2 -2
View File
@@ -53,8 +53,8 @@ declare namespace AltJS {
export type Source = {[name:string]: () => SourceModel<any>};
export interface SourceModel<S> {
local(state:any):any;
remote(state:any):Promise<S>;
local(state:any, ...args: any[]):any;
remote(state:any, ...args: any[]):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
+15 -15
View File
@@ -26,6 +26,19 @@ declare namespace AmCharts {
/** Clears all the charts on page, removes listeners and intervals. */
function clear();
/** Create chart by params. */
function makeChart(selector: string, params: any, delay?: number): AmChart;
/** Set a method to be called before initializing the chart.
* When the method is called, the chart instance is passed as an attribute.
* You can use this feature to preprocess chart data or do some other things you need
* before initializing the chart.
* @param {Function} handler - The method to be called.
* @param {string[]} types - Which chart types should call this method. Defaults to all
* if none is passed.
*/
function addInitHandler(handler: Function, types: string[]);
/** AmPieChart class creates pie/donut chart. In order to display pie chart you need to set at least three properties - dataProvider, titleField and valueField.
@example
@@ -36,7 +49,7 @@ declare namespace AmCharts {
chart.dataProvider = chartData;
chart.write("chartdiv");
*/
class AmPieChart {
class AmPieChart extends AmChart {
/** Name of the field in chart's dataProvider which holds slice's alpha. */
alphaField: string;
/** Pie lean angle (for 3D effect). Valid range is 0 - 90. */
@@ -187,19 +200,6 @@ declare namespace AmCharts {
rollOverSlice(index: number);
/** Shows slice. index - the number of a slice or Slice object. */
showSlice(index: number);
/** Adds event listener of the type "clickSlice" or "pullInSlice" or "pullOutSlice" to the object.
@param type Always "clickSlice" or "pullInSlice" or "pullOutSlice".
@param handler
If the type is "clickSlice", dispatched when user clicks on a slice.
If the type is "pullInSlice", dispatched when user clicks on a slice and the slice is pulled-in.
If the type is "pullOutSlice", dispatched when user clicks on a slice and the slice is pulled-out.
If the type is "rollOutSlice", dispatched when user rolls-out of the slice.
If the type is "rollOverSlice", dispatched when user rolls-over the slice.
*/
addListener(type: string, handler: (e: {/** Always "rollOverSlice". */
type: string; dataItem: Slice;
}) => void );
}
/** AmRadarChart is the class you have to use for radar and polar chart types.
@@ -1016,7 +1016,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
bold - specifies if text is bold (true/false),
url - url
*/
addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string);
addLabel(x: number|string, y: number|string, text: string, align: string, size?: number, color?: string, rotation?: number, alpha?: number, bold?: boolean, url?: string);
/** Adds a legend to the chart.
By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter.
(NOTE: This method will not work on StockPanel.)
@@ -0,0 +1,11 @@
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="./angular-deferred-bootstrap.d.ts" />
deferredBootstrapper.bootstrap(
{
element: window.document,
module: "myApp",
resolve: {
configuration: ["$http", ($http: ng.IHttpService) => $http.get("config.json")]
}
});
@@ -0,0 +1,20 @@
// Type definitions for angular-deferred-bootstrap v0.1.9
// Project: https://github.com/philippd/angular-deferred-bootstrap
// Definitions by: Markus Wagner <https://github.com/Ritzlgrmft/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare var deferredBootstrapper: angular.IDeferredBootstrapperStatic;
declare module angular {
interface IDeferredBootstrapperStatic {
bootstrap(configParam: IConfigParam): ng.IPromise<boolean>
}
interface IConfigParam {
element?: Node,
module?: string,
resolve: any
}
}
+5
View File
@@ -14,6 +14,11 @@ declare namespace angular.environment {
* loads the correct environment variables.
*/
check: () => void;
/**
* Retrieves the correct version of a
* variable for the current environment.
*/
read: (key: string) => any;
}
interface Service {
/**
+157
View File
@@ -0,0 +1,157 @@
/// <reference path="./angular-es.d.ts" />
//
// @Component
//
import { Component } from 'angular-es';
@Component({
selector: '',
template: ''
})
class MyComponentController {
}
//
// @Config
//
import { Config } from 'angular-es';
@Config()
class MyConfig {
}
//
// @Constant
//
import { Constant } from 'angular-es';
@Constant('MyConstant')
class MyConstant {
foo = 'foo';
bar = 'bar';
}
//
// @Controller
//
import { Controller } from 'angular-es';
@Controller('MyController')
class MyController {
}
//
// @Decorator
//
import { Decorator } from 'angular-es';
@Decorator('MyServiceDecorator')
class MyServiceDecorator {
}
//
// @Directive
//
import { Directive } from 'angular-es';
@Directive('MyDirective')
class MyDirective {
}
//
// @Factory
//
import { Factory } from 'angular-es';
@Factory('MyFactory')
class MyFactory {
}
//
// @Filter
//
import { Filter } from 'angular-es';
@Filter('MyFilter')
class MyFilter {
}
//
// @Inject
//
import { Inject } from 'angular-es';
@Inject('fooBar')
class MyFooService {
@Inject('bazBar')
myMethod(bazBar: Object) {
}
constructor(fooBar: Object) {
}
}
//
// @InjectAsProperty
//
import { InjectAsProperty } from 'angular-es';
@InjectAsProperty('fooBar')
class MyFooBarService {
fooBar: Object;
myMethod() {
this.fooBar !== undefined;
}
}
//
// @Module
//
import { Module } from 'angular-es';
@Module('my.module')
@Service('MyModuleService')
class MyModuleService {
}
//
// @Provider
//
import { Provider } from 'angular-es';
@Provider('MyProvider')
class MyProvider {
}
//
// @Run
//
import { Run } from 'angular-es';
@Run()
class MyRunBlock {
}
//
// @Service
//
import { Service } from 'angular-es';
@Service('MyService')
class MyService {
}
//
// @Value
//
import { Value } from 'angular-es';
@Value('MyValue')
class MyValue {
}
+187
View File
@@ -0,0 +1,187 @@
// Type definitions for angular-es v0.0.3
// Project: https://github.com/mbutsykin/angular-es
// Definitions by: mbutsykin <https://github.com/mbutsykin/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'angular-es' {
interface ClassDecorator {
<TFunction extends Function>(target: TFunction): TFunction|void;
}
interface MethodDecorator {
<T>(target: Object, propertyKey: string|symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T>|void;
}
/**
* Decorated target
*/
interface ngESDecorator extends ClassDecorator, MethodDecorator {
(target: Object|Function,
ngName?: string,
ngArguments?: Array<any>,
ngType?: string,
injectAsProperty?: Array<string>): void;
}
/**
* Component interface
* @see https://docs.angularjs.org/guide/component
*/
interface iComponent {
template: string,
selector: string,
controllerAs?: string,
require?: string,
templateUrl?: string,
transclude?: string,
bindings?: Object
}
/**
* Register component
*
* @param {Object<iComponent>} component - component config
*
* @returns {ngESDecorator} - decorated class
*/
var Component: (component: iComponent) => ngESDecorator;
/**
* Register config block
*/
var Config: () => ngESDecorator;
/**
* Register constant
*
* @param {string} name - constant name
*
* @returns {ngESDecorator} - decorated class
*/
var Constant: (name: string) => ngESDecorator;
/**
* Register controller
*
* @param {string} name - controller name
*
* @returns {ngESDecorator} - decorated class
*/
var Controller: (name: string) => ngESDecorator;
/**
* Register decorator
*
* @param {string} name - provider name to decorate
*
* @returns {ngESDecorator} - decorated class
*/
var Decorator: (name: string) => ngESDecorator;
/**
* Register directive
*
* @param {string} name - directive selector, can be in hyphen-case
*
* @returns {ngESDecorator} - decorated class
*/
var Directive: (name: string) => ngESDecorator;
/**
* Register factory
*
* @param {string} name - factory name
*
* @returns {ngESDecorator} - decorated class
*/
var Factory: (name: string) => ngESDecorator;
/**
* Register filter
*
* @param {string} name - filter name
*
* @returns {ngESDecorator} - decorated class
*/
var Filter: (name: string) => ngESDecorator;
/**
* Add $inject property to target
*
* @param {Array<string>} dependencies - dependencies to inject
*
* @returns {ngESDecorator} - decorated class
*/
var Inject: (...dependencies: Array<string>) => ngESDecorator;
/**
* Inject dependencies as properties to target
*
* @param {Array<string>} dependencies - dependencies to inject
*
* @returns {ngESDecorator} - decorated class
*/
var InjectAsProperty: (...dependencies: Array<string>) => ngESDecorator;
/**
* Attach target to the specified module
*
* @param {string} name - module name
*
* @returns {ngESDecorator} - decorated class
*/
var Module: (name: string) => ngESDecorator;
/**
* Register provider
*
* @param {string} name - provider name
*
* @returns {ngESDecorator} - decorated class
*/
var Provider: (name: string) => ngESDecorator;
/**
* Register run block
*
* @returns {ngESDecorator} - decorated class
*/
var Run: () => ngESDecorator;
/**
* Register service
*
* @param {string} name - service name
*
* @returns {ngESDecorator} - decorated class
*/
var Service: (name: string) => ngESDecorator;
/**
* Register value
*
* @param {string} name - value name
*
* @returns {ngESDecorator} - decorated class
*/
var Value: (name: string) => ngESDecorator;
export {
Component,
Config,
Constant,
Controller,
Decorator,
Directive,
Factory,
Filter,
Inject,
InjectAsProperty,
Module,
Provider,
Run,
Service,
Value,
}
}
+9
View File
@@ -56,6 +56,15 @@ declare namespace angular.local.storage {
* @param val
*/
set(key:string, val:string):boolean;
/**
* Directly adds a value to cookies with an expiration.
* Note: Typically used as a fallback if local storage is not supported.
* Returns: Boolean
* @param key
* @param val
* @param daysToExpiry
*/
set(key:string, val:string, daysToExpiry:number):boolean;
/**
* Directly get a value from a cookie.
* Returns: value from local storage
+83 -1
View File
@@ -30,7 +30,11 @@ myApp.config((
myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService) => {
$scope['openBottomSheet'] = () => {
$mdBottomSheet.show({
template: '<md-bottom-sheet>Hello!</md-bottom-sheet>'
template: '<md-bottom-sheet>Hello!</md-bottom-sheet>',
clickOutsideToClose: true,
disableBackdrop: true,
disableParentScroll: false,
parent: () => {}
});
};
$scope['hideBottomSheet'] = $mdBottomSheet.hide.bind($mdBottomSheet, 'hide');
@@ -55,6 +59,28 @@ myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.
$scope['confirmDialog'] = () => {
$mdDialog.show($mdDialog.confirm().htmlContent('<span>Confirm!</span>'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().textContent('Prompt!'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().htmlContent('<span>Prompt!</span>'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().cancel('Prompt "Cancel" button text'));
};
$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');
});
@@ -93,8 +119,64 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
$scope['close'] = () => $mdSidenav(componentId).close();
$scope['isOpen'] = $mdSidenav(componentId).isOpen();
$scope['isLockedOpen'] = $mdSidenav(componentId).isLockedOpen();
$scope['asyncLookup'] = $mdSidenav(componentId, true).then((instance) => {
instance.toggle();
instance.open();
instance.close();
instance.isOpen();
instance.isLockedOpen();
});
});
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});
};
});
+121 -9
View File
@@ -1,9 +1,15 @@
// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module)
// Type definitions for Angular Material 1.1.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" />
declare module 'angular-material' {
   var _: string;
  export = _;
}
declare namespace angular.material {
interface IBottomSheetOptions {
@@ -13,11 +19,12 @@ declare namespace angular.material {
preserveScope?: boolean; // default: false
controller?: string|Function;
locals?: {[index: string]: any};
targetEvent?: MouseEvent;
resolve?: {[index: string]: angular.IPromise<any>}
clickOutsideToClose?: boolean;
disableBackdrop?: boolean;
escapeToClose?: boolean;
resolve?: {[index: string]: angular.IPromise<any>};
controllerAs?: string;
bindToController?: boolean;
parent?: string|Element|JQuery; // default: root node
parent?: Function|string|Object; // default: root node
disableParentScroll?: boolean; // default: true
}
@@ -60,9 +67,16 @@ declare namespace angular.material {
cancel(cancel: string): IConfirmDialog;
}
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
cancel(cancel: 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;
@@ -70,7 +84,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
@@ -83,13 +97,15 @@ 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;
hide(response?: any): angular.IPromise<any>;
cancel(response?: any): void;
}
@@ -119,6 +135,7 @@ declare namespace angular.material {
}
interface ISidenavService {
(component: string, enableWait: boolean): angular.IPromise<ISidenavObject>;
(component: string): ISidenavObject;
}
@@ -230,6 +247,7 @@ declare namespace angular.material {
extendPalette(name: string, palette: IPalette): IPalette;
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
setNonce(nonce: string): void;
}
interface IDateLocaleProvider {
@@ -271,4 +289,98 @@ 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;
propagateContainerEvents?: boolean;
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;
updatePosition(position: IPanelPosition): void;
}
interface IPanelPosition {
absolute(): IPanelPosition;
relativeTo(someElement: string|JQuery|Element): IPanelPosition;
top(top?: string): IPanelPosition; // default: '0'
bottom(bottom?: string): IPanelPosition; // default: '0'
start(start?: string): IPanelPosition; // default: '0'
end(end?: string): IPanelPosition; // default: '0'
left(left?: string): IPanelPosition; // default: '0'
right(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;
xPosition: {
CENTER: string,
ALIGN_START: string,
ALIGN_END: string,
OFFSET_START: string,
OFFSET_END: string,
};
yPosition: {
CENTER: string,
ALIGN_TOPS: string,
ALIGN_BOTTOMS: string,
ABOVE: string,
BELOW: string,
};
animation: {
SLIDE: string,
SCALE: string,
FADE: string,
};
}
}
+10 -9
View File
@@ -1,10 +1,11 @@
/// <reference path="./angular-permission.d.ts" />
import permission = angular.permission;
import permissionNamespace = angular.permission;
import { permission, ngPermission, uiPermission } from "angular-permission";
angular
.module('fooModule', ['permission', 'user'])
.run(function (PermissionStore: permission.PermissionStore, User: any) {
.module('fooModule', [permission, ngPermission, uiPermission, 'user'])
.run(function (PermissionStore: permissionNamespace.PermissionStore, User: any) {
// Define anonymous permission
PermissionStore
.definePermission('anonymous', function (stateParams) {
@@ -22,8 +23,8 @@ angular
hasPermissionDefinition(permission: string) : angular.IPromise<any>;
}
angular.module('barModule', ['permission', 'user'])
.run(function (PermissionStore: permission.PermissionStore, User: BackendUserService, $q: angular.IQService) {
angular.module('barModule', [permission, 'user'])
.run(function (PermissionStore: permissionNamespace.PermissionStore, User: BackendUserService, $q: angular.IQService) {
PermissionStore
// Define user permission calling back-end
.definePermission('user', function (stateParams) {
@@ -64,14 +65,14 @@ angular
PermissionStore.removePermissionDefinition('user');
let permissions: Array<permission.Permission> = PermissionStore.getStore();
let permissions: Array<permissionNamespace.Permission> = PermissionStore.getStore();
});
angular
.module('fooModule', ['permission', 'user'])
.run(function (RoleStore: permission.RoleStore, User: any) {
.module('fooModule', [permission, 'user'])
.run(function (RoleStore: permissionNamespace.RoleStore, User: any) {
RoleStore
// Permission array validated role
// Library will internally validate if 'user' and 'editor' permissions are valid when checking if role is valid
@@ -88,5 +89,5 @@ angular
RoleStore.removeRoleDefinition('user');
let roles: Array<permission.Role> = RoleStore.getStore();
let roles: Array<permissionNamespace.Role> = RoleStore.getStore();
});
+6
View File
@@ -173,3 +173,9 @@ declare namespace angular.permission {
options?: angular.ui.IStateOptions;
}
}
declare module "angular-permission" {
export var permission: string;
export var ngPermission: string;
export var uiPermission: string;
}
@@ -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>;
}
}
+6 -3
View File
@@ -13,7 +13,7 @@ declare module "angular-translate" {
declare namespace angular.translate {
interface ITranslationTable {
[key: string]: any;
[key: string]: string | ITranslationTable;
}
interface ILanguageKeyAlias {
@@ -68,10 +68,11 @@ declare namespace angular.translate {
loaderCache(): any;
isReady(): boolean;
onReady(): angular.IPromise<void>;
resolveClientLocale():string;
}
interface ITranslateProvider extends angular.IServiceProvider {
translations(): ITranslationTable;
translations(key?: string): ITranslationTable;
translations(key: string, translationTable: ITranslationTable): ITranslateProvider;
cloakClassName(): string;
cloakClassName(name: string): ITranslateProvider;
@@ -94,8 +95,9 @@ declare namespace angular.translate {
use(key: string): ITranslateProvider;
storageKey(): string;
storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here
uniformLanguageTag(options: string | Object): ITranslateProvider;
useUrlLoader(url: string): ITranslateProvider;
useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider;
useStaticFilesLoader(options: IStaticFilesLoaderOptions | { files: IStaticFilesLoaderOptions[] }): ITranslateProvider;
useLoader(loaderFactory: string, options?: any): ITranslateProvider;
useLocalStorage(): ITranslateProvider;
useCookieStorage(): ITranslateProvider;
@@ -111,6 +113,7 @@ declare namespace angular.translate {
registerAvailableLanguageKeys(): string[];
registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider;
useLoaderCache(cache?: any): ITranslateProvider;
resolveClientLocale():string;
}
}
@@ -181,6 +181,10 @@ testApp.controller('TestCtrl', (
$log.log('modal rendered');
});
modalInstance.closed.then(()=> {
$log.log('modal closed');
});
modalInstance.result.then((closeResult:any)=> {
$log.log('modal closed', closeResult);
}, (dismissResult:any)=> {
+18
View File
@@ -270,6 +270,11 @@ declare namespace angular.ui.bootstrap {
* A promise that is resolved when a modal is rendered.
*/
rendered: angular.IPromise<any>;
/**
* A promise that is resolved when a modal is closed and the animation completes.
*/
closed: angular.IPromise<any>;
}
interface IModalScope extends angular.IScope {
@@ -382,6 +387,19 @@ declare namespace angular.ui.bootstrap {
* @default 'model-open'
*/
openedClass?: string;
/**
* CSS class(es) to be added to the top modal window.
*/
windowTopClass?: string;
/**
* Appends the modal to a specific element.
*
* @default 'body'
*/
appendTo?: angular.IAugmentedJQuery;
}
interface IModalStackService {
+5 -4
View File
@@ -1,6 +1,7 @@
/// <reference path="angular-ui-router.d.ts" />
var myApp = angular.module('testModule');
import uiRouterModule from "angular-ui-router";
var myApp = angular.module("testModule", [uiRouterModule]);
interface MyAppScope extends ng.IScope {
items: string[];
@@ -141,7 +142,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
private $state: ng.ui.IStateService
) {
$rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event));
$rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) =>
$rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) =>
this.onStateNotFound(event, unfoundState, fromState, fromParams));
}
@@ -164,14 +165,14 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
});
}
}
private onStateNotFound(event: ng.IAngularEvent,
unfoundState: ng.ui.IUnfoundState,
fromState: ng.ui.IState,
fromParams: {}) {
var unfoundTo: string = unfoundState.to;
var unfoundToParams: {} = unfoundState.toParams;
var unfoundOptions: ng.ui.IStateOptions = unfoundState.options
var unfoundOptions: ng.ui.IStateOptions = unfoundState.options
}
private stateServiceTest() {
+9 -11
View File
@@ -7,13 +7,7 @@
// Support for AMD require and CommonJS
declare module 'angular-ui-router' {
// Since angular-ui-router adds providers for a bunch of
// injectable dependencies, it doesn't really return any
// actual data except the plain string 'ui.router'.
//
// As such, I don't think anybody will ever use the actual
// default value of the module. So I've only included the
// the types. (@xogeny)
export default "ui.router";
export type IState = angular.ui.IState;
export type IStateProvider = angular.ui.IStateProvider;
export type IUrlMatcher = angular.ui.IUrlMatcher;
@@ -35,7 +29,7 @@ declare namespace angular.ui {
/**
* String HTML content, or function that returns an HTML string
*/
template?: string | {(): string};
template?: string | {(params: IStateParamsService): string};
/**
* String URL path to template file OR Function, returns URL path string
*/
@@ -44,6 +38,10 @@ declare namespace angular.ui {
* Function, returns HTML content string
*/
templateProvider?: Function | Array<string|Function>;
/**
* String, component name
*/
component?: string;
/**
* A controller paired to the state. Function, annotated array or name as String
*/
@@ -105,7 +103,7 @@ declare namespace angular.ui {
toParams: {},
options: IStateOptions
}
interface IStateProvider extends angular.IServiceProvider {
state(name:string, config:IState): IStateProvider;
state(config:IState): IStateProvider;
@@ -229,9 +227,9 @@ declare namespace angular.ui {
*/
notify?: boolean;
/**
* {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.
* {boolean=false|string|IState}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.
*/
reload?: boolean;
reload?: boolean | string | IState;
}
interface IHrefOptions {
@@ -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";
}]);
+98
View File
@@ -0,0 +1,98 @@
// 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;
}
interface IEditableFormController extends angular.IFormController {
/**
* Shows form with editable controls.
*/
$show(): void;
/**
* Hides form with editable controls without saving.
*/
$hide(): void;
/**
* Sets focus on form field specified by `name`.<br/>
* When trying to set the focus on a form field of a new row in the editable table, the `$activate` call needs to be wrapped in a `$timeout` call so that the form is rendered before the `$activate` function is called.
*
* @param name name of field
*/
$activate(name: string): void;
/**
* Triggers `oncancel` event and calls `$hide()`.
*/
$cancel(): void;
$setWaiting(value: boolean): void;
/**
* Shows error message for particular field.
*
* @param name name of field
* @param msg error message
*/
$setError(name: string, msg: string): void;
$submit(): void;
$save(): void;
}
}
+37 -26
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.
@@ -69,8 +69,8 @@ declare namespace angular.animate {
* @param value If provided then set the animation on or off.
* @returns current animation state
*/
enabled(value?: boolean): boolean;
enabled(element: JQuery, value?: boolean): boolean;
enabled(value: boolean): boolean;
/**
* Cancels the provided animation.
@@ -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 {
+51
View File
@@ -428,4 +428,55 @@ declare namespace angular {
interface OnReuse {
$routerOnReuse(next?: angular.ComponentInstruction, prev?: angular.ComponentInstruction): any;
}
/**
* Runtime representation a type that a Component or other object is instances of.
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.
*/
interface Type extends Function {
}
/**
* `RouteDefinition` defines a route within a {@link RouteConfig} decorator.
*
* Supported keys:
* - `path` or `aux` (requires exactly one of these)
* - `component`, `loader`, `redirectTo` (requires exactly one of these)
* - `name` or `as` (optional) (requires exactly one of these)
* - `data` (optional)
*
* See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}.
*/
interface RouteDefinition {
path?: string;
aux?: string;
component?: Type | ComponentDefinition | string;
loader?: Function;
redirectTo?: any[];
as?: string;
name?: string;
data?: any;
useAsDefault?: boolean;
}
/**
* Represents either a component type (`type` is `component`) or a loader function
* (`type` is `loader`).
*
* See also {@link RouteDefinition}.
*/
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
// Supplement IComponentOptions from angular.d.ts with router-specific
// fields.
interface IComponentOptions {
$canActivate?: () => boolean;
$routeConfig?: RouteDefinition[];
}
}
+49
View File
@@ -137,15 +137,19 @@ requestHandler = httpBackendService.expect('GET', /test.local/);
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data');
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/);
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
@@ -163,17 +167,21 @@ requestHandler = httpBackendService.expect('GET', (url: string) => { return true
requestHandler = httpBackendService.expectDELETE('http://test.local');
requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectGET('http://test.local');
requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectGET(/test.local\/(\d+)/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectHEAD('http://test.local');
requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectJSONP('http://test.local');
requestHandler = httpBackendService.expectJSONP(/test.local/);
requestHandler = httpBackendService.expectJSONP(/test.local\/(\d+)/, ['id']);
requestHandler = httpBackendService.expectJSONP((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH('http://test.local');
@@ -188,12 +196,15 @@ requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'val
requestHandler = httpBackendService.expectPATCH(/test.local/);
requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data');
requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/);
requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
@@ -216,12 +227,15 @@ requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'valu
requestHandler = httpBackendService.expectPOST(/test.local/);
requestHandler = httpBackendService.expectPOST(/test.local/, 'response data');
requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPOST(/test.local/, /response data/);
requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPOST((url: string) => { return true; });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' });
@@ -244,12 +258,16 @@ requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value
requestHandler = httpBackendService.expectPUT(/test.local/);
requestHandler = httpBackendService.expectPUT(/test.local/, 'response data');
requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPUT(/test.local/, /response data/);
requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.expectPUT((url: string) => { return true; });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' });
@@ -276,16 +294,24 @@ requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'val
requestHandler = httpBackendService.when('GET', /test.local/);
requestHandler = httpBackendService.when('GET', /test.local/, 'response data');
requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']);
requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.when('GET', /test.local/, /response data/);
requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']);
requestHandler = httpBackendService.when('GET', (url: string) => { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
@@ -303,17 +329,21 @@ requestHandler = httpBackendService.when('GET', (url: string) => { return true;
requestHandler = httpBackendService.whenDELETE('http://test.local');
requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenGET('http://test.local');
requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenGET(/test.local\/(\d+)/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenHEAD('http://test.local');
requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenJSONP('http://test.local');
requestHandler = httpBackendService.whenJSONP(/test.local/);
requestHandler = httpBackendService.whenJSONP(/test.local\/(\d+)/, ['id']);
requestHandler = httpBackendService.whenJSONP((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH('http://test.local');
@@ -328,12 +358,16 @@ requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value
requestHandler = httpBackendService.whenPATCH(/test.local/);
requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data');
requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/);
requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
@@ -356,12 +390,16 @@ requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value'
requestHandler = httpBackendService.whenPOST(/test.local/);
requestHandler = httpBackendService.whenPOST(/test.local/, 'response data');
requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPOST(/test.local/, /response data/);
requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPOST((url: string) => { return true; });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' });
@@ -384,12 +422,16 @@ requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value'
requestHandler = httpBackendService.whenPUT(/test.local/);
requestHandler = httpBackendService.whenPUT(/test.local/, 'response data');
requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPUT(/test.local/, /response data/);
requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']);
requestHandler = httpBackendService.whenPUT((url: string) => { return true; });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' });
@@ -410,6 +452,13 @@ requestHandler.passThrough().passThrough();
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']);
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({});
requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; });
requestHandler.respond((method, url, data, headers, params) => {
if(params.id === 1) {
return [200, { key: 'value'}, { header: 'value'}, 'responseText'];
} else {
return [404, { key: 'value' }, { header: 'value' }, 'responseText'];
}
});
requestHandler.respond('data');
requestHandler.respond('data').respond({});
requestHandler.respond(expectedData);
+38 -20
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Type definitions for Angular JS 1.5 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Tony Curtis <http://github.com/daltin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -157,8 +157,9 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler;
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]) :mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
@@ -166,8 +167,9 @@ declare namespace angular {
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
@@ -175,8 +177,9 @@ declare namespace angular {
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
@@ -184,16 +187,19 @@ declare namespace angular {
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
@@ -202,8 +208,9 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
@@ -212,8 +219,9 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
@@ -222,8 +230,9 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition.
@@ -232,40 +241,46 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in request url described above
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
whenJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
@@ -273,8 +288,9 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
@@ -282,8 +298,9 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
@@ -291,8 +308,9 @@ declare namespace angular {
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
}
export module mock {
@@ -302,9 +320,9 @@ declare namespace angular {
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
* @param func Function that receives the request HTTP method, url, data, headers, and an array of keys to regex matches in the request url and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler;
respond(func: ((method: string, url: string, data: string | Object, headers: Object, params?: any) => [number, string | Object, Object, string])): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
+2 -2
View File
@@ -95,7 +95,7 @@ declare namespace angular.resource {
(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
}
// Baseclass for everyresource with default actions.
// Baseclass for every resource with default actions.
// If you define your new actions for the resource, you will need
// to extend this interface and typecast the ResourceClass to it.
//
@@ -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>;
+11 -3
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: '='
},
@@ -1096,6 +1098,12 @@ function parseTyping() {
}
}
function parseWithParams() {
var $parse: angular.IParseService;
var compiledExp = $parse('a.b.c', () => null);
var compiledExp = $parse('a.b.c', null, false);
}
function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService {
if (mode === 'debug') {
return angular.bootstrap(element, ['main', function($provide: ng.auto.IProvideService) {
@@ -1103,11 +1111,11 @@ function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjector
$delegate['debug'] = true;
});
}, 'debug-helpers'], {
debugInfoEnabled: true
strictDi: true
});
}
return angular.bootstrap(element, ['main'], {
debugInfoEnabled: false
strictDi: false
});
}
+142 -104
View File
@@ -41,7 +41,6 @@ declare namespace angular {
interface IAngularBootstrapConfig {
strictDi?: boolean;
debugInfoEnabled?: boolean;
}
///////////////////////////////////////////////////////////////////////////
@@ -81,7 +80,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;
@@ -119,14 +118,14 @@ declare namespace angular {
fromJson(json: string): any;
identity<T>(arg?: T): T;
injector(modules?: any[], strictDi?: boolean): auto.IInjectorService;
isArray(value: any): boolean;
isDate(value: any): boolean;
isArray(value: any): value is Array<any>;
isDate(value: any): value is Date;
isDefined(value: any): boolean;
isElement(value: any): boolean;
isFunction(value: any): boolean;
isNumber(value: any): boolean;
isObject(value: any): boolean;
isString(value: any): boolean;
isFunction(value: any): value is Function;
isNumber(value: any): value is number;
isObject(value: any): value is Object;
isString(value: any): value is string;
isUndefined(value: any): boolean;
lowercase(str: string): string;
@@ -156,7 +155,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;
@@ -388,10 +387,11 @@ declare namespace angular {
$invalid: boolean;
$submitted: boolean;
$error: any;
$name: string;
$pending: any;
$addControl(control: INgModelController): void;
$removeControl(control: INgModelController): void;
$setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void;
$addControl(control: INgModelController | IFormController): void;
$removeControl(control: INgModelController | IFormController): void;
$setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void;
$setDirty(): void;
$setPristine(): void;
$commitViewValue(): void;
@@ -874,7 +874,7 @@ declare namespace angular {
// see http://docs.angularjs.org/api/ng.$parseProvider
///////////////////////////////////////////////////////////////////////////
interface IParseService {
(expression: string): ICompiledExpression;
(expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression;
}
interface IParseProvider {
@@ -883,6 +883,24 @@ declare namespace angular {
unwrapPromises(): boolean;
unwrapPromises(value: boolean): IParseProvider;
/**
* Configure $parse service to add literal values that will be present as literal at expressions.
*
* @param literalName Token for the literal value. The literal name value must be a valid literal name.
* @param literalValue Value for this literal. All literal values must be primitives or `undefined`.
**/
addLiteral(literalName: string, literalValue: any): void;
/**
* Allows defining the set of characters that are allowed in Angular expressions. The function identifierStart will get called to know if a given character is a valid character to be the first character for an identifier. The function identifierContinue will get called to know if a given character is a valid character to be a follow-up identifier character. The functions identifierStart and identifierContinue will receive as arguments the single character to be identifier and the character code point. These arguments will be string and numeric. Keep in mind that the string parameter can be two characters long depending on the character representation. It is expected for the function to return true or false, whether that character is allowed or not.
* Since this function will be called extensivelly, keep the implementation of these functions fast, as the performance of these functions have a direct impact on the expressions parsing speed.
*
* @param identifierStart The function that will decide whether the given character is a valid identifier start character.
* @param identifierContinue The function that will decide whether the given character is a valid identifier continue character.
**/
setIdentifierFns(identifierStart?: (character: string, codePoint: number) => boolean,
identifierContinue?: (character: string, codePoint: number) => boolean): void;
}
interface ICompiledExpression {
@@ -968,7 +986,10 @@ declare namespace angular {
// DocumentService
// see http://docs.angularjs.org/api/ng.$document
///////////////////////////////////////////////////////////////////////////
interface IDocumentService extends IAugmentedJQuery {}
interface IDocumentService extends JQuery {
// Must return intersection type for index signature compatibility with JQuery
[index: number]: HTMLElement & Document;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
@@ -1231,15 +1252,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;
}
///////////////////////////////////////////////////////////////////////////
@@ -1656,50 +1677,6 @@ declare namespace angular {
// see http://angularjs.blogspot.com.br/2015/11/angularjs-15-beta2-and-14-releases.html
// and http://toddmotto.com/exploring-the-angular-1-5-component-method/
///////////////////////////////////////////////////////////////////////////
/**
* Runtime representation a type that a Component or other object is instances of.
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.
*/
interface Type extends Function {
}
/**
* `RouteDefinition` defines a route within a {@link RouteConfig} decorator.
*
* Supported keys:
* - `path` or `aux` (requires exactly one of these)
* - `component`, `loader`, `redirectTo` (requires exactly one of these)
* - `name` or `as` (optional) (requires exactly one of these)
* - `data` (optional)
*
* See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}.
*/
interface RouteDefinition {
path?: string;
aux?: string;
component?: Type | ComponentDefinition | string;
loader?: Function;
redirectTo?: any[];
as?: string;
name?: string;
data?: any;
useAsDefault?: boolean;
}
/**
* Represents either a component type (`type` is `component`) or a loader function
* (`type` is `loader`).
*
* See also {@link RouteDefinition}.
*/
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
/**
* Component definition object (a simplified directive definition object)
*/
@@ -1709,7 +1686,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.
@@ -1742,11 +1719,58 @@ declare namespace angular {
* Whether transclusion is enabled. Enabled by default.
*/
transclude?: boolean | string | {[slot: string]: string};
require?: string | string[] | {[controller: string]: string};
/**
* Requires the controllers of other directives and binds them to this component's controller.
* The object keys specify the property names under which the required controllers (object values) will be bound.
* Note that the required controllers will not be available during the instantiation of the controller,
* but they are guaranteed to be available just before the $onInit method is executed!
*/
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;
}
///////////////////////////////////////////////////////////////////////////
@@ -1762,7 +1786,7 @@ declare namespace angular {
interface IDirectiveLinkFn {
(
scope: IScope,
instanceElement: IAugmentedJQuery,
instanceElement: JQuery,
instanceAttributes: IAttributes,
controller: {},
transclude: ITranscludeFunction
@@ -1776,7 +1800,7 @@ declare namespace angular {
interface IDirectiveCompileFn {
(
templateElement: IAugmentedJQuery,
templateElement: JQuery,
templateAttributes: IAttributes,
/**
* @deprecated
@@ -1785,7 +1809,7 @@ declare namespace angular {
* that is passed to the link function instead.
*/
transclude: ITranscludeFunction
): IDirectivePrePost;
): void | IDirectivePrePost;
}
interface IDirective {
@@ -1818,44 +1842,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)
@@ -1870,6 +1864,33 @@ declare namespace angular {
annotate(fn: Function, strictDi?: boolean): string[];
annotate(inlineAnnotatedFunction: any[]): string[];
get<T>(name: string, caller?: string): T;
get(name: '$anchorScroll'): IAnchorScrollService
get(name: '$cacheFactory'): ICacheFactoryService
get(name: '$compile'): ICompileService
get(name: '$controller'): IControllerService
get(name: '$document'): IDocumentService
get(name: '$exceptionHandler'): IExceptionHandlerService
get(name: '$filter'): IFilterService
get(name: '$http'): IHttpService
get(name: '$httpBackend'): IHttpBackendService
get(name: '$httpParamSerializer'): IHttpParamSerializer
get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer
get(name: '$interpolate'): IInterpolateService
get(name: '$interval'): IIntervalService
get(name: '$locale'): ILocaleService
get(name: '$location'): ILocationService
get(name: '$log'): ILogService
get(name: '$parse'): IParseService
get(name: '$q'): IQService
get(name: '$rootElement'): IRootElementService
get(name: '$rootScope'): IRootScopeService
get(name: '$sce'): ISCEService
get(name: '$sceDelegate'): ISCEDelegateService
get(name: '$templateCache'): ITemplateCacheService
get(name: '$templateRequest'): ITemplateRequestService
get(name: '$timeout'): ITimeoutService
get(name: '$window'): IWindowService
get<T>(name: '$xhrFactory'): IXhrFactory<T>
has(name: string): boolean;
instantiate<T>(typeConstructor: Function, locals?: any): T;
invoke(inlineAnnotatedFunction: any[]): any;
@@ -1930,3 +1951,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;
}
+1 -1
View File
@@ -886,7 +886,7 @@ declare namespace angular {
// see http://docs.angularjs.org/api/ng.$parseProvider
///////////////////////////////////////////////////////////////////////////
interface IParseService {
(expression: string): ICompiledExpression;
(expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression;
}
interface IParseProvider {
+403
View File
@@ -0,0 +1,403 @@
/// <reference path="angular-mocks-1.3.d.ts" />
///////////////////////////////////////
// IAngularStatic
///////////////////////////////////////
var angular: ng.IAngularStatic;
var mock: ng.IMockStatic;
mock = angular.mock;
///////////////////////////////////////
// IMockStatic
///////////////////////////////////////
var date: Date;
mock.dump({ key: 'value' });
mock.inject(
function () { return 1; },
function () { return 2; }
);
mock.inject(
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }]);
// This overload is not documented on the website, but flows from
// how the injector works.
mock.inject(
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }],
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 2; }]);
mock.module('module1', 'module2');
mock.module(
function () { return 1; },
function () { return 2; }
);
mock.module({ module1: function () { return 1; } });
date = mock.TzDate(-7, '2013-1-1T15:00:00Z');
date = mock.TzDate(-8, 12345678);
///////////////////////////////////////
// IExceptionHandlerProvider
///////////////////////////////////////
var exceptionHandlerProvider: ng.IExceptionHandlerProvider;
exceptionHandlerProvider.mode('log');
///////////////////////////////////////
// ITimeoutService
///////////////////////////////////////
var timeoutService: ng.ITimeoutService;
timeoutService.flush();
timeoutService.flush(1234);
timeoutService.flushNext();
timeoutService.flushNext(1234);
timeoutService.verifyNoPendingTasks();
////////////////////////////////////////
// IIntervalService
////////////////////////////////////////
var intervalService: ng.IIntervalService;
var intervalServiceTimeActuallyAdvanced: number;
intervalServiceTimeActuallyAdvanced = intervalService.flush();
intervalServiceTimeActuallyAdvanced = intervalService.flush(1234);
///////////////////////////////////////
// ILogService, ILogCall
///////////////////////////////////////
var logService: ng.ILogService;
var logCall: ng.ILogCall;
var logs: string[];
logService.assertEmpty();
logService.reset();
logCall = logService.debug;
logCall = logService.error;
logCall = logService.info;
logCall = logService.log;
logCall = logService.warn;
logs = logCall.logs;
///////////////////////////////////////
// IHttpBackendService
///////////////////////////////////////
var httpBackendService: ng.IHttpBackendService;
var requestHandler: ng.mock.IRequestHandler;
httpBackendService.flush();
httpBackendService.flush(1234);
httpBackendService.resetExpectations();
httpBackendService.verifyNoOutstandingExpectation();
httpBackendService.verifyNoOutstandingRequest();
requestHandler = httpBackendService.expect('GET', 'http://test.local');
requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data');
requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/);
requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/);
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data');
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/);
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expectDELETE('http://test.local');
requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectGET('http://test.local');
requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectHEAD('http://test.local');
requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectJSONP('http://test.local');
requestHandler = httpBackendService.expectJSONP(/test.local/);
requestHandler = httpBackendService.expectJSONP((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH('http://test.local');
requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data');
requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/);
requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' });
requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/);
requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data');
requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/);
requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local');
requestHandler = httpBackendService.expectPOST('http://test.local', 'response data');
requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', /response data/);
requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/);
requestHandler = httpBackendService.expectPOST(/test.local/, 'response data');
requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, /response data/);
requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local');
requestHandler = httpBackendService.expectPUT('http://test.local', 'response data');
requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', /response data/);
requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/);
requestHandler = httpBackendService.expectPUT(/test.local/, 'response data');
requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, /response data/);
requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local');
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data');
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/);
requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/);
requestHandler = httpBackendService.when('GET', /test.local/, 'response data');
requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, /response data/);
requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.whenDELETE('http://test.local');
requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenGET('http://test.local');
requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenHEAD('http://test.local');
requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenJSONP('http://test.local');
requestHandler = httpBackendService.whenJSONP(/test.local/);
requestHandler = httpBackendService.whenJSONP((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH('http://test.local');
requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data');
requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/);
requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' });
requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/);
requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data');
requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/);
requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local');
requestHandler = httpBackendService.whenPOST('http://test.local', 'response data');
requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', /response data/);
requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/);
requestHandler = httpBackendService.whenPOST(/test.local/, 'response data');
requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, /response data/);
requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local');
requestHandler = httpBackendService.whenPUT('http://test.local', 'response data');
requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', /response data/);
requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/);
requestHandler = httpBackendService.whenPUT(/test.local/, 'response data');
requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, /response data/);
requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
///////////////////////////////////////
// IRequestHandler
///////////////////////////////////////
var expectedData = { key: 'value'};
requestHandler.passThrough();
requestHandler.passThrough().passThrough();
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']);
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({});
requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; });
requestHandler.respond('data');
requestHandler.respond('data').respond({});
requestHandler.respond(expectedData);
requestHandler.respond({ key: 'value' });
requestHandler.respond({ key: 'value' }, { header: 'value' });
requestHandler.respond({ key: 'value' }, { header: 'value' }, 'responseText');
requestHandler.respond(404, 'data');
requestHandler.respond(404, 'data').respond({});
requestHandler.respond(404, { key: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText');
+318
View File
@@ -0,0 +1,318 @@
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Tony Curtis <http://github.com/daltin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular-1.4.d.ts" />
declare module "angular-mocks/ngMock" {
var _: string;
export = _;
}
declare module "angular-mocks/ngMockE2E" {
var _: string;
export = _;
}
declare module "angular-mocks/ngAnimateMock" {
var _: string;
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
declare module angular {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// We reopen it to add the MockStatic definition
///////////////////////////////////////////////////////////////////////////
interface IAngularStatic {
mock: IMockStatic;
}
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
interface IInjectStatic {
(...fns: Function[]): any;
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
strictDi(val?: boolean): void;
}
interface IMockStatic {
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
dump(obj: any): string;
inject: IInjectStatic
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module(...modules: any[]): any;
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
TzDate(offset: number, timestamp: string): Date;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
// see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler
// see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider
///////////////////////////////////////////////////////////////////////////
interface IExceptionHandlerProvider extends IServiceProvider {
mode(mode: string): void;
}
///////////////////////////////////////////////////////////////////////////
// TimeoutService
// see https://docs.angularjs.org/api/ngMock/service/$timeout
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
flush(delay?: number): void;
flushNext(expectedDelay?: number): void;
verifyNoPendingTasks(): void;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see https://docs.angularjs.org/api/ngMock/service/$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
flush(millis?: number): number;
}
///////////////////////////////////////////////////////////////////////////
// LogService
// see https://docs.angularjs.org/api/ngMock/service/$log
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ILogService {
assertEmpty(): void;
reset(): void;
}
interface ILogCall {
logs: string[];
}
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes all pending requests using the trained responses.
* @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
*/
flush(count?: number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
*/
verifyNoOutstandingExpectation(): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
// Available when ngMockE2E is loaded
/**
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
*/
passThrough(): IRequestHandler;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
//declare var module: (...modules: any[]) => any;
declare var inject: angular.IInjectStatic;
+82
View File
@@ -0,0 +1,82 @@
/// <reference path="../react/react.d.ts" />
/// <reference path="./aphrodite.d.ts" />
import * as React from "react";
import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils } from "aphrodite";
const styles = StyleSheet.create({
red: {
backgroundColor: 'red'
},
blue: {
backgroundColor: 'blue'
},
hover: {
':hover': {
backgroundColor: 'red'
}
},
small: {
'@media (max-width: 600px)': {
backgroundColor: 'red',
}
}
});
const coolFont = {
fontFamily: "CoolFont",
fontStyle: "normal",
fontWeight: "normal",
src: "url('coolfont.woff2') format('woff2')"
};
const withFont = StyleSheet.create({
headingText: {
fontFamily: coolFont,
fontSize: 20
},
bodyText: {
fontFamily: [coolFont, "sans-serif"],
fontSize: 12
}
});
class App extends React.Component<{}, {}> {
render() {
return <div>
<span className={css(styles.red)}>
This is red.
</span>
<span className={css(styles.hover)}>
This turns red on hover.
</span>
<span className={css(styles.small)}>
This turns red when the browser is less than 600px width.
</span>
<span className={css(styles.red, styles.blue)}>
This is blue.
</span>
<span className={css(styles.blue, styles.small)}>
This is blue and turns red when the browser is less than
600px width.
</span>
<span className={css(withFont.bodyText)}>
With font
</span>
</div>;
}
}
const output = StyleSheetServer.renderStatic(() => {
return "test";
});
output.css.content;
output.css.renderedClassNames;
output.html;
StyleSheet.rehydrate(output.css.renderedClassNames);
StyleSheetTestUtils.suppressStyleInjection();
StyleSheetTestUtils.clearBufferAndResumeStyleInjection();
+76
View File
@@ -0,0 +1,76 @@
// Type definitions for Aphrodite 0.5.0
// Project: https://github.com/Khan/aphrodite
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
declare module "aphrodite" {
import * as React from "react";
/**
* Aphrodite style declaration
*/
export interface StyleDeclaration {
[key: string]: React.CSSProperties;
}
interface StyleSheetStatic {
/**
* Create style sheet
*/
create<T extends StyleDeclaration>(styles: T): T;
/**
* Rehydrate class names from server renderer
*/
rehydrate(renderedClassNames: string[]): void;
}
export var StyleSheet: StyleSheetStatic;
/**
* Get class names from passed styles
*/
export function css(...styles: any[]): string;
interface StaticRendererResult {
html: string;
css: {
content: string;
renderedClassNames: string[];
}
}
/**
* Utilities for using Aphrodite server-side.
*/
interface StyleSheetServerStatic {
renderStatic(renderFunc: () => string): StaticRendererResult;
}
export var StyleSheetServer: StyleSheetServerStatic;
interface StyleSheetTestUtilsStatic {
/**
* Prevent styles from being injected into the DOM.
*
* This is useful in situations where you'd like to test rendering UI
* components which use Aphrodite without any of the side-effects of
* Aphrodite happening. Particularly useful for testing the output of
* components when you have no DOM, e.g. testing in Node without a fake DOM.
*
* Should be paired with a subsequent call to
* clearBufferAndResumeStyleInjection.
*/
suppressStyleInjection(): void;
/**
* Opposite method of preventStyleInject.
*/
clearBufferAndResumeStyleInjection(): void;
}
export var StyleSheetTestUtils: StyleSheetTestUtilsStatic;
}
declare module "aphrodite/no-important" {
export * from "aphrodite";
}
+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;
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="app-root-path.d.ts" />
import * as root from 'app-root-path';
let resolvedPath: string;
resolvedPath = root.resolve('../dir');
resolvedPath = root.path;
resolvedPath = root.toString();
let resolvedModule: any = root.require('app-root-path');
root.setPath('C:\\app-root');
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for app-root-path 1.2.1
// Project: https://github.com/inxilpro/node-app-root-path
// Definitions by: Shant Marouti <https://github.com/shantmarouti>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'app-root-path' {
interface RootPath {
/**
* Application root directory absolute path
* @type {string}
*/
path: string;
/**
* Resolves relative path from root to absolute path
* @param {string} pathToModule
* @returns {string}
*/
resolve(pathToModule: string): string;
/**
* Resolve module by relative addressing from root
* @param {string} pathToModule
* @returns {*}
*/
require(pathToModule: string): any;
/**
* Explicitly set root path
* @param {string} explicitlySetPath
*/
setPath(explicitlySetPath: string): void;
toString(): string;
}
var RootPath: RootPath;
export = RootPath;
}
@@ -0,0 +1,157 @@
///<reference path='applicationinsights-js.d.ts' />
// More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md
var config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: "<your iKey>",
endpointUrl: "endpointUrl",
emitLineDelimitedJson: false,
accountId: "accountId",
sessionRenewalMs: 30,
sessionExpirationMs: 24 * 60 * 60 * 1000,
maxBatchSizeInBytes: 100 * 1024,
maxBatchInterval: 15,
enableDebug: false,
disableTelemetry: false,
verboseLogging: false,
diagnosticLogInterval: 10,
samplingPercentage: 100,
autoTrackPageVisitTime: true,
disableExceptionTracking: false,
disableAjaxTracking: false,
overridePageViewDuration: false,
maxAjaxCallsPerView: -1,
disableDataLossAnalysis: true,
disableCorrelationHeaders: true,
disableFlushOnBeforeUnload: false,
enableSessionStorageBuffer: false,
cookieDomain: ""
};
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");
appInsights.trackPageView("page2", "http://example.com", null, null, 1000);
// startTrackPage
appInsights.startTrackPage("page");
// stopTrackPage
appInsights.stopTrackPage("page");
appInsights.stopTrackPage("page", "http://example.com", null, null);
// trackEvent
appInsights.trackEvent("page1");
appInsights.trackEvent("page1", null, null);
// trackMetric
appInsights.trackMetric("page1", 999);
appInsights.trackMetric("page1", 999, 1, 1, 2, null);
// trackException
appInsights.trackException(new Error("sample error"));
appInsights.trackException(new Error("sample error"), "handledAt", null, null);
// trackTrace
appInsights.trackTrace("message");
appInsights.trackTrace("message", null);
// flush
appInsights.flush();
// setAuthenticatedUserContext
appInsights.setAuthenticatedUserContext("userId");
appInsights.setAuthenticatedUserContext("userId", "accountId");
// set config dynamically
appInsights.config.instrumentationKey = "<new key>";
// TelementryContext
var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context;
context.application.ver = "v0.0.0";
context.application.build = "1.1.1";
context.device.type = "sampleDevice";
context.device.locale = "en-US";
context.user.id = "userId";
context.user.authenticatedId = "authId";
context.session.id = "sessionId";
context.session.isFirst = true;
context.location.ip = "127.0.0.1";
context.operation.id = "1";
context.operation.syntheticSource = "testAgent";
// track
var data = new Microsoft.Telemetry.Base();
var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, "name");
context.track(envelope);
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);
+796
View File
@@ -0,0 +1,796 @@
// Type definitions for ApplicationInsights-JS v0.23.2
// Project: https://github.com/Microsoft/ApplicationInsights-JS
// Definitions by: Kamil Szostak <https://github.com/kamilszostak>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module AI {
enum SeverityLevel {
Verbose = 0,
Information = 1,
Warning = 2,
Error = 3,
Critical = 4,
}
enum DependencyKind {
SQL = 0,
Http = 1,
Other = 2,
}
enum DependencySourceType {
Undefined = 0,
Aic = 1,
Apmc = 2,
}
class StackFrame {
level: number;
method: string;
assembly: string;
fileName: string;
line: number;
constructor();
}
class ExceptionDetails {
id: number;
outerId: number;
typeName: string;
message: string;
hasFullStack: boolean;
stack: string;
parsedStack: StackFrame[];
constructor();
}
enum DataPointType {
Measurement = 0,
Aggregation = 1,
}
class DataPoint {
name: string;
kind: AI.DataPointType;
value: number;
count: number;
min: number;
max: number;
stdDev: number;
constructor();
}
class EventData extends Microsoft.Telemetry.Domain {
ver: number;
name: string;
properties: any;
measurements: any;
constructor();
}
class PageViewData extends AI.EventData {
ver: number;
url: string;
name: string;
duration: string;
referrer: string;
referrerData: string;
properties: any;
measurements: any;
constructor();
}
class PageViewPerfData extends AI.PageViewData {
ver: number;
url: string;
perfTotal: string;
name: string;
duration: string;
networkConnect: string;
referrer: string;
sentRequest: string;
referrerData: string;
receivedResponse: string;
domProcessing: string;
properties: any;
measurements: any;
constructor();
}
class RemoteDependencyData extends Microsoft.Telemetry.Domain {
ver: number;
name: string;
id: string;
resultCode: string;
kind: AI.DataPointType;
value: number;
count: number;
min: number;
max: number;
stdDev: number;
dependencyKind: AI.DependencyKind;
success: boolean;
async: boolean;
dependencySource: AI.DependencySourceType;
commandName: string;
dependencyTypeName: string;
properties: any;
constructor();
}
class MessageData extends Microsoft.Telemetry.Domain {
ver: number;
message: string;
severityLevel: AI.SeverityLevel;
properties: any;
constructor();
}
}
declare module Microsoft.ApplicationInsights.Context {
interface IApplication {
/**
* The application version.
*/
ver: string;
/**
* The application build version.
*/
build: string;
}
interface IDevice {
/**
* The type for the current device.
*/
type: string;
/**
* A device unique ID.
*/
id: string;
/**
* The device OEM for the current device.
*/
oemName: string;
/**
* The device model for the current device.
*/
model: string;
/**
* The IANA interface type for the internet connected network adapter.
*/
network: number;
/**
* The application screen resolution.
*/
resolution: string;
/**
* The current display language of the operating system.
*/
locale: string;
/**
* The IP address.
*/
ip: string;
/**
* The device language.
*/
language: string;
/**
* The OS name.
*/
os: string;
/**
* The OS version.
*/
osversion: string;
}
interface ILocation {
/**
* Client IP address for reverse lookup
*/
ip: string;
}
interface IInternal {
/**
* The SDK version used to create this telemetry item.
*/
sdkVersion: string;
/**
* The SDK agent version.
*/
agentVersion: string;
}
interface ISample {
/**
* Sample rate
*/
sampleRate: number;
}
interface ISession {
/**
* The session ID.
*/
id: string;
/**
* The true if this is the first session
*/
isFirst: boolean;
/**
* The date at which this guid was genereated.
* Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds ellapse from this time.
*/
acquisitionDate: number;
/**
* The date at which this session ID was last reported.
* This value should be updated whenever telemetry is sent using this ID.
* Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity.
*/
renewalDate: number;
}
interface IOperation {
/**
* Operation id
*/
id: string;
/**
* Operation name
*/
name: string;
/**
* Parent operation id
*/
parentId: string;
/**
* Root operation id
*/
rootId: string;
/**
* Synthetic source of the operation
*/
syntheticSource: string;
}
interface IUser {
/**
* The telemetry configuration.
*/
config: any;
/**
* The user ID.
*/
id: string;
/**
* Authenticated user id
*/
authenticatedId: string;
/**
* The account ID.
*/
accountId: string;
/**
* The account acquisition date.
*/
accountAcquisitionDate: string;
/**
* The user agent string.
*/
agent: string;
/**
* The store region.
*/
storeRegion: string;
}
}
declare module Microsoft.Telemetry {
class Domain {
constructor();
}
class Base {
baseType: string;
constructor();
}
class Data<TDomain> extends Microsoft.Telemetry.Base {
baseType: string;
baseData: TDomain;
constructor();
}
}
declare module Microsoft.ApplicationInsights.Telemetry {
class Event implements Microsoft.ApplicationInsights.ISerializable {
static envelopeType: string;
static dataType: string;
ver: number;
name: string;
properties: any;
measurements: any;
aiDataContract: {
ver: Microsoft.ApplicationInsights.FieldType;
name: Microsoft.ApplicationInsights.FieldType;
properties: Microsoft.ApplicationInsights.FieldType;
measurements: Microsoft.ApplicationInsights.FieldType;
};
/**
* Constructs a new instance of the EventTelemetry object
*/
constructor(name: string, properties?: Object, measurements?: Object);
}
class Exception implements Microsoft.ApplicationInsights.ISerializable {
static envelopeType: string;
static dataType: string;
ver: number;
handledAt: string;
exceptions: AI.ExceptionDetails[];
severityLevel: AI.SeverityLevel;
problemId: string;
crashThreadId: number;
properties: any;
measurements: any;
aiDataContract: {
ver: Microsoft.ApplicationInsights.FieldType;
handledAt: Microsoft.ApplicationInsights.FieldType;
exceptions: Microsoft.ApplicationInsights.FieldType;
severityLevel: Microsoft.ApplicationInsights.FieldType;
properties: Microsoft.ApplicationInsights.FieldType;
measurements: Microsoft.ApplicationInsights.FieldType;
};
/**
* Constructs a new isntance of the ExceptionTelemetry object
*/
constructor(exception: Error, handledAt?: string, properties?: Object, measurements?: Object, severityLevel?: AI.SeverityLevel);
/**
* Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.
*/
static CreateSimpleException(message: string, typeName: string, assembly: string, fileName: string, details: string, line: number, handledAt?: string): Telemetry.Exception;
}
class Metric implements Microsoft.ApplicationInsights.ISerializable {
static envelopeType: string;
static dataType: string;
ver: number;
metrics: AI.DataPoint[];
properties: any;
aiDataContract: {
ver: Microsoft.ApplicationInsights.FieldType;
metrics: Microsoft.ApplicationInsights.FieldType;
properties: Microsoft.ApplicationInsights.FieldType;
};
/**
* Constructs a new instance of the MetricTelemetry object
*/
constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: Object);
}
class PageView extends AI.PageViewData implements Microsoft.ApplicationInsights.ISerializable {
static envelopeType: string;
static dataType: string;
aiDataContract: {
ver: Microsoft.ApplicationInsights.FieldType;
name: Microsoft.ApplicationInsights.FieldType;
url: Microsoft.ApplicationInsights.FieldType;
duration: Microsoft.ApplicationInsights.FieldType;
properties: Microsoft.ApplicationInsights.FieldType;
measurements: Microsoft.ApplicationInsights.FieldType;
};
/**
* Constructs a new instance of the PageEventTelemetry object
*/
constructor(name?: string, url?: string, durationMs?: number, properties?: any, measurements?: any);
}
class PageViewPerformance extends AI.PageViewPerfData implements Microsoft.ApplicationInsights.ISerializable {
static envelopeType: string;
static dataType: string;
aiDataContract: {
ver: Microsoft.ApplicationInsights.FieldType;
name: Microsoft.ApplicationInsights.FieldType;
url: Microsoft.ApplicationInsights.FieldType;
duration: Microsoft.ApplicationInsights.FieldType;
perfTotal: Microsoft.ApplicationInsights.FieldType;
networkConnect: Microsoft.ApplicationInsights.FieldType;
sentRequest: Microsoft.ApplicationInsights.FieldType;
receivedResponse: Microsoft.ApplicationInsights.FieldType;
domProcessing: Microsoft.ApplicationInsights.FieldType;
properties: Microsoft.ApplicationInsights.FieldType;
measurements: Microsoft.ApplicationInsights.FieldType;
};
/**
* Field indicating whether this instance of PageViewPerformance is valid and should be sent
*/
private isValid;
/**
* Indicates whether this instance of PageViewPerformance is valid and should be sent
*/
getIsValid(): boolean;
private durationMs;
/**
* Gets the total duration (PLT) in milliseconds. Check getIsValid() before using this method.
*/
getDurationMs(): number;
/**
* Constructs a new instance of the PageEventTelemetry object
*/
constructor(name: string, url: string, unused: number, properties?: any, measurements?: any);
static getPerformanceTiming(): PerformanceTiming;
/**
* Returns true is window performance timing API is supported, false otherwise.
*/
static isPerformanceTimingSupported(): PerformanceTiming;
/**
* As page loads different parts of performance timing numbers get set. When all of them are set we can report it.
* Returns true if ready, false otherwise.
*/
static isPerformanceTimingDataReady(): boolean;
static getDuration(start: any, end: any): number;
}
class RemoteDependencyData extends AI.RemoteDependencyData implements Microsoft.ApplicationInsights.ISerializable {
static envelopeType: string;
static dataType: string;
aiDataContract: {
id: Microsoft.ApplicationInsights.FieldType;
ver: Microsoft.ApplicationInsights.FieldType;
name: Microsoft.ApplicationInsights.FieldType;
kind: Microsoft.ApplicationInsights.FieldType;
value: Microsoft.ApplicationInsights.FieldType;
count: Microsoft.ApplicationInsights.FieldType;
min: Microsoft.ApplicationInsights.FieldType;
max: Microsoft.ApplicationInsights.FieldType;
stdDev: Microsoft.ApplicationInsights.FieldType;
dependencyKind: Microsoft.ApplicationInsights.FieldType;
success: Microsoft.ApplicationInsights.FieldType;
async: Microsoft.ApplicationInsights.FieldType;
dependencySource: Microsoft.ApplicationInsights.FieldType;
commandName: Microsoft.ApplicationInsights.FieldType;
dependencyTypeName: Microsoft.ApplicationInsights.FieldType;
properties: Microsoft.ApplicationInsights.FieldType;
resultCode: Microsoft.ApplicationInsights.FieldType;
};
/**
* Constructs a new instance of the RemoteDependencyData object
*/
constructor(id: string, absoluteUrl: string, commandName: string, value: number, success: boolean, resultCode: number, method?: string);
private formatDependencyName(method, absoluteUrl);
}
class Trace extends AI.MessageData implements Microsoft.ApplicationInsights.ISerializable {
static envelopeType: string;
static dataType: string;
aiDataContract: {
ver: Microsoft.ApplicationInsights.FieldType;
message: Microsoft.ApplicationInsights.FieldType;
severityLevel: Microsoft.ApplicationInsights.FieldType;
measurements: Microsoft.ApplicationInsights.FieldType;
properties: Microsoft.ApplicationInsights.FieldType;
};
/**
* Constructs a new instance of the MetricTelemetry object
*/
constructor(message: string, properties?: Object);
}
}
declare module Microsoft.ApplicationInsights.Telemetry.Common {
class Base extends Microsoft.Telemetry.Base implements Microsoft.ApplicationInsights.ISerializable {
/**
* The data contract for serializing this object.
*/
aiDataContract: {};
}
class Data<TDomain> extends Microsoft.Telemetry.Data<TDomain> implements Microsoft.ApplicationInsights.ISerializable {
/**
* The data contract for serializing this object.
*/
aiDataContract: {
baseType: FieldType;
baseData: FieldType;
};
/**
* Constructs a new instance of telemetry data.
*/
constructor(type: string, data: TDomain);
}
class Envelope implements IEnvelope {
ver: number;
name: string;
time: string;
sampleRate: number;
seq: string;
iKey: string;
flags: number;
deviceId: string;
os: string;
osVer: string;
appId: string;
appVer: string;
userId: string;
tags: any;
data: Base;
/**
* The data contract for serializing this object.
*/
aiDataContract: any;
/**
* Constructs a new instance of telemetry data.
*/
constructor(data: Microsoft.Telemetry.Base, name: string);
}
class DataSanitizer {
static sanitizeKeyAndAddUniqueness(key: any, map: any): any;
static sanitizeKey(name: any): any;
static sanitizeString(value: any): any;
static sanitizeUrl(url: any): any;
static sanitizeMessage(message: any): any;
static sanitizeException(exception: any): any;
static sanitizeProperties(properties: any): any;
static sanitizeMeasurements(measurements: any): any;
static padNumber(num: any): string;
}
}
declare module Microsoft.ApplicationInsights {
interface IConfig {
instrumentationKey?: string;
endpointUrl?: string;
emitLineDelimitedJson?: boolean;
accountId?: string;
sessionRenewalMs?: number;
sessionExpirationMs?: number;
maxBatchSizeInBytes?: number;
maxBatchInterval?: number;
enableDebug?: boolean;
disableExceptionTracking?: boolean;
disableTelemetry?: boolean;
verboseLogging?: boolean;
diagnosticLogInterval?: number;
samplingPercentage?: number;
autoTrackPageVisitTime?: boolean;
disableAjaxTracking?: boolean;
overridePageViewDuration?: boolean;
maxAjaxCallsPerView?: number;
disableDataLossAnalysis?: boolean;
disableCorrelationHeaders?: boolean;
disableFlushOnBeforeUnload?: boolean;
enableSessionStorageBuffer?: boolean;
cookieDomain?: string;
url?: string;
}
/**
* Enum is used in aiDataContract to describe how fields are serialized.
* For instance: (Fieldtype.Required | FieldType.Array) will mark the field as required and indicate it's an array
*/
enum FieldType {
Default = 0,
Required = 1,
Array = 2,
Hidden = 4,
}
interface ISerializable {
/**
* The set of fields for a serializeable object.
* This defines the serialization order and a value of true/false
* for each field defines whether the field is required or not.
*/
aiDataContract: any;
}
interface IEnvelope extends ISerializable {
ver: number;
name: string;
time: string;
sampleRate: number;
seq: string;
iKey: string;
flags: number;
deviceId: string;
os: string;
osVer: string;
appId: string;
appVer: string;
userId: string;
tags: {
[name: string]: any;
};
}
interface ITelemetryContext {
/**
* The object describing a component tracked by this object.
*/
application: Context.IApplication;
/**
* The object describing a device tracked by this object.
*/
device: Context.IDevice;
/**
* The object describing internal settings.
*/
internal: Context.IInternal;
/**
* The object describing a location tracked by this object.
*/
location: Context.ILocation;
/**
* The object describing a operation tracked by this object.
*/
operation: Context.IOperation;
/**
* The object describing sampling settings.
*/
sample: Context.ISample;
/**
* The object describing a user tracked by this object.
*/
user: Context.IUser;
/**
* The object describing a session tracked by this object.
*/
session: Context.ISession;
/**
* Adds telemetry initializer to the collection. Telemetry initializers will be called one by one
* before telemetry item is pushed for sending and in the order they were added.
*/
addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean): any;
/**
* Tracks telemetry object.
*/
track(envelope: Microsoft.ApplicationInsights.IEnvelope): any;
}
interface IAppInsights {
config: IConfig;
context: ITelemetryContext;
queue: (() => void)[];
/**
* Starts timing how long the user views a page or other item. Call this when the page opens.
* This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes.
* @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
*/
startTrackPage(name?: string): any;
/**
* Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
stopTrackPage(name?: string, url?: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}): any;
/**
* Logs that a page or other item was viewed.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
* @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally.
*/
trackPageView(name?: string, url?: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}, duration?: number): any;
/**
* Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends.
* @param name A string that identifies this event uniquely within the document.
*/
startTrackEvent(name: string): any;
/**
* Log an extended event that you started timing with {@link startTrackEvent}.
* @param name The string you used to identify this event in startTrackEvent.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
stopTrackEvent(name: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}): any;
/**
* Log a user action or other occurrence.
* @param name A string to identify this event in the portal.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
trackEvent(name: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}): any;
/**
* Log an AJAX request
* @param id Event id
* @param absoluteUrl Full url
* @param pathName Leave this parameter blank
* @param totalTime Total time it took for AJAX request to complete
* @param success Whether AJAX request succeeded or failed
* @param resultCode Result code returned from AJAX call
* @param method HTTP verb that was used (GET, POST)
*/
trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any;
/**
* Log an exception you have caught.
* @param exception An Error from a catch clause, or the string error message.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
* @param severityLevel AI.SeverityLevel - severity level
*/
trackException(exception: Error, handledAt?: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}, severityLevel?: AI.SeverityLevel): any;
/**
* Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.
* To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the
* telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals.
* @param name A string that identifies the metric.
* @param average Number representing either a single measurement, or the average of several measurements.
* @param sampleCount The number of measurements represented by the average. Defaults to 1.
* @param min The smallest measurement in the sample. Defaults to the average.
* @param max The largest measurement in the sample. Defaults to the average.
*/
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: {
[name: string]: string;
}): any;
/**
* Log a diagnostic message.
* @param message A message string
* @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty.
*/
trackTrace(message: string, properties?: {
[name: string]: string;
}): any;
/**
* Immediately send all queued telemetry.
*/
flush(): any;
/**
* Sets the autheticated user id and the account id in this session.
* User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars.
*
* @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service.
* @param accountId {string} - An optional string to represent the account associated with the authenticated user.
*/
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any;
/**
* Clears the authenticated user id and the account id from the user context.
*/
clearAuthenticatedUserContext(): any;
downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void;
/**
* The custom error handler for Application Insights
* @param {string} message - The error message
* @param {string} url - The url where the error was raised
* @param {number} lineNumber - The line number where the error was raised
* @param {number} columnNumber - The column number for the line where the error was raised
* @param {Error} error - The Error object
*/
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any;
}
}
declare module 'applicationinsights-js' {
export let AppInsights: Microsoft.ApplicationInsights.IAppInsights;
}
declare var appInsights: Microsoft.ApplicationInsights.IAppInsights;
+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")
+162 -44
View File
@@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript v3.16
// Type definitions for ArcGIS API for JavaScript v3.17
// Project: http://js.arcgis.com
// Definitions by: Esri <http://www.esri.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -18,7 +18,6 @@ declare module "esri" {
import BasemapLayer = require("esri/dijit/BasemapLayer");
import Symbol = require("esri/symbols/Symbol");
import BookmarkItem = require("esri/dijit/BookmarkItem");
import Units = require("esri/units");
import Color = require("esri/Color");
import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase");
import PictureMarkerSymbol = require("esri/symbols/PictureMarkerSymbol");
@@ -45,6 +44,7 @@ declare module "esri" {
import QueryTask = require("esri/tasks/QueryTask");
import TextSymbol = require("esri/symbols/TextSymbol");
import StandardGeographyQueryTask = require("esri/tasks/geoenrichment/StandardGeographyQueryTask");
import WMSLayerInfo = require("esri/layers/WMSLayerInfo");
import WMTSLayerInfo = require("esri/layers/WMTSLayerInfo");
export interface AGSMouseEvent extends MouseEvent {
@@ -354,7 +354,7 @@ declare module "esri" {
/** Radius of the circle. */
radius?: number;
/** Unit of the radius. */
radiusUnit?: Units;
radiusUnit?: string;
}
export interface CircleOptions2 {
/** The center point of the circle. */
@@ -366,7 +366,7 @@ declare module "esri" {
/** The radius of the circle. */
radius?: number;
/** Unit of the radius. */
radiusUnit?: Units;
radiusUnit?: string;
}
export interface ClassedColorSliderOptions {
/** Data map containing renderer information. */
@@ -643,6 +643,8 @@ declare module "esri" {
minStops?: number;
/** When true, stops on the route are re-ordered to provide an optimal route. */
optimalRoute?: boolean;
/** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */
portalUrl?: string;
/** URL link to a custom print page. */
printPage?: string;
/** If available, this print task is used to display an overview map of the route on the directions print page (Added at v3.11). */
@@ -677,6 +679,8 @@ declare module "esri" {
showReturnToStartOption?: boolean;
/** Display the 'Show Reverse Stops' button. */
showReverseStopsButton?: boolean;
/** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */
showSaveButton?: boolean;
/** Highlight the route segment when a directions step is clicked. */
showSegmentHighlight?: boolean;
/** Display a popup with segment details when a direction step is clicked. */
@@ -911,6 +915,8 @@ declare module "esri" {
layer: FeatureLayer;
}
export interface FeatureTableOptions {
/** The number of features a service will try to fetch. */
batchCount?: number;
/** Object defining the date options specifically for formatting date and time editors. */
dateOptions?: any;
/** Sets the editing state for the FeatureTable. */
@@ -931,12 +937,18 @@ declare module "esri" {
menuFunctions?: any[];
/** Attribute fields to include in the FeatureTable. */
outFields?: string[];
/** Displays or hides the attachment column. */
showAttachments?: boolean;
/** Displays the data type of the field right under the field label. */
showDataTypes?: boolean;
/** Displays or hides total number of features and selected number of features in the grid header. */
showFeatureCount?: boolean;
/** Displays or hides the FeatureTable header. */
showGridHeader?: boolean;
/** Displays or hides 'Options' drop-down menu of the FeatureTable. */
showGridMenu?: boolean;
/** Displays or hides the 'Statistics' option in column menus for numeric fields. */
showStatistics?: boolean;
/** Enables an interaction between the map and the feature table. */
syncSelection?: boolean;
/** Enables pan/zoom to selected features on the map when the table in 'sync selection' mode. */
@@ -1187,10 +1199,20 @@ declare module "esri" {
gdbVersion?: string;
}
export interface ImageServiceMeasureOptions {
/** The angular unit in which directions of line segments will be calculated. */
angularUnit?: string;
/** The area unit in which areas of polygons will be calculated. */
areaUnit?: string;
/** Defines whether to show the widget result in a popup or in the widget's result area when the widget has 'toolbar' layout. */
displayMeasureResultInPopup?: boolean;
/** Symbol to be used when drawing a polygon or extent. */
fillSymbol?: SimpleFillSymbol;
/** Image service layer with which the toolbar is associated. */
layer: ArcGISImageServiceLayer;
/** Defines the layout of the widget. */
layout?: string;
/** The linear unit in which height, length, or perimeters will be calculated. */
linearUnit?: string;
/** Symbol to be used when drawing a line. */
lineSymbol?: SimpleLineSymbol;
/** Map instance with which the toolbar is associate. */
@@ -1402,9 +1424,9 @@ declare module "esri" {
/** Flag for showing full list of units in the Location tool. */
advancedLocationUnits?: boolean;
/** The default area unit for the measure area tool. */
defaultAreaUnit?: Units;
defaultAreaUnit?: string;
/** The default length unit for the measure distance tool. */
defaultLengthUnit?: Units;
defaultLengthUnit?: string;
/** Allows the user to immediately measure previously-created geometry on dijit creation. */
geometry?: Point | Polyline | Polygon;
/** Line symbol used to draw the lines for the measure line and measure distance tools. */
@@ -2190,6 +2212,28 @@ declare module "esri" {
/** The well-known ID of the spatial reference used by the WFSLayer. */
wkid?: string;
}
export interface WMSLayerInfoOptions {
/** All the bounding extents defined for this layer. */
allExtents?: Extent[];
/** A description of the WMS layer. */
description?: string;
/** The extent of the WMS Layer. */
extent?: Extent;
/** The URL to the legend image. */
legendURL?: string;
/** The name of the WMS layer. */
name: string;
/** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats. */
queryable?: boolean;
/** Indicates if this layer should be included in the popup. */
showPopup?: boolean;
/** All the spatial references defined for this layer. */
spatialReferences?: SpatialReference[];
/** WMSLayerInfos of the layer's sub layers. */
subLayers?: WMSLayerInfo[];
/** The title of the WMS layer. */
title?: string;
}
export interface WMSLayerOptions {
/** Specify the map image format, valid options are png,jpg,bmp,gif,svg. */
format?: string;
@@ -3732,6 +3776,8 @@ declare module "esri/dijit/Directions" {
maxStopsReached: boolean;
/** Read-only: The graphic for the calculated route. */
mergedRouteGraphic: Graphic;
/** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */
portalUrl: string;
/** Routing parameters for the widget. */
routeParams: RouteParameters;
/** Routing task for the widget. */
@@ -3744,6 +3790,8 @@ declare module "esri/dijit/Directions" {
showClearButton: boolean;
/** If true, the toggle button group allowing user to choose between Miles and Kilometers is shown. */
showMilesKilometersOption: boolean;
/** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */
showSaveButton: boolean;
/** If true, and supported by the service, then two toggle button groups are shown: one to allow user to choose between driving a car, a truck, or walking, and one more group to choose between fastest or shortest routes. */
showTravelModesOption: boolean;
/** An array of graphics that define the stop locations along the route. */
@@ -3792,6 +3840,11 @@ declare module "esri/dijit/Directions" {
* @param index The index of the route segment to highlight.
*/
highlightSegment(index: number): void;
/**
* Loads a stored route layer from either ArcGIS Online or Portal
* @param itemId The itemId of the stored route layer from either ArcGIS Online or Portal.
*/
loadRoute(itemId: string): any;
/**
* Remove the stop at the specified index.
* @param index The index of the stop to remove.
@@ -3801,6 +3854,16 @@ declare module "esri/dijit/Directions" {
removeStops(): any;
/** Resets the directions widget removing any directions, stops and map graphics. */
reset(): any;
/**
* Specify the language used for the directions.
* @param locale The locale used for the directions.
*/
setDirectionsLanguage(locale: string): any;
/**
* Specify the length units used for the directions widget.
* @param units The length units used for the directions widget.
*/
setDirectionsLengthUnits(units: string): any;
/**
* If widget runs with Travel Modes enabled, call this method to switch to particular Travel mode programmatically.
* @param travelModeName Travel mode.
@@ -3843,10 +3906,16 @@ declare module "esri/dijit/Directions" {
on(type: "directions-finish", listener: (event: { result: RouteResult; target: Directions }) => void): esri.Handle;
/** Fires when the route services starts to calculate the route. */
on(type: "directions-start", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires after a user clicks the Save or Save as New button and subsequently does not have permission to create an item in ArcGIS Online or Portal. */
on(type: "feature-collection-created", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires when the directions widget has fully loaded. */
on(type: "load", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires when the widget starts or stops listening for map clicks. */
on(type: "map-click-active", listener: (event: { mapClickActive: boolean; target: Directions }) => void): esri.Handle;
/** Fires after a user clicks the Save or Save as New button for the first time in order to store a new route in either ArcGIS Online or Portal. */
on(type: "route-item-created", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires when a existing route layer item is successfully updated in ArcGIS Online or Portal after user clicks the Save button. */
on(type: "route-item-updated", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fired when you hover over a route segment in the directions display. */
on(type: "segment-highlight", listener: (event: { graphic: Graphic; target: Directions }) => void): esri.Handle;
/** Fires when a route segment is selected in the directions display. */
@@ -3901,6 +3970,8 @@ declare module "esri/dijit/FeatureTable" {
/** Creates an instance of the FeatureTable widget within the provided DOM node. */
class FeatureTable {
/** The number of features a service will try to fetch. */
batchCount: number;
/** Read-only: A reference to the column objects and their parameters. */
columns: any[];
/** Read-only: Reference to the dataStore used by the dGrid. */
@@ -3909,6 +3980,8 @@ declare module "esri/dijit/FeatureTable" {
dateOptions: any;
/** Sets the editing state for the FeatureTable. */
editable: boolean;
/** Event trigger(s) used to display editing interface for an individual cell. */
editOn: string | any;
/** Read-only: Number of records displayed in FeatureTable. */
featureCount: number;
/** The featureLayer that the table is associated with. */
@@ -3937,12 +4010,18 @@ declare module "esri/dijit/FeatureTable" {
selectedRowIds: number[];
/** Read-only: Each element in the array is an object that contains name-value pair of fields and field values associated with the selected rows. */
selectedRows: any[];
/** Displays the data type of the field right under the field label in the column header. */
/** Displays or hides the attachment column. */
showAttachments: boolean;
/** Displays or hides the data type of the field right under the field label in the column header. */
showDataTypes: boolean;
/** Displays or hides total number of features and selected number of features in the grid header. */
showFeatureCount: boolean;
/** Displays or hides the FeatureTable header. */
showGridHeader: boolean;
/** Displays or hides 'Options' drop-down menu of the FeatureTable. */
showGridMenu: boolean;
/** Displays or hides the 'Statistics' option in column menus for numeric fields. */
showStatistics: boolean;
/** Enables an interaction between the map and the feature table. */
syncSelection: boolean;
/** Enables pans to selected features on the map when the table in 'sync selection' mode. */
@@ -3953,6 +4032,29 @@ declare module "esri/dijit/FeatureTable" {
* @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into.
*/
constructor(params: esri.FeatureTableOptions, srcNodeRef: Node | string);
/** Removes all current selections including subsets from filterSelectedRecords(). */
clearSelection(): void;
/** Destroys the FeatureTable widget. */
destroy(): void;
/**
* Allows users to see the sub-set of currently selected records (uses dGrid.query).
* @param toggle When true only a subset of currently selected features will be displayed in the FeatureTable.
*/
filterSelectedRecords(toggle: boolean): void;
/**
* Queries and gets selected features from the FeatureLayer instead of the store.
* @param id Array of row ids
*/
getFeatureDataById(id: number[]): any;
/**
* Gets row object by the row ID.
* @param id row ID
*/
getRowDataById(id: number): any;
/** Refreshes the data in the grid. */
refresh(): void;
/** Resizes the grid's container. */
resize(): void;
/** Finalizes the creation of the widget. */
startup(): void;
/** Fires when the grid column is resized. */
@@ -4286,8 +4388,13 @@ declare module "esri/dijit/ImageServiceMeasure" {
/**
* Creates an instance of the ImageServiceMeasure widget.
* @param params An Object containing constructor options.
* @param srcNode Reference or id of the HTML element where the widget should be rendered.
*/
constructor(params: esri.ImageServiceMeasureOptions);
constructor(params: esri.ImageServiceMeasureOptions, srcNode: Node | string);
/** Destroys the ImageServiceMeasure widget. */
destroy(): void;
/** Finalizes the creation of the widget. */
startup(): void;
}
export = ImageServiceMeasure;
}
@@ -4528,9 +4635,14 @@ declare module "esri/dijit/LayerSwipe" {
declare module "esri/dijit/Legend" {
import esri = require("esri");
import Map = require("esri/map");
/** The legend dijit displays a label and symbol for some or all of the layers in the map. */
class Legend {
/** Specify a subset of the layers in the map to display in the legend. */
layerInfos: any[];
/** Reference to the map. */
map: Map;
/**
* Creates a new Legend dijit.
* @param params Parameters used to configure the dijit.
@@ -4555,7 +4667,7 @@ declare module "esri/dijit/LocateButton" {
import Symbol = require("esri/symbols/Symbol");
import Graphic = require("esri/graphic");
/** LocateButton provides a simple button to locate and zoom to the users current location. */
/** LocateButton provides a simple button to locate and zoom to the user's location. */
class LocateButton {
/** Centers the map to the location when a new position is returned. */
centerAt: boolean;
@@ -6767,7 +6879,7 @@ declare module "esri/dijit/editing/Add" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Add operations when editing. */
class Add extends OperationBase {
/**
* Create a new Add operation.
@@ -6810,7 +6922,7 @@ declare module "esri/dijit/editing/Cut" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Cut operations when editing. */
class Cut extends OperationBase {
/**
* Create a new Cut operation.
@@ -6829,7 +6941,7 @@ declare module "esri/dijit/editing/Delete" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Delete operations when editing. */
class Delete extends OperationBase {
/**
* Create a new Delete operation.
@@ -6929,7 +7041,7 @@ declare module "esri/dijit/editing/Union" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Union operations when editing. */
class Union extends OperationBase {
/**
* Create a new Union operation.
@@ -6948,7 +7060,7 @@ declare module "esri/dijit/editing/Update" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Update operations when editing. */
class Update extends OperationBase {
/**
* Create a new Update operation.
@@ -8353,8 +8465,9 @@ declare module "esri/geometry/webMercatorUtils" {
/**
* Converts geometry from Web Mercator units to geographic units.
* @param geometry The geometry to convert.
* @param isLinear Indicates whether to work with linear values, i.e., do not normalize.
*/
webMercatorToGeographic(geometry: Geometry): Geometry;
webMercatorToGeographic(geometry: Geometry, isLinear?: boolean): Geometry;
/**
* Translates the given Web Mercator coordinates to Longitude and Latitude.
* @param x The x coordinate value to convert.
@@ -10809,8 +10922,6 @@ declare module "esri/layers/VectorTileLayer" {
initialExtent: Extent;
/** The spatial reference of the layer. */
spatialReference: SpatialReference;
/** The style object of the service with fully qualified URLs for glyphs and sprite. */
style: any;
/** Contains information about the tiling scheme for the layer. */
tileInfo: TileInfo;
/** The URL to the vector tile service or style JSON that will be used to draw the layer. */
@@ -10821,6 +10932,8 @@ declare module "esri/layers/VectorTileLayer" {
* @param options Optional parameters.
*/
constructor(url: string | any, options?: esri.VectorTileLayerOptions);
/** Returns an object that contains the current style information for the layer. */
getStyle(): any;
/**
* Changes the style properties used to render the layers.
* @param styleUrl A url to a JSON file containing the stylesheet information to render the layer.
@@ -10835,14 +10948,15 @@ declare module "esri/layers/VectorTileLayer" {
declare module "esri/layers/WFSLayer" {
import esri = require("esri");
import GraphicsLayer = require("esri/layers/GraphicsLayer");
import Field = require("esri/layers/Field");
import Extent = require("esri/geometry/Extent");
import Graphic = require("esri/graphic");
import InfoTemplate = require("esri/InfoTemplate");
import Renderer = require("esri/renderers/Renderer");
/** (Currently in beta) A layer for OGC Web Feature Services (WFS). */
class WFSLayer {
/** (Currently in beta) A layer for OGC Web Feature Services (WFS). */
class WFSLayer extends GraphicsLayer {
/** An array of fields in the layer. */
fields: Field[];
/** The full extent of the layer. */
@@ -10864,17 +10978,11 @@ declare module "esri/layers/WFSLayer" {
* @param options See options table below for full descriptions of the properties needed for this object.
*/
constructor(options: esri.WFSLayerOptions);
/** Creates the getFeature parameter based on the version, nsLayerName, nsGeometryFieldName, mode, wkid, inverseFilter, maxFeatures constructor parameters. */
buildRequest(): string;
/**
* Gets the WFS layer capabilities.
* @param callback An array of WFS layers in JSON format.
* Creates a WFSLayer using the provided JSON object.
* @param json The input JSON.
*/
getCapabilities(callback?: Function): void;
/** Performs the getFeature request. */
getFeature(): void;
/** Returns a JSON Object containing all of the WFS parameters. */
getWFSParameters(): any;
fromJson(json: Object): void;
/** Redraws all the graphics in the layer. */
redraw(): void;
/** Refreshes the features in the WFS layer. */
@@ -10885,8 +10993,8 @@ declare module "esri/layers/WFSLayer" {
setPointSymbol(): void;
/** Sets the default polygon symbol to be used if no renderer is specified. */
setPolygonSymbol(): void;
/** Sets the WFS parameters using the provided JSON Object. */
setWFSParameters(): void;
/** Converts the WFSLayer instance to a JSON object. */
toJson(): any;
}
export = WFSLayer;
}
@@ -10952,6 +11060,7 @@ declare module "esri/layers/WMSLayer" {
}
declare module "esri/layers/WMSLayerInfo" {
import esri = require("esri");
import Extent = require("esri/geometry/Extent");
/** The WMSLayerInfo class defines and provides information about layers in a WMS service. */
@@ -10966,6 +11075,10 @@ declare module "esri/layers/WMSLayerInfo" {
legendURL: string;
/** The layer name. */
name: string;
/** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats */
queryable: boolean;
/** Indicates if this layer should be included in the popup. */
showPopup: boolean;
/** An array of WKIDs of all spatial references defined for the layer. */
spatialReferences: number[];
/** WMSLayerInfos of the layer's sub layers. */
@@ -10974,9 +11087,9 @@ declare module "esri/layers/WMSLayerInfo" {
title: string;
/**
* Creates a new WMSLayerInfo object.
* @param layer WMSLayerInfo layer object.
* @param options See options list for parameters.
*/
constructor(layer: any);
constructor(options?: esri.WMSLayerInfoOptions);
}
export = WMSLayerInfo;
}
@@ -11584,7 +11697,7 @@ declare module "esri/opsdashboard/DataSourceProxy" {
displayFieldName: string;
/** Read-only: The collection of fields. */
fields: Field[];
/** The geometry type. */
/** Read-only: The geometry type. */
geometryType: string;
/** Read-only: The id of the data source. */
id: string;
@@ -11611,8 +11724,8 @@ declare module "esri/opsdashboard/DataSourceProxy" {
executeQuery(query: Query): any;
/** An object that contains service level metadata about whether or not the layer supports queries using statistics, order by fields, DISTINCT, pagination, query with distance, and returning queries with extents. */
getAdvancedQueryCapabilities(): any;
/** Retrieve the associated data source that supports selection. */
getAssociatedSelectionDataSourceProxy(): any;
/** Retrieve the associated id of the data source that supports selection. */
getAssociatedSelectionDataSourceId(): any;
/** Get the associated popupInfo for the data source if any available. */
getPopupInfo(): any;
/** Get the associated render object for the data source if any available. */
@@ -11666,12 +11779,17 @@ declare module "esri/opsdashboard/ExtensionBase" {
static POLYLINE: any;
/** Read-only: Indicates if the host application is the Windows Operations Dashboard. */
isNative: boolean;
/** Read Only: It will list all of the Portal helper services. */
portalHelperServices: string;
/** Read-only: The URL to the ArcGIS.com site or in-house portal that you are currently signed in to. */
portalUrl: string;
/** Get the collection of data sources from the host application. */
getDataSourceProxies(): any;
/** Get the data source corresponding to the data source id from the host application. */
getDataSourceProxy(): any;
/**
* Get the data source corresponding to the data source id from the host application.
* @param dataSourceId The data source id
*/
getDataSourceProxy(dataSourceId: string): any;
/** Get the collection of map widgets from the host application. */
getMapWidgetProxies(): any;
/**
@@ -11791,7 +11909,7 @@ declare module "esri/opsdashboard/GraphicsLayerProxy" {
minScale: number;
/** Read-only: The current host graphics layer opacity ratio. */
opacity: number;
/** The current renderer used by the host graphics layer. */
/** Read-only: The current renderer used by the host graphics layer. */
renderer: Renderer;
/** Read-only: The current host graphics layer visibility. */
visible: boolean;
@@ -11928,8 +12046,6 @@ declare module "esri/opsdashboard/MapWidgetProxy" {
destroyGraphicsLayerProxy(graphicsLayerProxy: GraphicsLayerProxy): void;
/** Gets the current host map extent. */
getMapExtent(): any;
/** Called by the host application when the extent of the host map has changed. */
mapExtentChanged(): void;
/**
* Pans the map to a new location.
* @param mapPoint A new location with the same spatial reference as the host map.
@@ -14088,7 +14204,7 @@ declare module "esri/tasks/FindTask" {
url: string;
/**
* Creates a new FindTask object.
* @param url URL to the ArcGIS Server REST resource that represents a layer in a service.
* @param url URL to the ArcGIS Server REST resource that represents a map service.
* @param options Optional parameters.
*/
constructor(url: string, options?: esri.FindTaskOptions);
@@ -15343,6 +15459,8 @@ declare module "esri/tasks/RouteParameters" {
startTimeIsUTC: boolean;
/** The set of stops loaded as network locations during analysis. */
stops: any;
/** If true , the TimeWindowStart and TimeWindowEnd attributes of a stop are in UTC time (milliseconds). */
timeWindowsAreUTC: boolean;
/** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */
travelMode: any;
/** If true, the hierarchy attribute for the network should be used in analysis. */
@@ -16696,7 +16814,7 @@ declare module "esri/tasks/query" {
static SPATIAL_REL_TOUCHES: any;
/** The feature from feature class 1 is completely enclosed by the feature from feature class 2. */
static SPATIAL_REL_WITHIN: any;
/** Distance to buffer input geometry. */
/** Buffer distance for input geometries. */
distance: number;
/** The geometry to apply to the spatial filter. */
geometry: Geometry;
@@ -16738,7 +16856,7 @@ declare module "esri/tasks/query" {
text: string;
/** Specify a time extent for the query. */
timeExtent: TimeExtent;
/** Distance unit. */
/** The unit for calculating the buffer distance. */
units: string;
/** A where clause for the query. */
where: string;
@@ -17055,7 +17173,7 @@ declare module "esri/toolbars/navigation" {
* @param symbol The SimpleFillSymbol used for the rubber band zoom.
*/
setZoomSymbol(symbol: Symbol): void;
/** Zoom to full extent of base layer. */
/** Zoom to initial extent of base layer. */
zoomToFullExtent(): void;
/** Zoom to next extent in extent history. */
zoomToNextExtent(): void;
+1 -1
View File
@@ -24,7 +24,7 @@ declare module "archiver" {
interface Archiver extends STREAM.Transform {
pipe(writeStream: FS.WriteStream): void;
append(readStream: FS.ReadStream, name: nameInterface): void;
append(source: FS.ReadStream | Buffer | string, name: nameInterface): void;
finalize(): void;
}
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="argv.d.ts" />
import argv = require('argv');
argv.version( 'v1.0' );
argv.info( 'Special script info' );
argv.clear()
.option({
name: 'option',
short: 'o',
type: 'string',
description: 'Defines an option for your script',
example: "'script --opiton=value' or 'script -o value'"
})
.run([ '--option=123', '-o', '123' ]);
argv.run();
argv.help();
+59
View File
@@ -0,0 +1,59 @@
// Type definitions for argv
// Project: https://www.npmjs.com/package/argv
// Definitions by: Hookclaw <https://github.com/hookclaw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "argv" {
// argv module
type args = {
targets:string[],
options:{[key:string]:any}
};
type helpOption = {
name: string,
type: string,
short?: string,
description?: string,
example?: string
};
type module = {
mod: string,
description: string,
options: {[key:string]:helpOption}
};
type typeFunction = (value:any, ...arglist:any[]) => any;
type argv = {
// Runs the arguments parser
run: ( argv?:string[] ) => args,
// Adding options to definitions list
option: ( mod:helpOption|helpOption[] ) => argv,
// Creating module
mod: ( object:module|module[] ) => argv,
// Creates custom type function
type: ( name:string|{[key:string]:typeFunction}, callback?:typeFunction ) => any,
// Setting version number, and auto setting version option
version: ( v:string ) => argv,
// Description setup
info: ( mod:string, description?:module ) => argv,
// Cleans out current options
clear: () => argv,
// Prints out the help doc
help: ( mod?:string ) => argv
};
var argv:argv;
export = argv;
}
@@ -0,0 +1,10 @@
/// <reference path="./array-find-index.d.ts" />
import * as arrayFindIndex from 'array-find-index';
arrayFindIndex(['rainbow', 'unicorn', 'pony'], x => x === 'unicorn');
const ctx = {foo: 'rainbow'};
arrayFindIndex(['rainbow', 'unicorn', 'pony'], function (x) {
return x === this.foo;
}, ctx);
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for array-find-index
// Project: https://github.com/sindresorhus/array-find-index
// Definitions by: Sam Verschueren <https://github.com/samverschueren>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "array-find-index" {
type Predicate = (element: any, index: number, array: any[]) => boolean;
function arrayFindIndex(arr: any[], predicate: Predicate): number;
function arrayFindIndex(arr: any[], predicate: Predicate, ctx: any): number;
namespace arrayFindIndex {}
export = arrayFindIndex;
}
+1 -7
View File
@@ -378,6 +378,7 @@ async.auto({
async.retry(3, function (callback, results) { }, function (err, result) { });
async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { });
async.retry({ times: 3, interval: (retryCount) => { return 200 * retryCount; } }, function (callback, results) { }, function (err, result) { });
async.parallel([
@@ -391,13 +392,6 @@ function (results) {
]);
});
var sys;
var iterator = async.iterator([
function () { sys.p('one'); },
function () { sys.p('two'); },
function () { sys.p('three'); }
]);
async.parallel([
async.apply(fs.writeFile, 'testfile1', 'test1'),
async.apply(fs.writeFile, 'testfile2', 'test2'),
+61 -21
View File
@@ -1,4 +1,4 @@
// Type definitions for Async 1.4.2
// Type definitions for Async 2.0.1
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Arseniy Maximov <https://github.com/kern0>, Joe Herman <https://github.com/Penryn>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -12,10 +12,10 @@ interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): v
interface AsyncFunction<T> { (callback: (err?: Error, result?: T) => void): void; }
interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number|string, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (truthValue: boolean) => void): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (err: string, truthValue: boolean) => void): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
@@ -37,6 +37,13 @@ interface AsyncQueue<T> {
pause(): void
resume(): void;
kill(): void;
workersList(): {
data: T,
callback: Function
}[];
error(error: Error, data: any): void;
unsaturated(): void;
buffer: number;
}
interface AsyncPriorityQueue<T> {
@@ -54,6 +61,14 @@ interface AsyncPriorityQueue<T> {
pause(): void;
resume(): void;
kill(): void;
workersList(): {
data: T,
priority: number,
callback: Function
}[];
error(error: Error, data: any): void;
unsaturated(): void;
buffer: number;
}
interface AsyncCargo {
@@ -85,26 +100,35 @@ interface Async {
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
mapValuesLimit<T, R>(obj: {[name: string]: T}, limit: number, iteratee: (value: string, key: T, callback: AsyncResultCallback<R>) => void, callback: AsyncResultCallback<R[]>): void;
mapValues<T, R>(obj: {[name: string]: T}, iteratee: (value: string, key: T, callback: AsyncResultCallback<R>) => void, callback: AsyncResultCallback<R[]>): void;
mapValuesSeries: typeof async.mapValues;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
select<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
filterSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
selectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
reject<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
rejectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultArrayCallback<T>): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
find: typeof async.detect;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
findSeries: typeof async.detectSeries;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: AsyncResultCallback<T>): any;
findLimit: typeof async.detectLimit;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
anyLimit: typeof async.someLimit;
someSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
anySeries: typeof async.someSeries;
any<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
every<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
everyLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
@@ -134,18 +158,35 @@ interface Async {
queue<T>(worker: AsyncWorker<T>, concurrency?: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo;
auto(tasks: any, callback?: (error: Error, results: any) => void): void;
auto(tasks: any, concurrency?: number, callback?: (error: Error, results: any) => void): void;
autoInject(tasks: any, callback?: (error: Error, results: any) => void): void;
retry<T>(opts: number, task: (callback : AsyncResultCallback<T>, results: any) => void, callback: (error: Error, results: any) => void): void;
retry<T>(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: (error: Error, results: any) => void): void;
iterator(tasks: Function[]): Function;
retry<T>(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: (error: Error, results: any) => void): void;
retryable<T>(opts: number | {times: number, interval: number}, task: AsyncFunction<T>): AsyncFunction<T>;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function): void;
setImmediate(callback: Function): void;
nextTick(callback: Function, ...args: any[]): void;
setImmediate: typeof async.nextTick;
allLimit<T>(arr: T[], limit: number, iteratee: AsyncBooleanIterator<T>, cb?: (result: boolean) => any) : any;
everySeries<T>(arr: T[], iteratee: AsyncBooleanIterator<T>, cb?: (result: boolean) => any) : any
allSeries: typeof async.everySeries;
reflect<T>(fn: AsyncFunction<T>) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void;
reflectAll<T>(tasks: AsyncFunction<T>[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[];
timeout<T>(fn: AsyncFunction<T>, milliseconds: number, info: any): AsyncFunction<T>;
times<T> (n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesSeries<T>(n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesLimit<T>(n: number, limit: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
transform<T, R>(arr: T[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void;
transform<T, R>(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void;
transform<T, R>(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void;
transform<T, R>(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void;
race<T>(tasks: (AsyncFunction<T>)[], callback: AsyncResultCallback<T>) : void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
unmemoize(fn: Function): Function;
@@ -155,7 +196,6 @@ interface Async {
wrapSync(fn: Function): Function;
log(fn: Function, ...arguments: any[]): void;
dir(fn: Function, ...arguments: any[]): void;
noConflict(): Async;
}
declare var async: Async;
+4 -3
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;
@@ -102,5 +102,6 @@ declare namespace Atmosphere {
}
declare var atmosphere:Atmosphere.Atmosphere;
declare module 'atmosphere' {
export = atmosphere;
}
+104 -75
View File
@@ -456,82 +456,111 @@ declare namespace AtomCore {
// TBD
}
interface ISelection /* extends Theorist.Model */ {
cursor:ICursor;
marker:IDisplayBufferMarker;
editor:IEditor;
initialScreenRange:any;
wordwise:boolean;
needsAutoscroll:boolean;
retainSelection:boolean;
subscriptionCounts:any;
interface ISelection {
// https://atom.io/docs/api/v1.7.3/Selection
destroy():any;
finalize():any;
clearAutoscroll():any;
isEmpty():boolean;
isReversed():boolean;
isSingleScreenLine():boolean;
getScreenRange():TextBuffer.IRange;
setScreenRange(screenRange:any, options:any):any;
getBufferRange():TextBuffer.IRange;
setBufferRange(bufferRange:any, options:any):any;
getBufferRowRange():number[];
autoscroll():void;
getText():string;
clear():boolean;
selectWord():TextBuffer.IRange;
expandOverWord():any;
selectLine(row?:any):TextBuffer.IRange;
expandOverLine():boolean;
selectToScreenPosition(position:any):any;
selectToBufferPosition(position:any):any;
selectRight():boolean;
selectLeft():boolean;
selectUp(rowCount?:any):boolean;
selectDown(rowCount?:any):boolean;
selectToTop():any;
selectToBottom():any;
selectAll():any;
selectToBeginningOfLine():any;
selectToFirstCharacterOfLine():any;
selectToEndOfLine():any;
selectToBeginningOfWord():any;
selectToEndOfWord():any;
selectToBeginningOfNextWord():any;
selectToPreviousWordBoundary():any;
selectToNextWordBoundary():any;
addSelectionBelow():any;
getGoalBufferRange():any;
addSelectionAbove():any[];
insertText(text:string, options?:any):any;
normalizeIndents(text:string, indentBasis:number):any;
indent(_arg?:any):any;
indentSelectedRows():TextBuffer.IRange[];
setIndentationForLine(line:string, indentLevel:number):any;
backspace():any;
backspaceToBeginningOfWord():any;
backspaceToBeginningOfLine():any;
delete():any;
deleteToEndOfWord():any;
deleteSelectedText():any;
deleteLine():any;
joinLines():any;
outdentSelectedRows():any[];
autoIndentSelectedRows():any;
toggleLineComments():any;
cutToEndOfLine(maintainClipboard:any):any;
cut(maintainClipboard:any):any;
copy(maintainClipboard:any):any;
fold():any;
modifySelection(fn:()=>any):any;
plantTail():any;
intersectsBufferRange(bufferRange:any):any;
intersectsWith(otherSelection:any):any;
merge(otherSelection:any, options:any):any;
compare(otherSelection:any):any;
getRegionRects():any[];
screenRangeChanged():any;
// Event Subscription
onDidChangeRange(callback: (event: {
oldBufferRange: TextBuffer.IRange;
oldScreenRange: TextBuffer.IRange;
newBufferRange: TextBuffer.IRange;
newScreenRange: TextBuffer.IRange;
selection: ISelection;
}) => {}): Disposable;
onDidDestroy(callback: () => {}): Disposable;
// Managing the selection range
getScreenRange(): TextBuffer.IRange;
setScreenRange(screenRange: TextBuffer.IRange, options?: {
preserveFolds?: boolean;
autoscroll?: boolean;
}): void;
getBufferRange(): TextBuffer.IRange;
setBufferRange(bufferRange: TextBuffer.IRange, options?: {
preserveFolds?: boolean;
autoscroll?: boolean;
}): void;
getBufferRowRange(): [number];
// Info about the selection
isEmpty(): boolean;
isReversed(): boolean;
isSingleScreenLine(): boolean;
getText(): string;
intersectsBufferRange(bufferRange: TextBuffer.IRange): boolean;
intersectsWith(otherSelection: ISelection): boolean;
// Modifying the selected range
clear(options?: {autoscroll?: boolean}): void;
selectToScreenPosition(position: any): void;
selectToBufferPosition(position: any): void;
selectRight(columnCount?: number): void;
selectLeft(columnCount?: number): void;
selectUp(rowCount: number): void;
selectDown(rowCount: number): void;
selectToTop(): void;
selectToBottom(): void;
selectAll(): void;
selectToBeginningOfLine(): void;
selectToFirstCharacterOfLine(): void;
selectToEndOfLine(): void;
selectToEndOfBufferLine(): void;
selectToBeginningOfWord(): void;
selectToEndOfWord(): void;
selectToBeginningOfNextWord(): void;
selectToPreviousWordBoundary(): void;
selectToNextWordBoundary(): void;
selectToPreviousSubwordBoundary(): void;
selectToNextSubwordBoundary(): void;
selectToBeginningOfNextParagraph(): void;
selectToBeginningOfPreviousParagraph(): void;
selectWord(): TextBuffer.IRange;
expandOverWord(): void;
selectLine(row?: number): void;
expandOverLine(): void;
// Modifying the selected text
insertText(text: string, options?: {
select: boolean;
autoIndent: boolean;
autoIndentNewline: boolean;
autoDecreaseIndent: boolean;
normalizeLineEndings?: boolean;
undo?: 'skip';
}): void;
backspace(): void;
deleteToPreviousWordBoundary(): void;
deleteToNextWordBoundary(): void;
deleteToBeginningOfWord(): void;
deleteToBeginningOfLine(): void;
delete(): void;
deleteToEndOfLine(): void;
deleteToEndOfWord(): void;
deleteToBeginningOfSubword(): void;
deleteToEndOfSubword(): void;
deleteSelectedText(): void;
deleteLine(): void;
joinLines(): void;
outdentSelectedRows(): void;
autoIndentSelectedRows(): void;
toggleLineComments(): void;
cutToEndOfLine(): void;
cutToEndOfBufferLine(): void;
cut(maintainClipboard?: boolean, fullLine?: boolean): void;
copy(maintainClipboard?: boolean, fullLine?: boolean): void;
fold(): void;
indentSelectedRows(): void;
// Managing multiple selections
addSelectionBelow(): void;
addSelectionAbove(): void;
merge(otherSelection: ISelection, options?: {
preserveFolds?: boolean;
autoscroll?: boolean;
}): void;
// Comparing to other selections
compare(otherSelection: ISelection): any;
}
interface IDecorationParams {
+160 -8
View File
@@ -1,13 +1,165 @@
/// <reference path="../auth0/auth0.d.ts" />
/// <reference path="auth0.lock.d.ts" />
var lock: Auth0LockStatic = new Auth0Lock("dsa7d77dsa7d7", "mine.auth0.com");
const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID";
const DOMAIN = "YOUR_DOMAIN_AT.auth0.com";
lock.showSignin({
connections: ["facebook", "google-oauth2", "twitter", "Username-Password-Authentication"],
icon: "https://contoso.com/logo-32.png",
socialBigButtons: true
},
() => {
// The Auth0 Widget is now loaded.
var lock: Auth0LockStatic = new Auth0Lock(CLIENT_ID, DOMAIN);
lock.show();
lock.hide();
lock.logout(() => {});
// The examples below are lifted from auth0-lock documentation on Github
// "on" event-driven example
lock.on("authenticated", function(authResult : any) {
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
// Handle error
return;
}
localStorage.setItem("idToken", authResult.idToken);
localStorage.setItem("profile", JSON.stringify(profile));
});
});
// test theme
var themeOptions : Auth0LockConstructorOptions = {
theme: {
logo: "https://example.com/assets/logo.png",
primaryColor: "green"
}
};
new Auth0Lock(CLIENT_ID, DOMAIN, themeOptions);
// test authentication
var authOptions : Auth0LockConstructorOptions = {
auth: {
params: { state: "foo" },
redirect: true,
redirectUrl: "some url",
responseType: "token",
sso: true
}
};
new Auth0Lock(CLIENT_ID, DOMAIN, authOptions);
// test multi-variant example
var multiVariantOptions : Auth0LockConstructorOptions = {
container: "myContainer",
closable: false,
languageDictionary: {
signUpTerms: "I agree to the <a href='/terms' target='_new'>terms of service</a> ...",
title: "My Company",
},
autofocus: false
};
new Auth0Lock(CLIENT_ID, DOMAIN, multiVariantOptions);
// test text-field additional sign up field
var textFieldOptions : Auth0LockConstructorOptions = {
additionalSignUpFields: [{
name: "address",
placeholder: "enter your address",
// The following properties are optional
icon: "https://example.com/assests/address_icon.png",
prefill: "street 123",
validator: function(input : string) {
return {
valid: input.length >= 10,
hint: "Must have 10 or more chars" // optional
};
}
}]
};
new Auth0Lock(CLIENT_ID, DOMAIN, textFieldOptions);
// test select-field additional sign up field
var selectFieldOptions : Auth0LockConstructorOptions = {
additionalSignUpFields: [{
type: "select",
name: "location",
placeholder: "choose your location",
options: [
{value: "us", label: "United States"},
{value: "fr", label: "France"},
{value: "ar", label: "Argentina"}
],
// The following properties are optional
icon: "https://example.com/assests/location_icon.png",
prefill: "us"
}]
};
new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptions);
// test select-field additional sign up field with callbacks for
var selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = {
additionalSignUpFields: [{
type: "select",
name: "location",
placeholder: "choose your location",
options: function(cb) {
// obtain options, in case of error you call cb with the error in the
// first arg instead of null
let options = [
{value: "us", label: "United States"},
{value: "fr", label: "France"},
{value: "ar", label: "Argentina"}
];
cb(null, options);
},
icon: "https://example.com/assests/location_icon.png",
prefill: function(cb) {
// obtain prefill, in case of error you call cb with the error in the
// first arg instead of null
let prefill = "us";
cb(null, prefill);
}
}]
}
new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptionsWithCallbacks);
// test Avatar options
var avatarOptions : Auth0LockConstructorOptions = {
avatar: {
url: (email : string, cb : Auth0LockAvatarUrlCallback) => {
// obtain url for email, in case of error you call cb with the error in
// the first arg instead of null
let url = "url";
cb(null, url);
},
displayName: (email : string, cb : Auth0LockAvatarDisplayNameCallback) => {
// obtain displayName for email, in case of error you call cb with the
// error in the first arg instead of null
let displayName = "displayName";
cb(null, displayName);
}
}
};
new Auth0Lock(CLIENT_ID, DOMAIN, avatarOptions);
+98 -55
View File
@@ -1,10 +1,70 @@
// Type definitions for Auth0Widget.js
// Type definitions for auth0-lock v10.0.1
// Project: http://auth0.com
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions by: Brian Caruso <https://github.com/carusology>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../auth0/auth0.d.ts" />
interface Auth0LockAdditionalSignUpFieldOption {
value: string;
label: string;
}
type Auth0LockAdditionalSignUpFieldOptionsCallback =
(error: Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void;
type Auth0LockAdditionalSignUpFieldOptionsFunction =
(callback: Auth0LockAdditionalSignUpFieldOptionsCallback) => void;
type Auth0LockAdditionalSignUpFieldPrefillCallback =
(error: Auth0Error, prefill: string) => void;
type Auth0LockAdditionalSignUpFieldPrefillFunction =
(callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void;
interface Auth0LockAdditionalSignUpField {
icon?: string;
name: string;
options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction;
placeholder: string;
prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction;
type?: "select" | "text";
validator?: (input: string) => { valid: boolean; hint?: string };
}
type Auth0LockAvatarUrlCallback = (error: Auth0Error, url: string) => void;
type Auth0LockAvatarDisplayNameCallback = (error: Auth0Error, displayName: string) => void;
interface Auth0LockAvatarOptions {
url: (email: string, callback: Auth0LockAvatarUrlCallback) => void;
displayName: (email: string, callback: Auth0LockAvatarDisplayNameCallback) => void;
}
interface Auth0LockThemeOptions {
logo?: string;
primaryColor?: string;
}
// https://auth0.com/docs/libraries/lock/v10/sending-authentication-parameters
interface Auth0LockAuthParamsOptions {
access_token?: any;
connection_scopes?: any;
device?: any;
nonce?: any;
protocol?: any;
request_id?: any;
scope?: string;
state?: string;
}
interface Auth0LockAuthOptions {
params?: Auth0LockAuthParamsOptions;
redirect?: boolean;
redirectUrl?: string;
responseType?: string;
sso?: boolean;
}
interface Auth0LockPopupOptions {
width: number;
height: number;
@@ -12,68 +72,51 @@ interface Auth0LockPopupOptions {
top: number;
}
interface Auth0LockOptions {
authParams?: any;
callbackURL?: string;
connections?: string[];
container?: string;
closable?: boolean;
dict?: any;
defaultUserPasswordConnection?: string;
defaultADUsernameFromEmailPrefix?: boolean;
disableResetAction?: boolean;
disableSignupAction?: boolean;
focusInput?: boolean;
forceJSONP?: boolean;
gravatar?: boolean;
integratedWindowsLogin?: boolean;
icon?: string;
loginAfterSignup?: boolean;
popup?: boolean;
popupOptions?: Auth0LockPopupOptions;
rememberLastLogin?: boolean;
resetLink?: string;
responseType?: string;
signupLink?: string;
socialBigButtons?: boolean;
sso?: boolean;
theme?: string;
usernameStyle?: any;
}
interface Auth0LockConstructorOptions {
cdn?: string;
additionalSignUpFields?: Auth0LockAdditionalSignUpField[];
allowedConnections?: string[];
allowForgotPassword?: boolean;
allowLogin?: boolean;
allowSignUp?: boolean;
assetsUrl?: string;
useCordovaSocialPlugins?: boolean;
auth?: Auth0LockAuthOptions;
autoclose?: boolean;
autofocus?: boolean;
avatar?: Auth0LockAvatarOptions;
closable?: boolean;
container?: string;
defaultADUsernameFromEmailPrefix?: string;
defaultDatabaseConnection?: string;
defaultEnterpriseConnection?: string;
forgotPasswordLink?: string;
initialScreen?: "login" | "signUp" | "forgotPassword";
language?: string;
languageDictionary?: any;
loginAfterSignup?: boolean;
mustAcceptTerms?: boolean;
popupOptions?: Auth0LockPopupOptions;
prefill?: { email?: string, username?: string};
rememberLastLogin?: boolean;
signupLink?: string;
socialButtonStyle?: "big" | "small";
theme?: Auth0LockThemeOptions;
usernameStyle?: string;
}
interface Auth0LockStatic {
new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic;
getProfile(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void) : void;
show(): void;
show(options: Auth0LockOptions): void;
show(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void;
show(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void;
hide(): void;
logout(query: any): void;
showSignin(): void;
showSignin(options: Auth0LockOptions): void;
showSignin(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void;
showSignin(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void;
showSignup(): void;
showSignup(options: Auth0LockOptions): void;
showSignup(callback: (error?: Auth0Error) => void) : void;
showSignup(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void;
showReset(): void;
showReset(options: Auth0LockOptions): void;
showReset(callback: (error?: Auth0Error) => void) : void;
showReset(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void;
hide(callback: () => void): void;
logout(callback: () => void): void;
getClient(): Auth0Static;
on(event: "show", callback: () => void) : void;
on(event: "hide", callback: () => void) : void;
on(event: "unrecoverable_error", callback: (error: Auth0Error) => void) : void;
on(event: "authorization_error", callback: (error: Auth0Error) => void) : void;
on(event: "authenticated", callback: (authResult: any) => void) : void;
on(event: string, callback: (...args: any[]) => void) : void;
}
declare var Auth0Lock: Auth0LockStatic;
+3 -2
View File
@@ -45,7 +45,7 @@ declare namespace autobahn {
interface IInvocation {
caller?: number;
progress?: boolean;
progress?: (args : any[], kwargs : any) => void;
procedure: string;
}
@@ -163,6 +163,7 @@ declare namespace autobahn {
}
interface IPublishOptions {
acknowledge?: boolean;
exclude?: number[];
eligible?: number[];
disclose_me?: Boolean;
@@ -181,7 +182,7 @@ declare namespace autobahn {
open(): void;
close(reason: string, message: string): void;
close(reason?: string, message?: string): void;
onopen: (session: Session, details: any) => void;
onclose: (reason: string, details: any) => boolean;
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="autosize.d.ts" />
// from a NodeList
autosize(document.querySelectorAll('textarea'));
// from a single Node
autosize(document.querySelector('textarea'));
// from a single element
autosize(document.getElementById('my-textarea'));
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for jquery.autosize 3.0.7
// Project: http://www.jacklmoore.com/autosize/
// Definitions by: Aaron T. King <https://github.com/kingdango>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace autosize {
interface AutosizeStatic {
(el: Element): void;
(el: NodeList): void;
}
}
declare var autosize: autosize.AutosizeStatic;
declare module 'autosize' {
export = autosize;
}
+222
View File
@@ -0,0 +1,222 @@
/// <reference path="avoscloud-sdk.d.ts" />
import * as AV from 'avoscloud-sdk'
// 创建一个新的 TestObject 对象
AV.initialize('uay57kigwe0b6f5n0e1d4z4xhydsml3dor24bzwvzr57wdap','kfgz7jjfsk55r5a8a3y4ttd3je1ko11bkibcikonk32oozww');
var TestObject = AV.Object.extend('TestObject');
function avobject_Test() {
var testObject = new TestObject();
testObject.set("testBoolean", false);
testObject.set("testInteger", 178);
testObject.set("testString", "leancloud");
testObject.set("testDate", new Date());
testObject.set("testArray", ["leancloud","is","great"]);
testObject.set("testDictionary", {key:"value"});
testObject.increment("testInteger");
testObject.addUnique("testArray", "service");
testObject.save();
}
function test_query() {
var TestObject = AV.Object.extend('TestObject')
var todoObject = new TestObject();
var query = new AV.Query(TestObject);
query.equalTo("testString", "leancloud");
query.notEqualTo("testString", "aws");
query.greaterThan("testInteger", 150);
query.limit(10);
query.skip(10);
// Sorts the results in ascending order by the score field
query.ascending("testString");
// Sorts the results in descending order by the score field
query.descending("testString");
// Restricts to wins < 50
query.lessThan("testInteger", 50);
// Restricts to wins <= 50
query.lessThanOrEqualTo("testInteger", 50);
// Restricts to wins > 50
query.greaterThan("testInteger", 50);
// Restricts to wins >= 50
query.greaterThanOrEqualTo("testInteger", 50);
// Finds scores from any of Jonathan, Dario, or Shawn
query.containedIn("testString",
["leancloud", "aws", "azure"]);
// Finds scores from anyone who is neither Jonathan, Dario, nor Shawn
query.notContainedIn("testString",
["leancloud", "aws", "azure"]);
// Finds objects that have the score set
query.exists("testInteger");
// Finds objects that don't have the score set
query.doesNotExist("testInteger");
query.select("testInteger", "leancloud");
// Find objects where the array in arrayKey contains 2.
query.equalTo("arrayKey", 2);
// Find objects where the array in arrayKey contains all of the elements 2, 3, and 4.
query.containsAll("arrayKey", [2, 3, 4]);
query.startsWith("testString", "l");
}
function test_file() {
var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
var file = new AV.File("myfile.txt", { base64: base64 });
var bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ];
var file = new AV.File("myfile.txt", bytes);
var file = new AV.File("myfile.zzz", {}, "image/png");
var src = file.url();
file.save().then(
() => {
// The file has been saved to Parse.
},
(error) => {
// The file either could n ot be read, or could not be saved to Parse.
});
// TODO: Check
}
function test_analytics() {
var dimensions = {
// Define ranges to bucket data points into meaningful segments
priceRange: '1000-1500',
// Did the user filter the query?
source: 'craigslist',
// Do searches happen more often on weekdays or weekends?
dayType: 'weekday'
};
// Send the dimensions to Parse along with the 'search' event
AV.Analytics.track('search', dimensions);
var codeString = '404';
AV.Analytics.track('error', { code: codeString })
}
function test_user_acl_roles() {
var user = new AV.User();
user.set("username", "my name");
user.set("password", "my pass");
user.set("email", "email@example.com");
// other fields can be set just like with Parse.Object
user.set("phone", "415-392-0202");
var currentUser = AV.User.current();
if (currentUser) {
// do stuff with the user
} else {
// show the signup or login page
}
AV.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
var groupACL = new AV.ACL();
var userList: AV.User[] = [AV.User.current()];
// userList is an array with the users we are sending this message to.
for (var i = 0; i < userList.length; i++) {
groupACL.setReadAccess(userList[i], true);
groupACL.setWriteAccess(userList[i], true);
}
groupACL.setPublicReadAccess(true);
AV.User.requestPasswordReset("email@example.com").then(function (data) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
// By specifying no write privileges for the ACL, we can ensure the role cannot be altered.
var role = new AV.Role("Administrator", groupACL);
role.getUsers().add(role);
role.getRoles().add(role);
role.save();
AV.User.logOut().then(function (data) {
// logged out
});
}
function test_push() {
AV.Push.send({
channels: [ "Gia nts", "Mets" ],
data: {
alert: "The Giants won against the Mets 2-3."
}
}, {
success: () => {
// Push was successful
},
error: (error: any) => {
// Handle error
}
});
var query = new AV.Query(AV.Installation);
query.equalTo('injuryReports', true);
AV.Push.send({
where: query, // Set our Installation query
data: {
alert: "Willie Hayes injured by own pop fly."
}
}, {
success: function() {
// Push was successful
},
error: function(error: any) {
// Handle error
}
});
}
function test_promise() {
let resolved = AV.Promise.as(true);
let rejected = AV.Promise.error("an error object");
AV.Promise.when([resolved, rejected]).then(function() {
// success
}, function() {
// failed
});
// can check whether an object is a Parse.Promise object or not
AV.Promise.is(resolved);
}
+806
View File
@@ -0,0 +1,806 @@
// Type definitions for avoscloud-sdk 0.6.10
// Project: https://leancloud.cn/
// Definitions by: Wu Jun <http://leancloud.cn>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "avoscloud-sdk" {
namespace AV {
var applicationId: string;
var applicationKey: string;
var masterKey: string;
interface SuccessOption {
success?: Function;
}
interface ErrorOption {
error?: Function;
}
interface SuccessFailureOptions extends SuccessOption, ErrorOption {
}
interface WaitOption {
/**
* Set to true to wait for the server to confirm success
* before triggering an event.
*/
wait?: boolean;
}
interface UseMasterKeyOption {
/**
* In Cloud Code and Node only, causes the Master Key to be used for this request.
*/
useMasterKey?: boolean;
}
interface SilentOption {
/**
* Set to true to avoid firing the event.
*/
silent?: boolean;
}
/**
* A Promise is returned by async methods as a hook to provide callbacks to be
* called when the async task is fulfilled.
*
* <p>Typical usage would be like:<pre>
* query.find().then(function(results) {
* results[0].set("foo", "bar");
* return results[0].saveAsync();
* }).then(function(result) {
* console.log("Updated " + result.id);
* });
* </pre></p>
*
* @see AV.Promise.prototype.then
* @class
*/
interface IPromise<T> {
then<U>(resolvedCallback: (value: T) => IPromise<U>, rejectedCallback?: (reason: any) => IPromise<U>): IPromise<T>;
then<U>(resolvedCallback: (value: T) => U, rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (value: T) => U, rejectedCallback?: (reason: any) => U): IPromise<U>;
}
class Promise<T> {
static as<U>(resolvedValue: U): Promise<U>;
static error<U>(error: U): Promise<U>;
static is(possiblePromise: any): Boolean;
static when(promises: Promise<any>[]): Promise<any>;
always(callback: Function): Promise<T>;
done(callback: Function): Promise<T>;
fail(callback: Function): Promise<T>;
reject(error: any): void;
resolve(result: any): void;
then<U>(resolvedCallback: (value: T) => Promise<U>,
rejectedCallback?: (reason: any) => Promise<U>): IPromise<T>;
then<U>(resolvedCallback: (value: T) => U,
rejectedCallback?: (reason: any) => IPromise<U>): IPromise<T>;
then<U>(resolvedCallback: (value: T) => U,
rejectedCallback?: (reason: any) => U): IPromise<T>;
}
interface IBaseObject {
toJSON(): any;
}
class BaseObject implements IBaseObject {
toJSON(): any;
}
/**
* Creates a new ACL.
* If no argument is given, the ACL has no permissions for anyone.
* If the argument is a AV.User, the ACL will have read and write
* permission for only that user.
* If the argument is any other JSON object, that object will be interpretted
* as a serialized ACL created with toJSON().
* @see AV.Object#setACL
* @class
*
* <p>An ACL, or Access Control List can be added to any
* <code>AV.Object</code> to restrict access to only a subset of users
* of your application.</p>
*/
class ACL extends BaseObject {
permissionsById: any;
constructor(arg1?: any);
setPublicReadAccess(allowed: boolean): void;
getPublicReadAccess(): boolean;
setPublicWriteAccess(allowed: boolean): void;
getPublicWriteAccess(): boolean;
setReadAccess(userId: User, allowed: boolean): void;
getReadAccess(userId: User): boolean;
setReadAccess(userId: string, allowed: boolean): void;
getReadAccess(userId: string): boolean;
setRoleReadAccess(role: Role, allowed: boolean): void;
setRoleReadAccess(role: string, allowed: boolean): void;
getRoleReadAccess(role: Role): boolean;
getRoleReadAccess(role: string): boolean;
setRoleWriteAccess(role: Role, allowed: boolean): void;
setRoleWriteAccess(role: string, allowed: boolean): void;
getRoleWriteAccess(role: Role): boolean;
getRoleWriteAccess(role: string): boolean;
setWriteAccess(userId: User, allowed: boolean): void;
setWriteAccess(userId: string, allowed: boolean): void;
getWriteAccess(userId: User): boolean;
getWriteAccess(userId: string): boolean;
}
/**
* A AV.File is a local representation of a file that is saved to the AV
* cloud.
* @class
* @param name {String} The file's name. This will be prefixed by a unique
* value once the file has finished saving. The file name must begin with
* an alphanumeric character, and consist of alphanumeric characters,
* periods, spaces, underscores, or dashes.
* @param data {Array} The data for the file, as either:
* 1. an Array of byte value Numbers, or
* 2. an Object like { base64: "..." } with a base64-encoded String.
* 3. a File object selected with a file upload control. (3) only works
* in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
* For example:<pre>
* var fileUploadControl = $("#profilePhotoFileUpload")[0];
* if (fileUploadControl.files.length > 0) {
* var file = fileUploadControl.files[0];
* var name = "photo.jpg";
* var AVFile = new AV.File(name, file);
* AVFile.save().then(function() {
* // The file has been saved to AV.
* }, function(error) {
* // The file either could not be read, or could not be saved to AV.
* });
* }</pre>
* @param type {String} Optional Content-Type header to use for the file. If
* this is omitted, the content type will be inferred from the name's
* extension.
*/
class File {
constructor(name: string, data: any, type?: string);
name(): string;
url(): string;
save<T>(options?: SuccessFailureOptions): Promise<T>;
}
/**
* Creates a new GeoPoint with any of the following forms:<br>
* <pre>
* new GeoPoint(otherGeoPoint)
* new GeoPoint(30, 30)
* new GeoPoint([30, 30])
* new GeoPoint({latitude: 30, longitude: 30})
* new GeoPoint() // defaults to (0, 0)
* </pre>
* @class
*
* <p>Represents a latitude / longitude point that may be associated
* with a key in a AVObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.</p>
*
* <p>Only one key in a class may contain a GeoPoint.</p>
*
* <p>Example:<pre>
* var point = new AV.GeoPoint(30.0, -20.0);
* var object = new AV.Object("PlaceObject");
* object.set("location", point);
* object.save();</pre></p>
*/
class GeoPoint extends BaseObject {
latitude: number;
longitude: number;
constructor(arg1?: any, arg2?: any);
current(options?: SuccessFailureOptions): GeoPoint;
radiansTo(point: GeoPoint): number;
kilometersTo(point: GeoPoint): number;
milesTo(point: GeoPoint): number;
}
/**
* A class that is used to access all of the children of a many-to-many relationship.
* Each instance of AV.Relation is associated with a particular parent object and key.
*/
class Relation extends BaseObject {
parent: Object;
key: string;
targetClassName: string;
constructor(parent?: Object, key?: string);
//Adds a AV.Object or an array of AV.Objects to the relation.
add(object: Object): void;
// Returns a AV.Query that is limited to objects in this relation.
query(): Query;
// Removes a AV.Object or an array of AV.Objects from this relation.
remove(object: Object): void;
}
/**
* Creates a new model with defined attributes. A client id (cid) is
* automatically generated and assigned for you.
*
* <p>You won't normally call this method directly. It is recommended that
* you use a subclass of <code>AV.Object</code> instead, created by calling
* <code>extend</code>.</p>
*
* <p>However, if you don't want to use a subclass, or aren't sure which
* subclass is appropriate, you can use this form:<pre>
* var object = new AV.Object("ClassName");
* </pre>
* That is basically equivalent to:<pre>
* var MyClass = AV.Object.extend("ClassName");
* var object = new MyClass();
* </pre></p>
*
* @param {Object} attributes The initial set of data to store in the object.
* @param {Object} options A set of Backbone-like options for creating the
* object. The only option currently supported is "collection".
* @see AV.Object.extend
*
* @class
*
* <p>The fundamental unit of AV data, which implements the Backbone Model
* interface.</p>
*/
class Object extends BaseObject {
id: any;
createdAt:any;
updatedAt:any;
attributes: any;
cid: string;
changed: boolean;
className: string;
constructor(className?: string, options?: any);
constructor(attributes?: string[], options?: any);
static extend(className: string, protoProps?: any, classProps?: any): any;
static fetchAll<T>(list: Object[], options: SuccessFailureOptions): Promise<T>;
static fetchAllIfNeeded<T>(list: Object[], options: SuccessFailureOptions): Promise<T>;
static destroyAll<T>(list: Object[], options?: Object.DestroyAllOptions): Promise<T>;
static saveAll<T>(list: Object[], options?: Object.SaveAllOptions): Promise<T>;
initialize(): void;
add(attr: string, item: any): Object;
addUnique(attr: string, item: any): any;
change(options: any): Object;
changedAttributes(diff: any): boolean;
clear(options: any): any;
clone(): Object;
destroy<T>(options?: Object.DestroyOptions): Promise<T>;
dirty(attr: String): boolean;
dirtyKeys(): string[];
escape(attr: string): string;
existed(): boolean;
fetch<T>(options?: Object.FetchOptions): Promise<T>;
get(attr: string): any;
getACL(): ACL;
getObjectId(): string;
has(attr: string): boolean;
hasChanged(attr: string): boolean;
increment(attr: string, amount?: number): any;
isValid(): boolean;
op(attr: string): any;
previous(attr: string): any;
previousAttributes(): any;
relation(attr: string): Relation;
remove(attr: string, item: any): any;
save<T>(options?: Object.SaveOptions, arg2?: any, arg3?: any): Promise<T>;
set(key: string, value: any, options?: Object.SetOptions): boolean;
setACL(acl: ACL, options?: SuccessFailureOptions): boolean;
unset(attr: string, options?: any): any;
validate(attrs: any, options?: SuccessFailureOptions): boolean;
}
namespace Object {
interface DestroyOptions extends SuccessFailureOptions, WaitOption, UseMasterKeyOption { }
interface DestroyAllOptions extends SuccessFailureOptions, UseMasterKeyOption { }
interface FetchOptions extends SuccessFailureOptions, UseMasterKeyOption { }
interface SaveOptions extends SuccessFailureOptions, SilentOption, UseMasterKeyOption, WaitOption { }
interface SaveAllOptions extends SuccessFailureOptions, UseMasterKeyOption { }
interface SetOptions extends ErrorOption, SilentOption {
promise?: any;
}
}
/**
* Every AV application installed on a device registered for
* push notifications has an associated Installation object.
*/
class Installation extends Object {
badge: any;
channels: string[];
timeZone: any;
deviceType: string;
pushType: string;
installationId: string;
deviceToken: string;
channelUris: string;
appName: string;
appVersion: string;
AVVersion: string;
appIdentifier: string;
}
/**
* Creates a new instance with the given models and options. Typically, you
* will not call this method directly, but will instead make a subclass using
* <code>AV.Collection.extend</code>.
*
* @param {Array} models An array of instances of <code>AV.Object</code>.
*
* @param {Object} options An optional object with Backbone-style options.
* Valid options are:<ul>
* <li>model: The AV.Object subclass that this collection contains.
* <li>query: An instance of AV.Query to use when fetching items.
* <li>comparator: A string property name or function to sort by.
* </ul>
*
* @see AV.Collection.extend
*
* @class
*
* <p>Provides a standard collection class for our sets of models, ordered
* or unordered. For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Collection">Backbone
* documentation</a>.</p>
*/
class Collection<T> extends Events implements IBaseObject {
model: Object;
models: Object[];
query: Query;
comparator: (object: Object) => any;
constructor(models?: Object[], options?: Collection.Options);
static extend(instanceProps: any, classProps: any): any;
initialize(): void;
add(models: any[], options?: Collection.AddOptions): Collection<T>;
at(index: number): Object;
fetch(options?: Collection.FetchOptions): Promise<T>;
create(model: Object, options?: Collection.CreateOptions): Object;
get(id: string): Object;
getByCid(cid: any): any;
pluck(attr: string): any[];
remove(model: any, options?: Collection.RemoveOptions): Collection<T>;
remove(models: any[], options?: Collection.RemoveOptions): Collection<T>;
reset(models: any[], options?: Collection.ResetOptions): Collection<T>;
sort(options?: Collection.SortOptions): Collection<T>;
toJSON(): any;
}
namespace Collection {
interface Options {
model?: Object;
query?: Query;
comparator?: string;
}
interface AddOptions extends SilentOption {
/**
* The index at which to add the models.
*/
at?: number;
}
interface CreateOptions extends SuccessFailureOptions, WaitOption, SilentOption, UseMasterKeyOption {
}
interface FetchOptions extends SuccessFailureOptions, SilentOption, UseMasterKeyOption { }
interface RemoveOptions extends SilentOption { }
interface ResetOptions extends SilentOption { }
interface SortOptions extends SilentOption { }
}
/**
* @class
*
* <p>AV.Events is a fork of Backbone's Events module, provided for your
* convenience.</p>
*
* <p>A module that can be mixed in to any object in order to provide
* it with custom events. You may bind callback functions to an event
* with `on`, or remove these functions with `off`.
* Triggering an event fires all callbacks in the order that `on` was
* called.
*
* <pre>
* var object = {};
* _.extend(object, AV.Events);
* object.on('expand', function(){ alert('expanded'); });
* object.trigger('expand');</pre></p>
*
* <p>For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Events">Backbone
* documentation</a>.</p>
*/
class Events {
static off(events: string[], callback?: Function, context?: any): Events;
static on(events: string[], callback?: Function, context?: any): Events;
static trigger(events: string[]): Events;
static bind(): Events;
static unbind(): Events;
on(eventName: string, callback?: Function, context?: any): Events;
off(eventName?: string, callback?: Function, context?: any): Events;
trigger(eventName: string, ...args: any[]): Events;
bind(eventName: string, callback: Function, context?: any): Events;
unbind(eventName?: string, callback?: Function, context?: any): Events;
}
/**
* Creates a new AV AV.Query for the given AV.Object subclass.
* @param objectClass -
* An instance of a subclass of AV.Object, or a AV className string.
* @class
*
* <p>AV.Query defines a query that is used to fetch AV.Objects. The
* most common use case is finding all objects that match a query through the
* <code>find</code> method. For example, this sample code fetches all objects
* of class <code>MyClass</code>. It calls a different function depending on
* whether the fetch succeeded or not.
*
* <pre>
* var query = new AV.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of AV.Object.
* },
*
* error: function(error) {
* // error is an instance of AV.Error.
* }
* });</pre></p>
*
* <p>A AV.Query can also be used to retrieve a single object whose id is
* known, through the get method. For example, this sample code fetches an
* object of class <code>MyClass</code> and id <code>myId</code>. It calls a
* different function depending on whether the fetch succeeded or not.
*
* <pre>
* var query = new AV.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of AV.Object.
* },
*
* error: function(object, error) {
* // error is an instance of AV.Error.
* }
* });</pre></p>
*
* <p>A AV.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. For example, this
* sample code counts the number of objects of the class <code>MyClass</code>
* <pre>
* var query = new AV.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of AV.Error.
* }
* });</pre></p>
*/
class Query extends BaseObject {
objectClass: any;
className: string;
constructor(objectClass: any);
static and(...var_args: Query[]): Query;
static or(...var_args: Query[]): Query;
addAscending(key: string): Query;
addAscending(key: string[]): Query;
addDescending(key: string): Query;
addDescending(key: string[]): Query;
ascending(key: string): Query;
ascending(key: string[]): Query;
collection(items?: Object[], options?: Collection.Options): Collection<Object>;
containedIn(key: string, values: any[]): Query;
contains(key: string, substring: string): Query;
containsAll(key: string, values: any[]): Query;
count<T>(options?: Query.CountOptions): Promise<T>;
descending(key: string): Query;
descending(key: string[]): Query;
doesNotExist(key: string): Query;
doesNotMatchKeyInQuery(key: string, queryKey: string, query: Query): Query;
doesNotMatchQuery(key: string, query: Query): Query;
each<T>(callback: Function, options?: SuccessFailureOptions): Promise<T>;
endsWith(key: string, suffix: string): Query;
equalTo(key: string, value: any): Query;
exists(key: string): Query;
find<T>(options?: Query.FindOptions): Promise<T>;
first<T>(options?: Query.FirstOptions): Promise<T>;
get(objectId: string, options?: Query.GetOptions): Promise<any>;
greaterThan(key: string, value: any): Query;
greaterThanOrEqualTo(key: string, value: any): Query;
include(key: string): Query;
include(keys: string[]): Query;
lessThan(key: string, value: any): Query;
lessThanOrEqualTo(key: string, value: any): Query;
limit(n: number): Query;
matches(key: string, regex: RegExp, modifiers: any): Query;
matchesKeyInQuery(key: string, queryKey: string, query: Query): Query;
matchesQuery(key: string, query: Query): Query;
near(key: string, point: GeoPoint): Query;
notContainedIn(key: string, values: any[]): Query;
notEqualTo(key: string, value: any): Query;
select(...keys: string[]): Query;
skip(n: number): Query;
startsWith(key: string, prefix: string): Query;
withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query;
withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query;
withinMiles(key: string, point: GeoPoint, maxDistance: number): Query;
withinRadians(key: string, point: GeoPoint, maxDistance: number): Query;
}
namespace Query {
interface CountOptions extends SuccessFailureOptions, UseMasterKeyOption { }
interface FindOptions extends SuccessFailureOptions, UseMasterKeyOption { }
interface FirstOptions extends SuccessFailureOptions, UseMasterKeyOption { }
interface GetOptions extends SuccessFailureOptions, UseMasterKeyOption { }
}
/**
* Represents a Role on the AV server. Roles represent groupings of
* Users for the purposes of granting permissions (e.g. specifying an ACL
* for an Object). Roles are specified by their sets of child users and
* child roles, all of which are granted any permissions that the parent
* role has.
*
* <p>Roles must have a name (which cannot be changed after creation of the
* role), and must specify an ACL.</p>
* @class
* A AV.Role is a local representation of a role persisted to the AV
* cloud.
*/
class Role extends Object {
constructor(name: string, acl: ACL);
getRoles(): Relation;
getUsers(): Relation;
getName(): string;
setName(name: string, options?: SuccessFailureOptions): any;
}
/**
* @class
*
* <p>A AV.User object is a local representation of a user persisted to the
* AV cloud. This class is a subclass of a AV.Object, and retains the
* same functionality of a AV.Object, but also extends it with various
* user specific methods, like authentication, signing up, and validation of
* uniqueness.</p>
*/
class User extends Object {
static current(): User;
static signUp<T>(username: string, password: string, attrs: any, options?: SuccessFailureOptions): Promise<T>;
static logIn<T>(username: string, password: string, options?: SuccessFailureOptions): Promise<T>;
static logOut<T>(): Promise<T>;
static allowCustomUserClass(isAllowed: boolean): void;
static become<T>(sessionToken: string, options?: SuccessFailureOptions): Promise<T>;
static requestPasswordReset<T>(email: string, options?: SuccessFailureOptions): Promise<T>;
signUp<T>(attrs: any, options?: SuccessFailureOptions): Promise<T>;
logIn<T>(options?: SuccessFailureOptions): Promise<T>;
fetch<T>(options?: SuccessFailureOptions): Promise<T>;
save<T>(arg1?: any, arg2?: any, arg3?: any): Promise<T>;
authenticated(): boolean;
isCurrent(): boolean;
getEmail(): string;
setEmail(email: string, options: SuccessFailureOptions): boolean;
getUsername(): string;
setUsername(username: string, options?: SuccessFailureOptions): boolean;
setPassword(password: string, options?: SuccessFailureOptions): boolean;
getSessionToken(): string;
}
namespace Analytics {
function track<T>(name: string, dimensions: any):Promise<T>;
}
class Error {
code: ErrorCode;
message: string;
constructor(code: ErrorCode, message: string);
}
enum ErrorCode {
OTHER_CAUSE = -1,
INTERNAL_SERVER_ERROR = 1,
CONNECTION_FAILED = 100,
OBJECT_NOT_FOUND = 101,
INVALID_QUERY = 102,
INVALID_CLASS_NAME = 103,
MISSING_OBJECT_ID = 104,
INVALID_KEY_NAME = 105,
INVALID_POINTER = 106,
INVALID_JSON = 107,
COMMAND_UNAVAILABLE = 108,
NOT_INITIALIZED = 109,
INCORRECT_TYPE = 111,
INVALID_CHANNEL_NAME = 112,
PUSH_MISCONFIGURED = 115,
OBJECT_TOO_LARGE = 116,
OPERATION_FORBIDDEN = 119,
CACHE_MISS = 120,
INVALID_NESTED_KEY = 121,
INVALID_FILE_NAME = 122,
INVALID_ACL = 123,
TIMEOUT = 124,
INVALID_EMAIL_ADDRESS = 125,
MISSING_CONTENT_TYPE = 126,
MISSING_CONTENT_LENGTH = 127,
INVALID_CONTENT_LENGTH = 128,
FILE_TOO_LARGE = 129,
FILE_SAVE_ERROR = 130,
DUPLICATE_VALUE = 137,
INVALID_ROLE_NAME = 139,
EXCEEDED_QUOTA = 140,
SCRIPT_FAILED = 141,
VALIDATION_ERROR = 142,
INVALID_IMAGE_DATA = 150,
UNSAVED_FILE_ERROR = 151,
INVALID_PUSH_TIME_ERROR = 152,
FILE_DELETE_ERROR = 153,
REQUEST_LIMIT_EXCEEDED = 155,
INVALID_EVENT_NAME = 160,
USERNAME_MISSING = 200,
PASSWORD_MISSING = 201,
USERNAME_TAKEN = 202,
EMAIL_TAKEN = 203,
EMAIL_MISSING = 204,
EMAIL_NOT_FOUND = 205,
SESSION_MISSING = 206,
MUST_CREATE_USER_THROUGH_SIGNUP = 207,
ACCOUNT_ALREADY_LINKED = 208,
INVALID_SESSION_TOKEN = 209,
LINKED_ID_MISSING = 250,
INVALID_LINKED_SESSION = 251,
UNSUPPORTED_SERVICE = 252,
AGGREGATE_ERROR = 600,
FILE_READ_ERROR = 601,
X_DOMAIN_REQUEST = 602
}
/**
* @class
* A AV.Op is an atomic operation that can be applied to a field in a
* AV.Object. For example, calling <code>object.set("foo", "bar")</code>
* is an example of a AV.Op.Set. Calling <code>object.unset("foo")</code>
* is a AV.Op.Unset. These operations are stored in a AV.Object and
* sent to the server as part of <code>object.save()</code> operations.
* Instances of AV.Op should be immutable.
*
* You should not create subclasses of AV.Op or instantiate AV.Op
* directly.
*/
namespace Op {
interface BaseOperation extends IBaseObject {
objects(): any[];
}
interface Add extends BaseOperation {
}
interface AddUnique extends BaseOperation {
}
interface Increment extends IBaseObject {
amount: number;
}
interface Relation extends IBaseObject {
added(): Object[];
removed: Object[];
}
interface Set extends IBaseObject {
value(): any;
}
interface Unset extends IBaseObject {
}
}
/**
* Contains functions to deal with Push in AV
* @name AV.Push
* @namespace
*/
namespace Push {
function send<T>(data: PushData, options?: SendOptions): Promise<T>;
interface PushData {
channels?: string[];
push_time?: Date;
expiration_time?: Date;
expiration_interval?: number;
where?: Query;
data?: any;
alert?: string;
badge?: string;
sound?: string;
title?: string;
}
interface SendOptions {
success?: () => void;
error?: (error: Error) => void;
}
}
/**
* Call this method first to set up your authentication tokens for AV.
* @param {String} applicationId Your Application ID.
* @param {String} applicationKey Your Application Key.
* @param {String} masterKey (optional) Your Application Master Key. (Node.js only!)
*/
function initialize(applicationId: string, applicationKey: string, masterKey?: string): void;
}
export = AV;
}
declare module 'leanengine' {
import alias = require('avoscloud-sdk');
export = alias;
}
+49
View File
@@ -0,0 +1,49 @@
/// <reference path="aws-lambda.d.ts" />
import lambda = require('aws-lambda');
var str: string;
var date: Date;
var sns: lambda.SNS;
var kinesis: lambda.Kinesis;
var recordsList: lambda.Record[];
var anyObj: any;
var num: number;
/* Records */
var records: lambda.Records;
recordsList = records.Records;
/* Record */
var record: lambda.Record;
str = record.EventVersion;
str = record.EventSubscriptionArn;
str = record.EnventSource;
sns = record.Sns;
kinesis = record.kinesis;
/* SNS */
str = sns.Type;
str = sns.MessageId;
str = sns.TopicArn;
str = sns.Subject;
str = sns.Message;
date = sns.Timestamp;
/* Kinesis */
var kinesis: lambda.Kinesis;
str = kinesis.data;
/* Context */
var context: lambda.Context;
context.log(str, anyObj);
context.fail(str);
context.succeed(str);
context.succeed(anyObj);
context.succeed(str, anyObj);
str = context.awsRequestId;
num = context.getRemainingTimeInMillis();
+43
View File
@@ -0,0 +1,43 @@
// Type definitions for AWS Lambda
// Project: http://docs.aws.amazon.com/lambda
// Definitions by: Michael Skarum <https://github.com/skarum>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "aws-lambda" {
export interface Records {
Records: Record[];
}
interface Record {
EventVersion: string;
EventSubscriptionArn: string;
EnventSource: string;
Sns: SNS;
kinesis: Kinesis;
}
interface SNS {
Type: string;
MessageId: string;
TopicArn: string;
Subject: string;
Message: string;
Timestamp: Date;
}
interface Kinesis {
data: string;
}
export interface Context {
log(message: string, object: any): void;
fail(message: string): void;
succeed(message: string): void;
succeed(object: any): void;
succeed(message: string, object: any): void;
awsRequestId: string;
getRemainingTimeInMillis(): number;
}
export type Callback = (error?: Error, message?: string) => void;
}
+130 -1
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
*/
@@ -253,4 +279,107 @@ sqs.setQueueAttributes({
else console.log(data); // successful response
});
var dynamoDBDocClient:AWS.DynamoDB.DocumentClient;
dynamoDBDocClient = new AWS.DynamoDB.DocumentClient();
dynamoDBDocClient = new AWS.DynamoDB.DocumentClient({});
dynamoDBDocClient.createSet([1, 2, 3], { validate: true });
dynamoDBDocClient.get(
{
TableName: 'TABLE_NAME',
Key: { userId: 'abc123', email: 'abc123@abc123.com' }
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}
);
dynamoDBDocClient.put(
{
TableName: 'TABLE_NAME',
Item: {
userId: 'abc123',
email: 'abc123@abc123.com',
firstName: 'Matt',
lastName: 'Forrester the ' + new Date().getTime()
}
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}
);
dynamoDBDocClient.delete(
{
TableName: 'TABLE_NAME',
Key: {
userId: 'abc123',
email: 'abc123@abc123.com'
}
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}
);
dynamoDBDocClient.update(
{
TableName: 'TABLE_NAME',
Key: {
userId: 'abc123',
email: 'abc123@abc123.com'
},
AttributeUpdates: {
thingsWithWheels: {
Action: 'PUT',
Value: dynamoDBDocClient.createSet(
[
'SkateBoard',
'Skates',
'Mountain Bike',
'Evolve Electric Skateboard'
],
{ validate: true }
)
},
age: {
Action: 'PUT',
Value: 35
}
}
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}
);
dynamoDBDocClient.scan(
{
TableName: 'TABLE_NAME',
KeyConditions: {
age: {
ComparisonOperator: 'EQ',
AttributeValueList: [35]
}
}
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}
);
dynamoDBDocClient.query(
{
TableName: 'TABLE_NAME',
KeyConditions: {
userId: {
ComparisonOperator: 'EQ',
AttributeValueList: ['abc123']
}
}
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}
);
+1801 -1185
View File
File diff suppressed because it is too large Load Diff
+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;
}
@@ -0,0 +1,81 @@
///<reference path="./backbone-fetch-cache.d.ts" />
import * as Backbone from "backbone-fetch-cache";
// static methods / properties
const fc: BackboneFetchCache.Static = Backbone.fetchCache;
fc.enabled = true;
fc.localStorage = true;
const opts: BackboneFetchCache.GetCacheOptions = {url: "string url", data: {}};
const strKey: string = "string key";
const getCacheKeyOpts = {getCacheKey: () => "string key"};
let cache: BackboneFetchCache.Cache
cache = fc.getCache(strKey);
cache = fc.getCache(() => strKey);
cache = fc.getCache(getCacheKeyOpts);
cache = fc.getCache({url: strKey});
cache = fc.getCache({url: () => strKey});
cache = fc.getCache(strKey, opts);
const cacheExpires: number = cache.expires;
const cacheLastSync: number = cache.lastSync;
const cachePrefillExpires: number = cache.prefillExpires;
const cacheValue: any = cache.value;
let key: string;
key = fc.getCacheKey(strKey);
key = fc.getCacheKey(strKey, opts);
key = fc.getCacheKey(getCacheKeyOpts);
let lastSync: number;
lastSync = fc.getLastSync(strKey, opts);
lastSync = fc.getLastSync(getCacheKeyOpts, opts);
fc.getLocalStorage();
const localStorageKey: string = fc.getLocalStorageKey();
fc.priorityFn = (a: BackboneFetchCache.Cache, b: BackboneFetchCache.Cache) => 12345;
fc.reset();
const setOpts: BackboneFetchCache.SetCacheOptions = {
data: {},
url: strKey,
cache: true,
expires: 12345,
prefill: true,
prefillExpires: 12345,
};
fc.setCache(strKey, setOpts, {});
fc.setLocalStorage();
// instance methods
const modelOpts: Backbone.ModelFetchWithCacheOptions = {
cache: true,
expires: new Date().getTime(),
prefill: true,
prefillExpires: new Date().getTime(),
prefillSuccess: (self: any, attributes: any, opts: Backbone.ModelFetchWithCacheOptions) => { },
context: {},
};
const hoge = <Backbone.ModelWithCache> new Backbone.Model;
hoge.fetch(modelOpts);
const collectionOpts: Backbone.CollectionFetchWithCacheOptions = {
cache: true,
context: {},
expires: new Date().getTime(),
prefill: true,
prefillExpires: new Date().getTime(),
prefillSuccess: (self: any) => { },
};
const fuga = <Backbone.CollectionWithCache> new Backbone.Collection;
fuga.fetch(collectionOpts);
+189
View File
@@ -0,0 +1,189 @@
// Type definitions for backbone-fetch-cache 1.4.0
// Project: https://github.com/madglory/backbone-fetch-cache
// Definitions by: delphinus <https://github.com/delphinus35/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../backbone/backbone.d.ts" />
declare namespace BackboneFetchCache {
interface SuperMethods {
modelFetch(options?: Backbone.ModelFetchOptions): JQueryXHR;
modelSync(...arg: any[]): JQueryXHR;
collectionFetch(options?: Backbone.CollectionFetchOptions): JQueryXHR;
}
interface GetCacheOptions {
data?: any;
url?: string;
}
interface SetCacheOptions extends GetCacheOptions {
cache: boolean;
expires: boolean | number;
prefill: boolean;
prefillExpires: boolean | number;
}
interface Cache {
expires: number;
lastSync: number;
prefillExpires: number;
value: any;
}
interface GetCacheKeyObject {
getCacheKey?: (opts?: GetCacheOptions) => string;
url?: () => string;
}
type GetCacheKeyOptions = string | {url: string} | GetCacheKeyObject;
interface Static {
/**
* Global flag to enable/disable caching
*/
enabled: boolean;
/**
* By default the cache is persisted in localStorage (if available).
* Set Backbone.fetchCache.localStorage = false to disable this.
*/
localStorage: boolean;
/**
* Sometimes you just need to clear a cached item manually.
* Backbone.fetchCache.clearItem() can be called safely from anywhere
* in your application. It will take your backbone Model or Collection,
* a function that returns the key String, or the key String itself. If
* you pass in a Model or Collection, the .getCacheKey() method will be
* checked before the url property.
*/
clearItem(...args: any[]): any;
/**
* You can explicitly fetch a cached item, without having to call the
* models/collection fetch. This might be useful for debugging and
* testing.
*/
getCache(key: () => string, opts?: GetCacheOptions): Cache;
getCache(key: GetCacheKeyOptions, opts?: GetCacheOptions): Cache;
getCacheKey(key: () => string, opts?: GetCacheOptions): string;
getCacheKey(key: GetCacheKeyOptions, opts?: GetCacheOptions): string;
/**
* If you want to know when was the last (server) sync of a given key, you can use.
*/
getLastSync(key: () => string, opts?: GetCacheOptions): number;
getLastSync(key: GetCacheKeyOptions, opts?: GetCacheOptions): number;
getLocalStorage(): void;
getLocalStorageKey(): string;
/**
* When setting items in localStorage, the browser may throw a
* QUOTA_EXCEEDED_ERR, meaning the store is full. Backbone.fetchCache
* tries to work around this problem by deleting what it considers the
* most stale item to make space for the new data. The staleness of
* data is determined by the sorting function priorityFn, which by
* default returns the oldest item.
*/
priorityFn(a: Cache, b: Cache): number;
reset(): void;
setCache(instance: () => string, opts?: SetCacheOptions, attrs?: any): void;
setCache(instance: GetCacheKeyOptions, opts?: SetCacheOptions, attrs?: any): void;
setLocalStorage(...args: any[]): any;
_superMethods: SuperMethods;
}
}
declare module Backbone {
var fetchCache: BackboneFetchCache.Static;
/**
* The most used API hook for Backbone Fetch Cache is the Model and
* Collection #.fetch() method. Here are the options you can pass into that
* method to get behaviour particular to Backbone Fetch Cache.
*/
interface ModelFetchWithCacheOptions extends ModelFetchOptions {
/**
* Calls to modelInstance.fetch or collectionInstance.fetch will be
* fulfilled from the cache (if possible) when cache: true is set in
* the options hash.
*/
cache?: boolean;
context?: any;
/**
* Cache values expire after 5 minutes by default. You can adjust this
* by passing expires: <seconds> to the fetch call. Set to false to
* never expire.
*/
expires?: number;
/**
* This option allows the model/collection to be populated from the
* cache immediately and then be updated once the call to fetch has
* completed. The initial cache hit calls the prefillSuccess callback
* and then the AJAX success/error callbacks are called as normal when
* the request is complete. This allows the page to render something
* immediately and then update it after the request completes. (Note:
* the prefillSuccess callback will not fire if the data is not found
* in the cache.)
*
* prefill and prefillExpires options can be used with the promises
* interface like so (note: the progress event will not fire if the
* data is not found in the cache.).
*
* prefillExpires affects prefill in the following ways:
*
* 1. If the cache doesn't hold the requested data, just fetch it
* (usual behaviour)
* 2. If the cache holds an expired version of the requested data, just
* fetch it (usual behaviour)
* 3. If the cache holds requested data that is neither expired nor
* prefill expired, just return it and don't do a fetch / prefill
* callback (usual cache behavior, unusual prefill behaviour)
* 4. If the cache holds requested data that isn't expired but is
* prefill expired, use the prefill callback and do a fetch (usual
* prefill behaviour)
*/
prefill?: boolean;
prefillExpires?: number;
prefillSuccess?: (self: any, attributes: any, opts: ModelFetchWithCacheOptions) => void;
}
interface CollectionFetchWithCacheOptions extends ModelFetchWithCacheOptions {
prefillSuccess?: (self: any) => void;
}
interface ModelWithCache extends Model {
fetch(options?: ModelFetchWithCacheOptions): JQueryXHR;
}
interface CollectionWithCache extends Collection<Model> {
fetch(options?: CollectionFetchWithCacheOptions): JQueryXHR;
}
}
declare module "backbone-fetch-cache" {
export = Backbone;
}
+7 -1
View File
@@ -101,4 +101,10 @@ function TestGlobalApiAndChannels() {
Backbone.Radio.reply('auth', 'authenticate', onStart);
Backbone.Radio.request('auth', 'authenticate', 'pelle', 42);
}
}
import Radio = require('backbone.radio');
function TestImport() {
var channel: Backbone.Radio.Channel = Radio.channel('channel-name');
channel.command('show:view');
}
+6
View File
@@ -90,3 +90,9 @@ declare namespace Backbone {
}
}
}
declare module 'backbone.radio' {
import Backbone = require('backbone');
export = Backbone.Radio;
}
+90 -49
View File
@@ -1,4 +1,4 @@
// Type definitions for Backbone 1.0.0
// Type definitions for Backbone 1.3.3
// Project: http://backbonejs.org/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Natan Vivo <https://github.com/nvivo/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -9,6 +9,7 @@ declare namespace Backbone {
interface AddOptions extends Silenceable {
at?: number;
merge?: boolean;
}
interface HistoryOptions extends Silenceable {
@@ -108,9 +109,15 @@ declare namespace Backbone {
attributes: any;
changed: any[];
cidPrefix: string;
cid: string;
collection: Collection<any>;
private _changing: boolean;
private _previousAttributes : any;
private _pending: boolean;
/**
* Default attributes for the model. It can be an object hash or a method returning an object hash.
* For assigning an object hash, do it like this: this.defaults = <any>{ attribute: value, ... };
@@ -146,8 +153,14 @@ declare namespace Backbone {
/*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model;
set(obj: any, options?: ModelSetOptions): Model;
change(): any;
changedAttributes(attributes?: any): any[];
/**
* Return an object containing all the attributes that have changed, or
* false if there are no changed attributes. Useful for determining what
* parts of a view need to be updated and/or what attributes need to be
* persisted to the server. Unset attributes will be set to undefined.
* You can also pass an attributes object to diff against the model,
* determining if there *would be* a change. */
changedAttributes(attributes?: any): any;
clear(options?: Silenceable): any;
clone(): Model;
destroy(options?: ModelDestroyOptions): any;
@@ -172,8 +185,13 @@ 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;
matches(attrs: any): boolean;
}
class Collection<TModel extends Model> extends ModelBase {
@@ -204,12 +222,13 @@ declare namespace Backbone {
* Get a model from a collection, specified by an id, a cid, or by passing in a model.
**/
get(id: number|string|Model): TModel;
has(key: number|string|Model): boolean;
create(attributes: any, options?: ModelSaveOptions): TModel;
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;
@@ -217,63 +236,79 @@ declare namespace Backbone {
unshift(model: TModel, options?: AddOptions): TModel;
where(properties: any): TModel[];
findWhere(properties: any): TModel;
modelId(attrs: any) : any
private _prepareModel(attributes?: any, options?: any): any;
private _removeReference(model: TModel): void;
private _onModelEvent(event: string, model: TModel, collection: Collection<TModel>, options: any): void;
private _isModel(obj: any) : obj is Model;
/**
* 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 {
@@ -296,6 +331,8 @@ declare namespace Backbone {
navigate(fragment: string, options?: NavigateOptions): Router;
navigate(fragment: string, trigger?: boolean): Router;
execute(callback: Function, args: any[], name: string) : void;
private _bindRoutes(): void;
private _routeToRegExp(route: string): RegExp;
private _extractParameters(route: RegExp, fragment: string): string[];
@@ -312,10 +349,15 @@ declare namespace Backbone {
getHash(window?: Window): string;
getFragment(fragment?: string): string;
decodeFragment(fragment: string): string;
getSearch(): string;
stop(): void;
route(route: string, callback: Function): number;
checkUrl(e?: any): void;
loadUrl(fragmentOverride: string): boolean;
getPath(): string;
matchRoot(): boolean;
atRoot(): boolean;
loadUrl(fragmentOverride?: string): boolean;
navigate(fragment: string, options?: any): boolean;
static started: boolean;
options: any;
@@ -369,7 +411,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;
+94
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,11 +180,86 @@ 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);
}
//////////
Backbone.history.start();
Backbone.History.started;
Backbone.history.loadUrl();
Backbone.history.loadUrl('12345');
namespace v1Changes {
namespace events {
+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);
}
//////////
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Backbone 1.0.0
// Type definitions for Backbone 1.3.3
// Project: http://backbonejs.org/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Natan Vivo <https://github.com/nvivo/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+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;
}
@@ -0,0 +1,12 @@
/// <reference path="bazinga-translator.d.ts" />
Translator.fallback = 'en';
Translator.defaultDomain = 'messages';
Translator.add("test", "it work", "frontend", "en");
Translator.trans('key', {}, 'frontend');
Translator.trans('key', {"foo": "bar"}, 'DOMAIN_NAME');
Translator.transChoice('key', 1, {}, 'frontend');
Translator.transChoice('key', 123, {"foo": "bar"}, 'DOMAIN_NAME');
+99
View File
@@ -0,0 +1,99 @@
// Type definitions for Translator
// Project: https://github.com/willdurand/BazingaJsTranslationBundle
// Definitions by: Alex <https://github.com/alexndlm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface BazingaTranslator {
/**
* The current locale.
*
* @type {String}
*/
locale: string;
/**
* Fallback locale.
*
* @type {String}
*/
fallback: string;
/**
* Placeholder prefix.
*
* @type {String}
*/
placeHolderPrefix: string;
/**
* Placeholder suffix.
*
* @type {String}
*/
placeHolderSuffix: string;
/**
* Default domain.
*
* @type {String}
*/
defaultDomain: string;
/**
* Plural separator.
*
* @type {String}
*/
pluralSeparator: string;
/**
* Adds a translation entry.
*
* @param {String} id The message id
* @param {String} message The message to register for the given id
* @param {String} [domain] The domain for the message or null to use the default
* @param {String} [locale] The locale or null to use the default
*
* @return {Object} Translator
*/
add(id: string, message: string, domain: string, locale: string): BazingaTranslator;
/**
* Translates the given message.
*
* @param {String} id The message id
* @param {Object} [parameters] An array of parameters for the message
* @param {String} [domain] The domain for the message or null to guess it
* @param {String} [locale] The locale or null to use the default
*
* @return {String} The translated string
*/
trans(id: string, parameters: any, domain: string, locale?: string): string;
/**
* Translates the given choice message by choosing a translation according to a number.
*
* @param {String} id The message id
* @param {Number} number The number to use to find the indice of the message
* @param {Object} [parameters] An array of parameters for the message
* @param {String} [domain] The domain for the message or null to guess it
* @param {String} [locale] The locale or null to use the default
*
* @return {String} The translated string
*/
transChoice(id: string, number: number, parameters: any, domain: string, locale?: string): string,
/**
* Loads translations from JSON.
*
* @param {String} data A JSON string or object literal
*
* @return {Object} Translator
*/
fromJSON(data: string): BazingaTranslator;
reset(): void;
}
declare var Translator: BazingaTranslator;
+98
View File
@@ -0,0 +1,98 @@
/// <reference path="./bezier-js.d.ts" />
function test() {
var bezierjs: typeof BezierJs;
var bezier = new bezierjs.Bezier([1, 2, 3, 4]);
var cap = new bezierjs.BezierCap([]);
var point: BezierJs.Point = { x: 0, y: 0 };
var utils = bezier.getUtils();
var line: BezierJs.Line = { p1: { x: 0, y: 0 }, p2: { x: 1, y: 1 } };
var abc: BezierJs.ABC = { A: null, B: null, C: null };
var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 };
var bbox: BezierJs.BBox = bezier.bbox();
var closest: BezierJs.Closest = { mdist: 1, mpos: 0 };
var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z: [0] };
var minmax: BezierJs.MinMax = { min: 0, max: 0 };
var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point };
var pair: BezierJs.Pair = { left: bezier, right: bezier };
var poly: BezierJs.PolyBezier = bezier.outline(1);
var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 };
var shape: BezierJs.Shape = {
startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox, intersections: function (shape) { return [[0]]; }
};
var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] };
bezier.arcs();
bezier.clockwise;
bezier.compute(.5);
bezier.computedirection();
bezier.curveintersects([bezier], [bezier]);
bezier.derivative(0);
bezier.get(1);
bezier.getLUT()[0].x;
bezier.hull(0);
bezier.extrema();
bezier.intersects(bezier);
bezier.length();
bezier.lineIntersects(line);
bezier.normal(0);
bezier.offset(1, 2);
bezier.on(point, 0);
bezier.order = 5;
bezier.outlineshapes(1, 3);
bezier.overlaps(bezier);
bezier.point(9);
bezier.project(point);
bezier.raise();
bezier.reduce();
bezier.scale(4);
bezier.selfintersects();
bezier.simple();
bezier.split(0, 1).clockwise;
bezier.split(0.5).left;
bezier.toSVG();
bezier.update();
cap.virtual = true;
poly.addCurve(bezier);
poly.bbox();
poly.curve(7);
poly.curves[0]._3d;
poly.length();
poly.offset(9).points[0].y;
poly.points[0];
utils.abcratio(0, 1);
utils.align([point], line);
utils.angle(point, point, point);
utils.approximately(5, 7, .001);
utils.arcfn(1, function () { });
utils.bboxoverlap(bbox, bbox);
utils.between(0, 0, 1);
utils.closest([point], point);
utils.copy({});
utils.dist(point, point);
utils.droots([9]);
utils.expandbox(bbox, bbox);
utils.findbbox([bezier]);
utils.getccenter(point, point, point);
utils.getminmax(bezier, 'x', [0]);
utils.length(function () { });
utils.lerp(1, point, point);
utils.lli(offset, offset);
utils.lli4(point, point, point, point);
utils.lli8(0, 0, 0, 0, 0, 0, 0, 0);
utils.makeline(point, point);
utils.makeshape(bezier, bezier);
utils.map(0, 0, 0, 0, 0);
utils.pairiteration(bezier, bezier);
utils.pointsToString([point]);
utils.projectionratio(0, 0);
utils.roots([point], line);
utils.round(.999, .001);
utils.shapeintersections(shape, bbox, shape, bbox);
}
+199
View File
@@ -0,0 +1,199 @@
// Type definitions for Bezier.js
// Project: https://github.com/Pomax/bezierjs
// Definitions by: Dan Marshall <https://github.com/danmarshall>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module BezierJs {
interface Point {
x: number;
y: number;
z?: number;
}
interface Projection extends Point {
t?: number;
d?: number;
}
interface Inflection {
x: number[];
y: number[];
z?: number[];
values: number[];
}
interface Offset extends Point {
c: Point;
n: Point;
}
interface Pair {
left: Bezier;
right: Bezier;
}
interface Split extends Pair {
span: Point[];
_t1?: number;
_t2?: number;
}
interface MinMax {
min: number;
mid?: number;
max: number;
size?: number;
}
interface BBox {
x: MinMax;
y: MinMax;
z?: MinMax;
}
interface Line {
p1: Point;
p2: Point;
}
interface Arc extends Point {
e: number;
r: number;
s: number;
}
interface Shape {
startcap: BezierCap;
forward: Bezier;
back: Bezier;
endcap: BezierCap;
bbox: BBox;
intersections: (shape: Shape) => string[][] | number[][];
}
interface ABC {
A: Point;
B: Point;
C: Point;
}
interface Closest {
mdist: number;
mpos: number;
}
/**
* Bezier curve constructor. The constructor argument can be one of three things:
*
* 1. array/4 of {x:..., y:..., z:...}, z optional
* 2. numerical array/8 ordered x1,y1,x2,y2,x3,y3,x4,y4
* 3. numerical array/12 ordered x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4
*
*/
class Bezier {
private _linear;
clockwise: boolean;
_3d: boolean;
_t1: number;
_t2: number;
_lut: Point[];
dpoints: Point[][];
order: number;
points: Point[];
dims: string[];
dimlen: number;
constructor(points: Point[]);
constructor(coords: number[]);
constructor(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4?: number, y4?: number);
constructor(p1: Point, p2: Point, p3: Point, p4?: Point);
static fromSVG(svgString: string): Bezier;
static getABC(n: number, S: Point, B: Point, E: Point, t: number): ABC;
static quadraticFromPoints(p1: Point, p2: Point, p3: Point, t: number): Bezier;
static cubicFromPoints(S: Point, B: Point, E: Point, t: number, d1: number): Bezier;
static getUtils(): typeof utils;
getUtils(): typeof utils;
valueOf(): string;
toString(): string;
toSVG(): string;
update(): void;
computedirection(): void;
length(): number;
getLUT(steps?: number): Point[];
on(point: Point, error: number): number;
project(point: Point): Projection;
get(t: number): Point;
point(idx: number): Point;
compute(t: number): Point;
raise(): Bezier;
derivative(t: number): Point;
inflections(): number[];
normal(t: number): Point;
private __normal2(t);
private __normal3(t);
private __normal(t);
hull(t: number): Point[];
split(t1: number): Split;
split(t1: number, t2: number): Bezier;
extrema(): Inflection;
bbox(): BBox;
overlaps(curve: Bezier): boolean;
offset(t: number, d?: number): Offset | Bezier[];
simple(): boolean;
reduce(): Bezier[];
scale(d: Function): Bezier;
scale(d: number): Bezier;
outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier;
outlineshapes(d1: number, d2: number, curveIntersectionThreshold?: number): Shape[];
intersects(curve: Bezier, curveIntersectionThreshold?: number): string[] | number[];
intersects(curve: Line): string[] | number[];
lineIntersects(line: Line): number[];
selfintersects(curveIntersectionThreshold?: number): string[];
curveintersects(c1: Bezier[], c2: Bezier[], curveIntersectionThreshold?: number): string[];
arcs(errorThreshold?: number): Arc[];
private _error(pc, np1, s, e);
private _iterate(errorThreshold, circles);
}
class BezierCap extends Bezier {
virtual: boolean;
}
}
declare module BezierJs.utils {
var Tvalues: number[];
var Cvalues: number[];
function arcfn(t: number, derivativeFn: Function): number;
function between(v: number, m: number, M: number): boolean;
function approximately(a: number, b: number, precision?: number): boolean;
function length(derivativeFn: Function): number;
function map(v: number, ds: number, de: number, ts: number, te: number): number;
function lerp(r: number, v1: Point, v2: Point): Point;
function pointToString(p: Point): string;
function pointsToString(points: Point[]): string;
function copy(obj: Object): any;
function angle(o: Point, v1: Point, v2: Point): number;
function round(v: number, d: number): number;
function dist(p1: Point, p2: Point): number;
function closest(LUT: Point[], point: Point): Closest;
function abcratio(t: number, n: number): number;
function projectionratio(t: number, n: number): number;
function lli8(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): Point;
function lli4(p1: Point, p2: Point, p3: Point, p4: Point): Point;
function lli(v1: Offset, v2: Offset): Point;
function makeline(p1: Point, p2: Point): Bezier;
function findbbox(sections: Bezier[]): BBox;
function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox, curveIntersectionThreshold?: number): string[][] | number[][];
function makeshape(forward: Bezier, back: Bezier, curveIntersectionThreshold?: number): Shape;
function getminmax(curve: Bezier, d: string, list: number[]): MinMax;
function align(points: Point[], line: Line): Point[];
function roots(points: Point[], line: Line): number[];
function droots(p: number[]): number[];
function inflections(points: Point[]): number[];
function bboxoverlap(b1: BBox, b2: BBox): boolean;
function expandbox(bbox: BBox, _bbox: BBox): void;
function pairiteration(c1: Bezier, c2: Bezier, curveIntersectionThreshold?: number): string[];
function getccenter(p1: Point, p2: Point, p3: Point): Arc;
}
declare module BezierJs {
/**
* Poly Bezier
* @param {[type]} curves [description]
*/
class PolyBezier {
curves: Bezier[];
private _3d;
points: Point[];
constructor(curves: Bezier[]);
valueOf(): string;
toString(): string;
addCurve(curve: Bezier): void;
length(): number;
curve(idx: number): Bezier;
bbox(): BBox;
offset(d: number): PolyBezier;
}
}
+17 -1
View File
@@ -12,6 +12,7 @@
*/
import BigJS = BigJsLibrary.BigJS;
function constructorTests() {
var x = new Big(9) // '9'
var y = new Big(x) // '9'
@@ -247,4 +248,19 @@ function testMultipleConstructors() {
x.div(3) // 1.667
y.div(3) // 1.6666666667
}
}
function multipleTypesAccepted(n: number | BigJS | string) {
var y = Big(n)
.minus(n)
.mod(n)
.plus(n)
.times(n);
y.cmp(n);
y.eq(n);
y.gt(n);
y.gte(n);
y.lt(n);
y.lte(n);
y.div(n)
}
+16 -82
View File
@@ -25,23 +25,11 @@ declare namespace BigJsLibrary {
RM: RoundingMode;
}
type BigNumberInputType = number | string | BigJS;
interface BigJS_Constructors {
/** A decimal value. */
new (value: number): BigJS;
/** A decimal value.
String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid.
String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */
new (value: string): BigJS;
/** A decimal value. */
new (value: BigJS): BigJS;
/** A decimal value. */
(value: number): BigJS;
/** A decimal value.
String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid.
String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */
(value: string): BigJS;
/** A decimal value. */
(value: BigJS): BigJS;
new (value: BigNumberInputType): BigJS;
(value: BigNumberInputType): BigJS;
/** A decimal value. */
(): BigJS;
@@ -57,85 +45,35 @@ declare namespace BigJsLibrary {
1 = If the value of this Big number is greater than the value of n
-1 = If the value of this Big number is less than the value of n
0 = If this Big number and n have the same value */
cmp(n: number): number;
/** Compare
@returns {Number}
1 = If the value of this Big number is greater than the value of n
-1 = If the value of this Big number is less than the value of n
0 = If this Big number and n have the same value */
cmp(n: string): number;
/** Compare
@returns {Number}
1 = If the value of this Big number is greater than the value of n
-1 = If the value of this Big number is less than the value of n
0 = If this Big number and n have the same value */
cmp(n: BigJS): number;
cmp(n: BigNumberInputType): number;
/** Returns a Big number whose value is the value of this Big number divided by n. */
div(n: number): BigJS;
/** Returns a Big number whose value is the value of this Big number divided by n. */
div(n: string): BigJS;
/** Returns a Big number whose value is the value of this Big number divided by n. */
div(n: BigJS): BigJS;
div(n: BigNumberInputType): BigJS;
/** Returns true if the value of this Big equals the value of n, otherwise returns false. */
eq(n: number): boolean;
/** Returns true if the value of this Big equals the value of n, otherwise returns false. */
eq(n: string): boolean;
/** Returns true if the value of this Big equals the value of n, otherwise returns false. */
eq(n: BigJS): boolean;
eq(n: BigNumberInputType): boolean;
/** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */
gt(n: number): boolean;
/** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */
gt(n: string): boolean;
/** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */
gt(n: BigJS): boolean;
gt(n: BigNumberInputType): boolean;
/** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */
gte(n: number): boolean;
/** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */
gte(n: string): boolean;
/** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */
gte(n: BigJS): boolean;
gte(n: BigNumberInputType): boolean;
/** Returns true if the value of this Big is less than the value of n, otherwise returns false. */
lt(n: number): boolean;
/** Returns true if the value of this Big is less than the value of n, otherwise returns false. */
lt(n: string): boolean;
/** Returns true if the value of this Big is less than the value of n, otherwise returns false. */
lt(n: BigJS): boolean;
lt(n: BigNumberInputType): boolean;
/** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */
lte(n: number): boolean;
/** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */
lte(n: string): boolean;
/** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */
lte(n: BigJS): boolean;
lte(n: BigNumberInputType): boolean;
/** Returns a Big number whose value is the value of this Big number minus n. */
minus(n: number): BigJS;
/** Returns a Big number whose value is the value of this Big number minus n. */
minus(n: string): BigJS;
/** Returns a Big number whose value is the value of this Big number minus n. */
minus(n: BigJS): BigJS;
minus(n: BigNumberInputType): BigJS;
/** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n.
The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */
mod(n: number): BigJS;
/** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n.
The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */
mod(n: string): BigJS;
/** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n.
The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */
mod(n: BigJS): BigJS;
The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */
mod(n: BigNumberInputType): BigJS;
/** Returns a Big number whose value is the value of this Big number plus n. */
plus(n: number): BigJS;
/** Returns a Big number whose value is the value of this Big number plus n. */
plus(n: string): BigJS;
/** Returns a Big number whose value is the value of this Big number plus n. */
plus(n: BigJS): BigJS;
plus(n: BigNumberInputType): BigJS;
/** Returns a Big number whose value is the value of this Big number raised to the power exp.
If exp is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM.
@@ -156,11 +94,7 @@ declare namespace BigJsLibrary {
sqrt(): BigJS;
/** Returns a Big number whose value is the value of this Big number times n. */
times(n: number): BigJS;
/** Returns a Big number whose value is the value of this Big number times n. */
times(n: string): BigJS;
/** Returns a Big number whose value is the value of this Big number times n. */
times(n: BigJS): BigJS;
times(n: BigNumberInputType): BigJS;
/** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. */
toExponential(): string;

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