From e72993b2cb4665509ab815400885ccc997986fcd Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Tue, 5 Apr 2016 18:07:16 +0100 Subject: [PATCH 01/13] Initial implementation of refactor to module pattern, still need to get karma to work and probably set up coverage reporting again. --- .gitignore | 1 + .yo-rc.json | 3 - bower.json | 26 - dist/index.d.ts | 1 + dist/index.js | 11 + dist/index.js.map | 1 + dist/ngJwtAuth.d.ts | 395 - dist/ngJwtAuth.js | 688 -- dist/ngJwtAuth.js.map | 1 - dist/ngJwtAuthInterceptor.d.ts | 16 + dist/ngJwtAuthInterceptor.js | 46 + dist/ngJwtAuthInterceptor.js.map | 1 + dist/ngJwtAuthInterfaces.d.ts | 63 + dist/ngJwtAuthInterfaces.js | 2 + dist/ngJwtAuthInterfaces.js.map | 1 + dist/ngJwtAuthService.d.ts | 257 + dist/ngJwtAuthService.js | 549 ++ dist/ngJwtAuthService.js.map | 1 + dist/ngJwtAuthServiceProvider.d.ts | 31 + dist/ngJwtAuthServiceProvider.js | 84 + dist/ngJwtAuthServiceProvider.js.map | 1 + index.js | 8 + karma.conf.js | 16 +- package.json | 44 +- src/index.ts | 13 + src/ngJwtAuthInterceptor.ts | 90 +- src/ngJwtAuthInterfaces.ts | 158 +- src/ngJwtAuthService.ts | 1103 +-- src/ngJwtAuthServiceProvider.ts | 143 +- test/{test.ts => test.spec.ts} | 89 +- tsconfig.build.json | 22 + tsconfig.test.json | 21 + tsd.json | 48 - typings.json | 18 + typings/angularjs/angular-cookies.d.ts | 63 - typings/angularjs/angular-mocks.d.ts | 239 - typings/angularjs/angular.d.ts | 1715 ----- .../chai-as-promised/chai-as-promised.d.ts | 36 - typings/chai/chai.d.ts | 308 - typings/chance/chance.d.ts | 213 - typings/jquery/jquery.d.ts | 3170 -------- typings/lodash/lodash.d.ts | 6696 ----------------- typings/mocha/mocha.d.ts | 214 - typings/moment/moment-node.d.ts | 483 -- typings/moment/moment.d.ts | 8 - typings/sinon-chai/sinon-chai.d.ts | 84 - typings/sinon/sinon.d.ts | 420 -- typings/tsd.d.ts | 13 - 48 files changed, 1967 insertions(+), 15647 deletions(-) delete mode 100644 .yo-rc.json delete mode 100644 bower.json create mode 100644 dist/index.d.ts create mode 100644 dist/index.js create mode 100644 dist/index.js.map delete mode 100644 dist/ngJwtAuth.d.ts delete mode 100644 dist/ngJwtAuth.js delete mode 100644 dist/ngJwtAuth.js.map create mode 100644 dist/ngJwtAuthInterceptor.d.ts create mode 100644 dist/ngJwtAuthInterceptor.js create mode 100644 dist/ngJwtAuthInterceptor.js.map create mode 100644 dist/ngJwtAuthInterfaces.d.ts create mode 100644 dist/ngJwtAuthInterfaces.js create mode 100644 dist/ngJwtAuthInterfaces.js.map create mode 100644 dist/ngJwtAuthService.d.ts create mode 100644 dist/ngJwtAuthService.js create mode 100644 dist/ngJwtAuthService.js.map create mode 100644 dist/ngJwtAuthServiceProvider.d.ts create mode 100644 dist/ngJwtAuthServiceProvider.js create mode 100644 dist/ngJwtAuthServiceProvider.js.map create mode 100644 index.js create mode 100644 src/index.ts rename test/{test.ts => test.spec.ts} (93%) create mode 100644 tsconfig.build.json create mode 100644 tsconfig.test.json delete mode 100644 tsd.json create mode 100644 typings.json delete mode 100644 typings/angularjs/angular-cookies.d.ts delete mode 100644 typings/angularjs/angular-mocks.d.ts delete mode 100644 typings/angularjs/angular.d.ts delete mode 100644 typings/chai-as-promised/chai-as-promised.d.ts delete mode 100644 typings/chai/chai.d.ts delete mode 100644 typings/chance/chance.d.ts delete mode 100644 typings/jquery/jquery.d.ts delete mode 100644 typings/lodash/lodash.d.ts delete mode 100644 typings/mocha/mocha.d.ts delete mode 100644 typings/moment/moment-node.d.ts delete mode 100644 typings/moment/moment.d.ts delete mode 100644 typings/sinon-chai/sinon-chai.d.ts delete mode 100644 typings/sinon/sinon.d.ts delete mode 100644 typings/tsd.d.ts diff --git a/.gitignore b/.gitignore index 76821ff..86f5796 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ node_modules reports tmp .idea +typings \ No newline at end of file diff --git a/.yo-rc.json b/.yo-rc.json deleted file mode 100644 index 0dd34b1..0000000 --- a/.yo-rc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "generator-bower-typescript": {} -} diff --git a/bower.json b/bower.json deleted file mode 100644 index c91c6f5..0000000 --- a/bower.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "ng-jwt-auth", - "version": "3.6.0", - "description": "Angular JSON Web Token Authentication Module", - "main": "dist/ngJwtAuth.js", - "dependencies": { - "lodash": "3.10.1", - "moment": "~2.10.3", - "angular": ">=1.4", - "angular-utf8-base64": "~0.0.5", - "angular-cookies": "~1.4.3" - }, - "devDependencies": { - "angular-mocks": "~1.4.3", - "faker": "~0.0.2", - "chance": "~0.7.6" - }, - "resolutions": { - "angular": "1.4.3" - }, - "ignore": [ - "**/.*", - "typings", - "test" - ] -} diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..51cabd3 --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1 @@ +import "angular"; diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..0cbd007 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,11 @@ +"use strict"; +require("angular"); +var ngJwtAuthServiceProvider_1 = require("./ngJwtAuthServiceProvider"); +var ngJwtAuthInterceptor_1 = require("./ngJwtAuthInterceptor"); +angular.module('ngJwtAuth', ['ab-base64', 'ngCookies']) + .provider('ngJwtAuthService', ngJwtAuthServiceProvider_1.NgJwtAuthServiceProvider) + .service('ngJwtAuthInterceptor', ngJwtAuthInterceptor_1.NgJwtAuthInterceptor) + .config(['$httpProvider', '$injector', function ($httpProvider) { + $httpProvider.interceptors.push('ngJwtAuthInterceptor'); + }]); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map new file mode 100644 index 0000000..b13e715 --- /dev/null +++ b/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,QAAO,SAAS,CAAC,CAAA;AACjB,yCAAuC,4BAA4B,CAAC,CAAA;AACpE,qCAAmC,wBAAwB,CAAC,CAAA;AAG5D,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;KAClD,QAAQ,CAAC,kBAAkB,EAAE,mDAAwB,CAAC;KACtD,OAAO,CAAC,sBAAsB,EAAE,2CAAoB,CAAC;KACrD,MAAM,CAAC,CAAC,eAAe,EAAE,WAAW,EAAE,UAAC,aAA8B;QAElE,aAAa,CAAC,YAAY,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC,CACN"} \ No newline at end of file diff --git a/dist/ngJwtAuth.d.ts b/dist/ngJwtAuth.d.ts deleted file mode 100644 index af9961f..0000000 --- a/dist/ngJwtAuth.d.ts +++ /dev/null @@ -1,395 +0,0 @@ -/// -declare module NgJwtAuth { - class NgJwtAuthInterceptor { - private $http; - private $q; - private $injector; - private ngJwtAuthService; - /** - * Construct the service with dependencies injected - * @param _$q - * @param _$injector - */ - static $inject: string[]; - constructor(_$q: ng.IQService, _$injector: ng.auto.IInjectorService); - private getNgJwtAuthService; - response: (response: ng.IHttpPromiseCallbackArg) => ng.IHttpPromiseCallbackArg; - responseError: (rejection: any) => any; - } -} -declare module NgJwtAuth { - interface INgJwtAuthService { - loggedIn: boolean; - rawToken: string; - getConfig(): INgJwtAuthServiceConfig; - init(): void; - isLoginMethod(url: string): boolean; - promptLogin(): ng.IPromise; - getUser(): Object; - getPromisedUser(): ng.IPromise; - processNewToken(rawToken: string): ng.IPromise; - loginAsUser(userIdentifier: string | number): ng.IPromise; - authenticateCredentials(username: string, password: string): ng.IPromise; - validateToken(rawToken: string): boolean; - exchangeToken(token: string): ng.IPromise; - requireCredentialsAndAuthenticate(): ng.IPromise; - registerLoginPromptFactory(promiseFactory: ILoginPromptFactory): NgJwtAuthService; - registerUserFactory(userFactory: IUserFactory): NgJwtAuthService; - logout(): void; - } - interface INgJwtAuthServiceProvider { - configure(config: INgJwtAuthServiceConfig): NgJwtAuthServiceProvider; - } - interface IEndpointDefinition { - base?: string; - login?: string; - loginAsUser?: string; - tokenExchange?: string; - refresh?: string; - } - interface ICookieConfig { - enabled: boolean; - name?: string; - topLevelDomain?: boolean; - } - interface INgJwtAuthServiceConfig { - tokenLocation?: string; - tokenUser?: string; - apiEndpoints?: IEndpointDefinition; - storageKeyName?: string; - refreshBeforeSeconds?: number; - checkExpiryEverySeconds?: number; - cookie?: ICookieConfig; - } - interface IJwtClaims { - iss: string; - aud: string; - sub: string; - nbf?: number; - iat: number; - exp: number; - jti: string; - } - interface IJwtToken { - header: { - alg: string; - typ: string; - }; - data: IJwtClaims; - signature: string; - } - interface IUser { - userId: any; - email: string; - firstName?: string; - lastName?: string; - } - interface ICredentials { - username: string; - password: string; - } - interface ILoginPromptFactory { - (deferredCredentials: ng.IDeferred, loginSuccessPromise: ng.IPromise, currentUser: IUser): ng.IPromise; - } - interface IUserFactory { - (subClaim: string, tokenData: IJwtClaims): ng.IPromise; - } - interface IUserEventListener { - (user: IUser): void; - } - interface IBase64Service { - encode(string: string): string; - decode(string: string): string; - urldecode(string: string): string; - urldecode(string: string): string; - } -} -declare module NgJwtAuth { - class NgJwtAuthService implements INgJwtAuthService { - private config; - private $http; - private $q; - private $window; - private $interval; - private base64Service; - private $cookies; - private $location; - private userFactory; - private loginPromptFactory; - private loginListeners; - private logoutListeners; - private userLoggedInPromise; - private refreshTimerPromise; - private tokenData; - user: IUser; - loggedIn: boolean; - rawToken: string; - /** - * Construct the service with dependencies injected - * @param config - * @param $http - * @param $q - * @param $window - * @param $interval - * @param base64Service - * @param $cookies - * @param $location - */ - constructor(config: INgJwtAuthServiceConfig, $http: ng.IHttpService, $q: ng.IQService, $window: ng.IWindowService, $interval: ng.IIntervalService, base64Service: IBase64Service, $cookies: ng.cookies.ICookiesService, $location: ng.ILocationService); - /** - * Get the current configuration - * @returns {INgJwtAuthServiceConfig} - */ - getConfig(): INgJwtAuthServiceConfig; - /** - * A default implementation of the user factory if the client does not provide one - */ - private defaultUserFactory(subClaim, tokenData); - /** - * Service needs an init function so runtime configuration can occur before - * bootstrapping the service. This allows the user supplied LoginPromptFactory - * to be registered - */ - init(): ng.IPromise; - /** - * Register the refresh timer - */ - private startRefreshTimer(); - /** - * Cancel the refresh timer - */ - private cancelRefreshTimer(); - /** - * Handle token refresh timer - */ - private tickRefreshTime; - /** - * Check if the token needs to refresh now - * @returns {boolean} - */ - private tokenNeedsToRefreshNow(); - /** - * Get the endpoint for login - * @returns {string} - */ - private getLoginEndpoint(); - /** - * Get the endpoint for exchanging a token - * @returns {string} - */ - private getTokenExchangeEndpoint(); - /** - * Get the endpoint for getting a user's token (impersonation) - * @returns {string} - */ - private getLoginAsUserEndpoint(userIdentifier); - /** - * Get the endpoint for refreshing a token - * @returns {string} - */ - private getRefreshEndpoint(); - /** - * Build a authentication basic header string - * @param username - * @param password - * @returns {string} - */ - private static getAuthHeader(username, password); - /** - * Build a token header string - * @returns {string} - */ - private static getTokenHeader(token); - /** - * Get the standard header for a jwt token request - * @returns {string} - */ - private getBearerHeader(); - /** - * Build a refresh header string - * @returns {string} - */ - private getRefreshHeader(); - /** - * Retrieve the token from the remote API - * @param endpoint - * @param authHeader - * @returns {IPromise} - */ - private retrieveAndProcessToken(endpoint, authHeader); - /** - * Parse the raw token - * @param rawToken - * @returns {IJwtToken} - */ - private readToken(rawToken); - /** - * Validate JWT Token - * @param rawToken - * @returns {any} - */ - validateToken(rawToken: string): boolean; - /** - * Prompt user for their login credentials, and attempt to login - * @returns {ng.IPromise} - */ - promptLogin(): angular.IPromise; - /** - * Read and save the raw token to storage, kick off timer to attempt refresh - * @param rawToken - * @returns {IUser} - */ - processNewToken(rawToken: string): ng.IPromise; - private loadTokenFromStorage(); - /** - * Check if the endpoint is a login method (used for skipping the authentication error interceptor) - * @param url - * @returns {boolean} - */ - isLoginMethod(url: string): boolean; - getUser(): IUser; - /** - * - * @returns {IHttpPromise} - */ - getPromisedUser(): ng.IPromise; - /** - * Clear the token - */ - private clearJWTToken(); - /** - * Attempt to log in with username and password - * @param username - * @param password - * @returns {IPromise} - */ - authenticateCredentials(username: string, password: string): ng.IPromise; - /** - * Exchange an arbitrary token with a jwt token - * @param token - * @returns {ng.IPromise} - */ - exchangeToken(token: string): ng.IPromise; - /** - * Refresh an existing token - * @returns {ng.IPromise} - */ - refreshToken(): ng.IPromise; - /** - * Require that the user logs in again for a request - * 1. Check if there is already credentials promised - * 2. If not, execute the credential promise factory - * 3. Wait until the credentials are resolved - * 4. Then try to authenticateCredentials - * @returns {IPromise} - */ - requireCredentialsAndAuthenticate(): ng.IPromise; - /** - * Handle the login event - * @param user - */ - private handleLogin(user); - /** - * Find the user object within the path - * @param tokenData - * @returns {T} - */ - private getUserFromTokenData(tokenData); - /** - * Save the token - * @param rawToken - * @param tokenData - */ - private saveTokenToStorage(rawToken, tokenData); - /** - * Save to cookie - * @param rawToken - * @param tokenData - */ - private saveCookie(rawToken, tokenData); - /** - * Set the authentication token for all new requests - * @param rawToken - */ - private setJWTHeader(rawToken); - /** - * Remove the default http authorization header - */ - private unsetJWTHeader(); - /** - * Handle a request that was rejected due to unauthorised response - * 1. Require authentication - * 2. Retry the rejected $http request - * - * @param rejection - */ - handleInterceptedUnauthorisedResponse(rejection: ng.IHttpPromiseCallbackArg): ng.IPromise>; - /** - * Register the login prompt factory - * @param loginPromptFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - registerLoginPromptFactory(loginPromptFactory: ILoginPromptFactory): NgJwtAuthService; - /** - * Register the user factory for extracting a user from data - * @param userFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - registerUserFactory(userFactory: IUserFactory): NgJwtAuthService; - /** - * Clear the token and service properties - */ - logout(): void; - /** - * Register a login listener function - * @param loginListener - */ - registerLoginListener(loginListener: IUserEventListener): void; - /** - * Register a logout listener function - * @param logoutListener - */ - registerLogoutListener(logoutListener: IUserEventListener): void; - /** - * Get a user's token given their identifier - * @param userIdentifier - * @returns {ng.IPromise} - * - * Note this feature should be implemented very carefully as it is a security risk as it means users - * can log in as other users (impersonation). The responsibility is on the implementing app to strongly - * control permissions to access this endpoint to avoid security risks - */ - loginAsUser(userIdentifier: string | number): ng.IPromise; - } -} -declare module NgJwtAuth { - class Error { - name: string; - message: string; - stack: string; - constructor(message?: string); - } - class NgJwtAuthException extends Error { - message: string; - constructor(message: string); - toString(): string; - } - class NgJwtAuthTokenExpiredException extends NgJwtAuthException { - } - class NgJwtAuthCredentialsFailedException extends NgJwtAuthException { - } - class NgJwtAuthServiceProvider implements ng.IServiceProvider, INgJwtAuthServiceProvider { - private config; - /** - * Initialise the service provider - */ - constructor(); - /** - * Set the configuration - * @param config - * @returns {NgJwtAuth.NgJwtAuthServiceProvider} - */ - configure(config: IEndpointDefinition): NgJwtAuthServiceProvider; - $get: (string | (($http: any, $q: any, $window: any, $interval: any, base64: any, $cookies: any, $location: any) => NgJwtAuthService))[]; - } -} diff --git a/dist/ngJwtAuth.js b/dist/ngJwtAuth.js deleted file mode 100644 index d17a7e1..0000000 --- a/dist/ngJwtAuth.js +++ /dev/null @@ -1,688 +0,0 @@ -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var NgJwtAuth; -(function (NgJwtAuth) { - var NgJwtAuthInterceptor = (function () { - function NgJwtAuthInterceptor(_$q, _$injector) { - var _this = this; - this.getNgJwtAuthService = function () { - if (_this.ngJwtAuthService == null) { - _this.ngJwtAuthService = _this.$injector.get('ngJwtAuthService'); - } - return _this.ngJwtAuthService; - }; - this.response = function (response) { - var updateHeader = response.headers('Authorization-Update'); - if (updateHeader) { - var newToken = updateHeader.replace('Bearer ', ''); - var ngJwtAuthService = _this.getNgJwtAuthService(); - if (!ngJwtAuthService.validateToken(newToken)) { - return response; //if it is not a valid JWT, just return the response as it might be some other kind of token that is being updated. - } - ngJwtAuthService.processNewToken(newToken); - } - return response; - }; - this.responseError = function (rejection) { - var ngJwtAuthService = _this.getNgJwtAuthService(); - //if the response is on a login method, reject immediately - if (ngJwtAuthService.isLoginMethod(rejection.config.url)) { - return _this.$q.reject(rejection); - } - if (401 === rejection.status) { - return ngJwtAuthService.handleInterceptedUnauthorisedResponse(rejection); - } - return _this.$q.reject(rejection); - }; - this.$q = _$q; - this.$injector = _$injector; - } - /** - * Construct the service with dependencies injected - * @param _$q - * @param _$injector - */ - NgJwtAuthInterceptor.$inject = ['$q', '$injector']; - return NgJwtAuthInterceptor; - }()); - NgJwtAuth.NgJwtAuthInterceptor = NgJwtAuthInterceptor; -})(NgJwtAuth || (NgJwtAuth = {})); -/// -var NgJwtAuth; -(function (NgJwtAuth) { - var NgJwtAuthService = (function () { - /** - * Construct the service with dependencies injected - * @param config - * @param $http - * @param $q - * @param $window - * @param $interval - * @param base64Service - * @param $cookies - * @param $location - */ - function NgJwtAuthService(config, $http, $q, $window, $interval, base64Service, $cookies, $location) { - var _this = this; - this.config = config; - this.$http = $http; - this.$q = $q; - this.$window = $window; - this.$interval = $interval; - this.base64Service = base64Service; - this.$cookies = $cookies; - this.$location = $location; - this.loginListeners = []; - this.logoutListeners = []; - this.loggedIn = false; - /** - * Handle token refresh timer - */ - this.tickRefreshTime = function () { - if (!_this.userLoggedInPromise && _this.tokenNeedsToRefreshNow()) { - _this.refreshToken(); - } - }; - this.userFactory = this.defaultUserFactory; - } - /** - * Get the current configuration - * @returns {INgJwtAuthServiceConfig} - */ - NgJwtAuthService.prototype.getConfig = function () { - return this.config; - }; - /** - * A default implementation of the user factory if the client does not provide one - */ - NgJwtAuthService.prototype.defaultUserFactory = function (subClaim, tokenData) { - return this.$q.when(_.get(tokenData, this.config.tokenUser)); - }; - /** - * Service needs an init function so runtime configuration can occur before - * bootstrapping the service. This allows the user supplied LoginPromptFactory - * to be registered - */ - NgJwtAuthService.prototype.init = function () { - var _this = this; - //attempt to load the token from storage - return this.loadTokenFromStorage() - .then(function () { - _this.startRefreshTimer(); - return true; - }); - }; - /** - * Register the refresh timer - */ - NgJwtAuthService.prototype.startRefreshTimer = function () { - //if the timer is already set, clear it so the timing is reset - if (!!this.refreshTimerPromise) { - this.cancelRefreshTimer(); - } - this.refreshTimerPromise = this.$interval(this.tickRefreshTime, this.config.checkExpiryEverySeconds * 1000, null, false); - }; - /** - * Cancel the refresh timer - */ - NgJwtAuthService.prototype.cancelRefreshTimer = function () { - this.$interval.cancel(this.refreshTimerPromise); - this.refreshTimerPromise = null; - }; - /** - * Check if the token needs to refresh now - * @returns {boolean} - */ - NgJwtAuthService.prototype.tokenNeedsToRefreshNow = function () { - if (!this.rawToken) { - return false; //cant refresh if there isn't a token - } - var latestRefresh = moment(this.tokenData.data.exp * 1000).subtract(this.config.refreshBeforeSeconds, 'seconds'), nextRefreshOpportunity = moment().add(this.config.checkExpiryEverySeconds); - //needs to refresh if the the next time we could refresh is after the configured refresh before date - return (latestRefresh <= nextRefreshOpportunity); - }; - /** - * Get the endpoint for login - * @returns {string} - */ - NgJwtAuthService.prototype.getLoginEndpoint = function () { - return this.config.apiEndpoints.base + this.config.apiEndpoints.login; - }; - /** - * Get the endpoint for exchanging a token - * @returns {string} - */ - NgJwtAuthService.prototype.getTokenExchangeEndpoint = function () { - return this.config.apiEndpoints.base + this.config.apiEndpoints.tokenExchange; - }; - /** - * Get the endpoint for getting a user's token (impersonation) - * @returns {string} - */ - NgJwtAuthService.prototype.getLoginAsUserEndpoint = function (userIdentifier) { - return this.config.apiEndpoints.base + this.config.apiEndpoints.loginAsUser + '/' + userIdentifier; - }; - /** - * Get the endpoint for refreshing a token - * @returns {string} - */ - NgJwtAuthService.prototype.getRefreshEndpoint = function () { - return this.config.apiEndpoints.base + this.config.apiEndpoints.refresh; - }; - /** - * Build a authentication basic header string - * @param username - * @param password - * @returns {string} - */ - NgJwtAuthService.getAuthHeader = function (username, password) { - return 'Basic ' + btoa(username + ':' + password); //note btoa is NOT supported <= IE9 - }; - /** - * Build a token header string - * @returns {string} - */ - NgJwtAuthService.getTokenHeader = function (token) { - return 'Token ' + token; - }; - /** - * Get the standard header for a jwt token request - * @returns {string} - */ - NgJwtAuthService.prototype.getBearerHeader = function () { - if (!this.rawToken) { - throw new NgJwtAuth.NgJwtAuthException("Token is not set"); - } - return 'Bearer ' + this.rawToken; - }; - /** - * Build a refresh header string - * @returns {string} - */ - NgJwtAuthService.prototype.getRefreshHeader = function () { - if (!this.rawToken) { - throw new NgJwtAuth.NgJwtAuthException("Token is not set, it cannot be refreshed"); - } - return 'Bearer ' + this.rawToken; - }; - /** - * Retrieve the token from the remote API - * @param endpoint - * @param authHeader - * @returns {IPromise} - */ - NgJwtAuthService.prototype.retrieveAndProcessToken = function (endpoint, authHeader) { - var _this = this; - var requestConfig = { - method: 'GET', - url: endpoint, - headers: { - Authorization: authHeader - }, - responseType: 'json' - }; - return this.$http(requestConfig).then(function (result) { - if (result && result.data) { - var token = _.get(result.data, _this.config.tokenLocation); - if (_.isString(token)) { - return token; - } - } - return _this.$q.reject(new NgJwtAuth.NgJwtAuthException("Token could not be found in response body")); - }) - .then(function (token) { - try { - return _this.processNewToken(token); - } - catch (error) { - return _this.$q.reject(error); - } - }) - .catch(function (e) { - if (_.isError(e) || e instanceof _this.$window.Error) { - return _this.$q.reject(new NgJwtAuth.NgJwtAuthException(e.message)); - } - if (e.status === 401) { - return _this.$q.reject(new NgJwtAuth.NgJwtAuthCredentialsFailedException("Login attempt received unauthorised response")); - } - return _this.$q.reject(new NgJwtAuth.NgJwtAuthException("The API reported an error - " + e.status + " " + e.statusText)); - }); - }; - /** - * Parse the raw token - * @param rawToken - * @returns {IJwtToken} - */ - NgJwtAuthService.prototype.readToken = function (rawToken) { - if ((rawToken.match(/\./g) || []).length !== 2) { - throw new NgJwtAuth.NgJwtAuthException("Raw token is has incorrect format. Format must be of form \"[header].[data].[signature]\""); - } - var pieces = rawToken.split('.'); - var jwt = { - header: angular.fromJson(this.base64Service.urldecode(pieces[0])), - data: angular.fromJson(this.base64Service.urldecode(pieces[1])), - signature: pieces[2], - }; - return jwt; - }; - /** - * Validate JWT Token - * @param rawToken - * @returns {any} - */ - NgJwtAuthService.prototype.validateToken = function (rawToken) { - try { - var tokenData = this.readToken(rawToken); - return _.isObject(tokenData); - } - catch (e) { - return false; - } - }; - /** - * Prompt user for their login credentials, and attempt to login - * @returns {ng.IPromise} - */ - NgJwtAuthService.prototype.promptLogin = function () { - return this.requireCredentialsAndAuthenticate(); - }; - /** - * Read and save the raw token to storage, kick off timer to attempt refresh - * @param rawToken - * @returns {IUser} - */ - NgJwtAuthService.prototype.processNewToken = function (rawToken) { - var _this = this; - this.rawToken = rawToken; - this.tokenData = this.readToken(rawToken); - var expiryDate = moment(this.tokenData.data.exp * 1000); - if (expiryDate < moment()) { - throw new NgJwtAuth.NgJwtAuthTokenExpiredException("Token has expired"); - } - this.saveTokenToStorage(rawToken, this.tokenData); - this.setJWTHeader(rawToken); - this.loggedIn = true; - this.startRefreshTimer(); - var userFromToken = this.getUserFromTokenData(this.tokenData); - userFromToken.then(function (user) { return _this.handleLogin(user); }); - return userFromToken; - }; - NgJwtAuthService.prototype.loadTokenFromStorage = function () { - var rawToken = this.$window.localStorage.getItem(this.config.storageKeyName); - if (!rawToken) { - return this.$q.when("No token in storage"); - } - try { - return this.processNewToken(rawToken); - } - catch (e) { - if (e instanceof NgJwtAuth.NgJwtAuthTokenExpiredException) { - return this.requireCredentialsAndAuthenticate(); - } - return this.$q.reject(e); - } - }; - /** - * Check if the endpoint is a login method (used for skipping the authentication error interceptor) - * @param url - * @returns {boolean} - */ - NgJwtAuthService.prototype.isLoginMethod = function (url) { - var loginMethods = [ - this.getLoginEndpoint(), - this.getTokenExchangeEndpoint(), - ]; - return _.contains(loginMethods, url); - }; - NgJwtAuthService.prototype.getUser = function () { - return this.user; - }; - /** - * - * @returns {IHttpPromise} - */ - NgJwtAuthService.prototype.getPromisedUser = function () { - if (this.loggedIn) { - return this.$q.when(this.user); - } - else { - return this.requireCredentialsAndAuthenticate(); - } - }; - /** - * Clear the token - */ - NgJwtAuthService.prototype.clearJWTToken = function () { - this.rawToken = null; - this.$window.localStorage.removeItem(this.config.storageKeyName); - if (this.config.cookie.enabled) { - this.$cookies.remove(this.config.cookie.name); - } - this.unsetJWTHeader(); - }; - /** - * Attempt to log in with username and password - * @param username - * @param password - * @returns {IPromise} - */ - NgJwtAuthService.prototype.authenticateCredentials = function (username, password) { - var authHeader = NgJwtAuthService.getAuthHeader(username, password); - var endpoint = this.getLoginEndpoint(); - return this.retrieveAndProcessToken(endpoint, authHeader); - }; - /** - * Exchange an arbitrary token with a jwt token - * @param token - * @returns {ng.IPromise} - */ - NgJwtAuthService.prototype.exchangeToken = function (token) { - var authHeader = NgJwtAuthService.getTokenHeader(token); - var endpoint = this.getTokenExchangeEndpoint(); - return this.retrieveAndProcessToken(endpoint, authHeader); - }; - /** - * Refresh an existing token - * @returns {ng.IPromise} - */ - NgJwtAuthService.prototype.refreshToken = function () { - var _this = this; - var authHeader = this.getRefreshHeader(); - var endpoint = this.getRefreshEndpoint(); - return this.retrieveAndProcessToken(endpoint, authHeader) - .catch(function (err) { - _this.cancelRefreshTimer(); //if token refreshing fails, stop the refresh timer - return _this.$q.reject(err); - }); - }; - /** - * Require that the user logs in again for a request - * 1. Check if there is already credentials promised - * 2. If not, execute the credential promise factory - * 3. Wait until the credentials are resolved - * 4. Then try to authenticateCredentials - * @returns {IPromise} - */ - NgJwtAuthService.prototype.requireCredentialsAndAuthenticate = function () { - var _this = this; - if (!_.isFunction(this.loginPromptFactory)) { - throw new NgJwtAuth.NgJwtAuthException("You must set a loginPromptFactory with `ngJwtAuthService.registerLoginPromptFactory()` so the user can be prompted for their credentials"); - } - if (!this.userLoggedInPromise) { - var deferredCredentials_1 = this.$q.defer(); - var loginSuccess_1 = this.$q.defer(); - deferredCredentials_1.promise - .then(null, null, function (credentials) { - return _this.authenticateCredentials(credentials.username, credentials.password).then(function (user) { - //credentials were successful; resolve the promises - deferredCredentials_1.resolve(user); - loginSuccess_1.resolve(user); - }, function (err) { - loginSuccess_1.notify(err); - }); - }); - this.userLoggedInPromise = this.loginPromptFactory(deferredCredentials_1, loginSuccess_1.promise, this.user) - .then(function () { return loginSuccess_1.promise; }, //when the user has completed the login, chain on the login success promise - function (err) { - deferredCredentials_1.reject(); //if the user aborted login, reject the credentials promise - loginSuccess_1.reject(); - return _this.$q.reject(err); //and reject the login promise - }); - } - return this.userLoggedInPromise - .then(function () { - return _this.getUser(); - }) - .finally(function () { - if (!!_this.userLoggedInPromise) { - _this.userLoggedInPromise = null; - } - }); - }; - /** - * Handle the login event - * @param user - */ - NgJwtAuthService.prototype.handleLogin = function (user) { - _.invoke(this.loginListeners, _.call, null, user); - }; - /** - * Find the user object within the path - * @param tokenData - * @returns {T} - */ - NgJwtAuthService.prototype.getUserFromTokenData = function (tokenData) { - var _this = this; - return this.userFactory(tokenData.data.sub, tokenData.data) - .then(function (user) { - _this.user = user; - return user; - }); - }; - /** - * Save the token - * @param rawToken - * @param tokenData - */ - NgJwtAuthService.prototype.saveTokenToStorage = function (rawToken, tokenData) { - this.$window.localStorage.setItem(this.config.storageKeyName, rawToken); - if (this.config.cookie.enabled) { - this.saveCookie(rawToken, tokenData); - } - }; - /** - * Save to cookie - * @param rawToken - * @param tokenData - */ - NgJwtAuthService.prototype.saveCookie = function (rawToken, tokenData) { - var cookieKey = this.config.cookie.name, expires = new Date(tokenData.data.exp * 1000); //set the cookie expiry to the same as the jwt - if (this.config.cookie.topLevelDomain) { - var hostnameParts = this.$location.host().split('.'); - var segmentCount = 1; - var testHostname = ''; - do { - //definitely typed does not have a definition for lodash's _.takeRight - testHostname = _.takeRight(hostnameParts, segmentCount).join('.'); - segmentCount++; - this.$cookies.put(cookieKey, rawToken, { - domain: testHostname, - expiry: expires, - }); - if (this.$cookies.get(cookieKey)) { - return; //so exit here - } - } while (segmentCount < hostnameParts.length + 1); //try all the segment combinations, exit when all attempted - throw new NgJwtAuth.NgJwtAuthException("Could not set cookie for domain " + testHostname); - } - else { - this.$cookies.put(cookieKey, rawToken, { - expires: expires, - }); - } - }; - /** - * Set the authentication token for all new requests - * @param rawToken - */ - NgJwtAuthService.prototype.setJWTHeader = function (rawToken) { - this.$http.defaults.headers.common.Authorization = 'Bearer ' + rawToken; - }; - /** - * Remove the default http authorization header - */ - NgJwtAuthService.prototype.unsetJWTHeader = function () { - delete this.$http.defaults.headers.common.Authorization; - }; - /** - * Handle a request that was rejected due to unauthorised response - * 1. Require authentication - * 2. Retry the rejected $http request - * - * @param rejection - */ - NgJwtAuthService.prototype.handleInterceptedUnauthorisedResponse = function (rejection) { - var _this = this; - return this.requireCredentialsAndAuthenticate() - .then(function () { - //update with the new header - rejection.config.headers.Authorization = _this.getBearerHeader(); - return _this.$http(rejection.config); - }); - }; - /** - * Register the login prompt factory - * @param loginPromptFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - NgJwtAuthService.prototype.registerLoginPromptFactory = function (loginPromptFactory) { - if (_.isFunction(this.loginPromptFactory)) { - throw new NgJwtAuth.NgJwtAuthException("You cannot redeclare the login prompt factory"); - } - this.loginPromptFactory = loginPromptFactory; - return this; - }; - /** - * Register the user factory for extracting a user from data - * @param userFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - NgJwtAuthService.prototype.registerUserFactory = function (userFactory) { - this.userFactory = userFactory; - return this; - }; - /** - * Clear the token and service properties - */ - NgJwtAuthService.prototype.logout = function () { - this.clearJWTToken(); - this.loggedIn = false; - //call all logout listeners - _.invoke(this.logoutListeners, _.call, null, this.user); - this.user = null; - }; - /** - * Register a login listener function - * @param loginListener - */ - NgJwtAuthService.prototype.registerLoginListener = function (loginListener) { - this.loginListeners.push(loginListener); - }; - /** - * Register a logout listener function - * @param logoutListener - */ - NgJwtAuthService.prototype.registerLogoutListener = function (logoutListener) { - this.logoutListeners.push(logoutListener); - }; - /** - * Get a user's token given their identifier - * @param userIdentifier - * @returns {ng.IPromise} - * - * Note this feature should be implemented very carefully as it is a security risk as it means users - * can log in as other users (impersonation). The responsibility is on the implementing app to strongly - * control permissions to access this endpoint to avoid security risks - */ - NgJwtAuthService.prototype.loginAsUser = function (userIdentifier) { - if (!this.loggedIn) { - throw new NgJwtAuth.NgJwtAuthException("You must be logged in to retrieve a user's token"); - } - var authHeader = this.getBearerHeader(); - var endpoint = this.getLoginAsUserEndpoint(userIdentifier); - return this.retrieveAndProcessToken(endpoint, authHeader); - }; - return NgJwtAuthService; - }()); - NgJwtAuth.NgJwtAuthService = NgJwtAuthService; -})(NgJwtAuth || (NgJwtAuth = {})); -var NgJwtAuth; -(function (NgJwtAuth) { - var NgJwtAuthException = (function (_super) { - __extends(NgJwtAuthException, _super); - function NgJwtAuthException(message) { - _super.call(this, message); - this.message = message; - this.name = 'NgJwtAuthException'; - this.message = message; - this.stack = (new Error()).stack; - } - NgJwtAuthException.prototype.toString = function () { - return this.name + ': ' + this.message; - }; - return NgJwtAuthException; - }(Error)); - NgJwtAuth.NgJwtAuthException = NgJwtAuthException; - var NgJwtAuthTokenExpiredException = (function (_super) { - __extends(NgJwtAuthTokenExpiredException, _super); - function NgJwtAuthTokenExpiredException() { - _super.apply(this, arguments); - } - return NgJwtAuthTokenExpiredException; - }(NgJwtAuthException)); - NgJwtAuth.NgJwtAuthTokenExpiredException = NgJwtAuthTokenExpiredException; - var NgJwtAuthCredentialsFailedException = (function (_super) { - __extends(NgJwtAuthCredentialsFailedException, _super); - function NgJwtAuthCredentialsFailedException() { - _super.apply(this, arguments); - } - return NgJwtAuthCredentialsFailedException; - }(NgJwtAuthException)); - NgJwtAuth.NgJwtAuthCredentialsFailedException = NgJwtAuthCredentialsFailedException; - var NgJwtAuthServiceProvider = (function () { - /** - * Initialise the service provider - */ - function NgJwtAuthServiceProvider() { - this.$get = ['$http', '$q', '$window', '$interval', 'base64', '$cookies', '$location', function NgJwtAuthServiceFactory($http, $q, $window, $interval, base64, $cookies, $location) { - return new NgJwtAuth.NgJwtAuthService(this.config, $http, $q, $window, $interval, base64, $cookies, $location); - }]; - //initialise service config - this.config = { - tokenLocation: 'token', - tokenUser: '#user', - apiEndpoints: { - base: '/api/auth', - login: '/login', - tokenExchange: '/token', - loginAsUser: '/user', - refresh: '/refresh', - }, - storageKeyName: 'NgJwtAuthToken', - refreshBeforeSeconds: 60 * 2, - checkExpiryEverySeconds: 60, - cookie: { - enabled: false, - name: 'ngJwtAuthToken', - topLevelDomain: false, - } - }; - } - /** - * Set the configuration - * @param config - * @returns {NgJwtAuth.NgJwtAuthServiceProvider} - */ - NgJwtAuthServiceProvider.prototype.configure = function (config) { - var mismatchedConfig = _.difference(_.keys(config), _.keys(this.config)); - if (mismatchedConfig.length > 0) { - throw new NgJwtAuthException("Invalid properties [" + mismatchedConfig.join(',') + "] passed to config)"); - } - this.config = _.defaultsDeep(config, this.config); - return this; - }; - return NgJwtAuthServiceProvider; - }()); - NgJwtAuth.NgJwtAuthServiceProvider = NgJwtAuthServiceProvider; - angular.module('ngJwtAuth', ['ab-base64', 'ngCookies']) - .provider('ngJwtAuthService', NgJwtAuthServiceProvider) - .service('ngJwtAuthInterceptor', NgJwtAuth.NgJwtAuthInterceptor) - .config(['$httpProvider', '$injector', function ($httpProvider) { - $httpProvider.interceptors.push('ngJwtAuthInterceptor'); - }]); -})(NgJwtAuth || (NgJwtAuth = {})); - -//# sourceMappingURL=ngJwtAuth.js.map diff --git a/dist/ngJwtAuth.js.map b/dist/ngJwtAuth.js.map deleted file mode 100644 index 77d3942..0000000 --- a/dist/ngJwtAuth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["ngJwtAuthInterceptor.ts","ngJwtAuthInterfaces.ts","ngJwtAuthService.ts","ngJwtAuthServiceProvider.ts"],"names":[],"mappings":";;;;;AAAA,IAAO,SAAS,CAsEf;AAtED,WAAO,SAAS,EAAC,CAAC;IAEd;QAeI,8BAAY,GAAiB,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,GAAG,CAAC,GAAC,qBAAqB,CAAC,CAAC;YAC1G,CAAC;YAED,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;YAClD,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAML,+BAAC;IAAD,CApDA,AAoDC,IAAA;IApDY,kCAAwB,2BAoDpC,CAAA;IAID,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;SAClD,QAAQ,CAAC,kBAAkB,EAAE,wBAAwB,CAAC;SACtD,OAAO,CAAC,sBAAsB,EAAE,8BAAoB,CAAC;SACrD,MAAM,CAAC,CAAC,eAAe,EAAE,WAAW,EAAE,UAAC,aAA8B;YAElE,aAAa,CAAC,YAAY,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC,CACN;AAEL,CAAC,EA1FM,SAAS,KAAT,SAAS,QA0Ff","file":"ngJwtAuth.js","sourceRoot":"../src/"} \ No newline at end of file diff --git a/dist/ngJwtAuthInterceptor.d.ts b/dist/ngJwtAuthInterceptor.d.ts new file mode 100644 index 0000000..6723681 --- /dev/null +++ b/dist/ngJwtAuthInterceptor.d.ts @@ -0,0 +1,16 @@ +export declare class NgJwtAuthInterceptor { + private $http; + private $q; + private $injector; + private ngJwtAuthService; + /** + * Construct the service with dependencies injected + * @param _$q + * @param _$injector + */ + static $inject: string[]; + constructor(_$q: ng.IQService, _$injector: ng.auto.IInjectorService); + private getNgJwtAuthService; + response: (response: ng.IHttpPromiseCallbackArg) => ng.IHttpPromiseCallbackArg; + responseError: (rejection: any) => any; +} diff --git a/dist/ngJwtAuthInterceptor.js b/dist/ngJwtAuthInterceptor.js new file mode 100644 index 0000000..5a49385 --- /dev/null +++ b/dist/ngJwtAuthInterceptor.js @@ -0,0 +1,46 @@ +"use strict"; +var NgJwtAuthInterceptor = (function () { + function NgJwtAuthInterceptor(_$q, _$injector) { + var _this = this; + this.getNgJwtAuthService = function () { + if (_this.ngJwtAuthService == null) { + _this.ngJwtAuthService = _this.$injector.get('ngJwtAuthService'); + } + return _this.ngJwtAuthService; + }; + this.response = function (response) { + var updateHeader = response.headers('Authorization-Update'); + if (updateHeader) { + var newToken = updateHeader.replace('Bearer ', ''); + var ngJwtAuthService = _this.getNgJwtAuthService(); + if (!ngJwtAuthService.validateToken(newToken)) { + return response; //if it is not a valid JWT, just return the response as it might be some other kind of token that is being updated. + } + ngJwtAuthService.processNewToken(newToken); + } + return response; + }; + this.responseError = function (rejection) { + var ngJwtAuthService = _this.getNgJwtAuthService(); + //if the response is on a login method, reject immediately + if (ngJwtAuthService.isLoginMethod(rejection.config.url)) { + return _this.$q.reject(rejection); + } + if (401 === rejection.status) { + return ngJwtAuthService.handleInterceptedUnauthorisedResponse(rejection); + } + return _this.$q.reject(rejection); + }; + this.$q = _$q; + this.$injector = _$injector; + } + /** + * Construct the service with dependencies injected + * @param _$q + * @param _$injector + */ + NgJwtAuthInterceptor.$inject = ['$q', '$injector']; + return NgJwtAuthInterceptor; +}()); +exports.NgJwtAuthInterceptor = NgJwtAuthInterceptor; +//# sourceMappingURL=ngJwtAuthInterceptor.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthInterceptor.js.map b/dist/ngJwtAuthInterceptor.js.map new file mode 100644 index 0000000..7d1d774 --- /dev/null +++ b/dist/ngJwtAuthInterceptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ngJwtAuthInterceptor.js","sourceRoot":"","sources":["../src/ngJwtAuthInterceptor.ts"],"names":[],"mappings":";AAIA;IAeI,8BAAY,GAAgB,EAAE,UAAmC;QAfrE,iBAkEC;QA7CW,wBAAmB,GAAG;YAC1B,EAAE,CAAC,CAAC,KAAI,CAAC,gBAAgB,IAAI,IAAI,CAAC,CAAC,CAAC;gBAChC,KAAI,CAAC,gBAAgB,GAAqB,KAAI,CAAC,SAAS,CAAC,GAAG,CAAC,kBAAk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,IAAI,CAAC,SAAS,GAAG,UAAU,CAAC;IAChC,CAAC;IAXD;;;;OAIG;IACI,4BAAO,GAAG,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAqDzC,2BAAC;AAAD,CAAC,AAlED,IAkEC;AAlEY,4BAAoB,uBAkEhC,CAAA"} \ No newline at end of file diff --git a/dist/ngJwtAuthInterfaces.d.ts b/dist/ngJwtAuthInterfaces.d.ts new file mode 100644 index 0000000..e71e939 --- /dev/null +++ b/dist/ngJwtAuthInterfaces.d.ts @@ -0,0 +1,63 @@ +export interface IEndpointDefinition { + base?: string; + login?: string; + loginAsUser?: string; + tokenExchange?: string; + refresh?: string; +} +export interface ICookieConfig { + enabled: boolean; + name?: string; + topLevelDomain?: boolean; +} +export interface INgJwtAuthServiceConfig { + tokenLocation?: string; + tokenUser?: string; + apiEndpoints?: IEndpointDefinition; + storageKeyName?: string; + refreshBeforeSeconds?: number; + checkExpiryEverySeconds?: number; + cookie?: ICookieConfig; +} +export interface IJwtClaims { + iss: string; + aud: string; + sub: string; + nbf?: number; + iat: number; + exp: number; + jti: string; +} +export interface IJwtToken { + header: { + alg: string; + typ: string; + }; + data: IJwtClaims; + signature: string; +} +export interface IUser { + userId: any; + email: string; + firstName?: string; + lastName?: string; +} +export interface ICredentials { + username: string; + password: string; +} +export interface ILoginPromptFactory { + (deferredCredentials: ng.IDeferred, loginSuccessPromise: ng.IPromise, currentUser: IUser): ng.IPromise; +} +export interface IUserFactory { + (subClaim: string, tokenData: IJwtClaims): ng.IPromise; +} +export interface IUserEventListener { + (user: IUser): void; +} +export interface IBase64Service { + encode(string: string): string; + decode(string: string): string; + urldecode(string: string): string; + urldecode(string: string): string; +} diff --git a/dist/ngJwtAuthInterfaces.js b/dist/ngJwtAuthInterfaces.js new file mode 100644 index 0000000..d8b9c48 --- /dev/null +++ b/dist/ngJwtAuthInterfaces.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=ngJwtAuthInterfaces.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthInterfaces.js.map b/dist/ngJwtAuthInterfaces.js.map new file mode 100644 index 0000000..82a8ada --- /dev/null +++ b/dist/ngJwtAuthInterfaces.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ngJwtAuthInterfaces.js","sourceRoot":"","sources":["../src/ngJwtAuthInterfaces.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/ngJwtAuthService.d.ts b/dist/ngJwtAuthService.d.ts new file mode 100644 index 0000000..087aff8 --- /dev/null +++ b/dist/ngJwtAuthService.d.ts @@ -0,0 +1,257 @@ +import { IUserFactory, ILoginPromptFactory, IUserEventListener, IUser, INgJwtAuthServiceConfig, IBase64Service } from "./ngJwtAuthInterfaces"; +export declare class NgJwtAuthService { + private config; + private $http; + private $q; + private $window; + private $interval; + private base64Service; + private $cookies; + private $location; + private userFactory; + private loginPromptFactory; + private loginListeners; + private logoutListeners; + private userLoggedInPromise; + private refreshTimerPromise; + private tokenData; + user: IUser; + loggedIn: boolean; + rawToken: string; + /** + * Construct the service with dependencies injected + * @param config + * @param $http + * @param $q + * @param $window + * @param $interval + * @param base64Service + * @param $cookies + * @param $location + */ + constructor(config: INgJwtAuthServiceConfig, $http: ng.IHttpService, $q: ng.IQService, $window: ng.IWindowService, $interval: ng.IIntervalService, base64Service: IBase64Service, $cookies: ng.cookies.ICookiesService, $location: ng.ILocationService); + /** + * Get the current configuration + * @returns {INgJwtAuthServiceConfig} + */ + getConfig(): INgJwtAuthServiceConfig; + /** + * A default implementation of the user factory if the client does not provide one + */ + private defaultUserFactory(subClaim, tokenData); + /** + * Service needs an init function so runtime configuration can occur before + * bootstrapping the service. This allows the user supplied LoginPromptFactory + * to be registered + */ + init(): ng.IPromise; + /** + * Register the refresh timer + */ + private startRefreshTimer(); + /** + * Cancel the refresh timer + */ + private cancelRefreshTimer(); + /** + * Handle token refresh timer + */ + private tickRefreshTime; + /** + * Check if the token needs to refresh now + * @returns {boolean} + */ + private tokenNeedsToRefreshNow(); + /** + * Get the endpoint for login + * @returns {string} + */ + private getLoginEndpoint(); + /** + * Get the endpoint for exchanging a token + * @returns {string} + */ + private getTokenExchangeEndpoint(); + /** + * Get the endpoint for getting a user's token (impersonation) + * @returns {string} + */ + private getLoginAsUserEndpoint(userIdentifier); + /** + * Get the endpoint for refreshing a token + * @returns {string} + */ + private getRefreshEndpoint(); + /** + * Build a authentication basic header string + * @param username + * @param password + * @returns {string} + */ + private static getAuthHeader(username, password); + /** + * Build a token header string + * @returns {string} + */ + private static getTokenHeader(token); + /** + * Get the standard header for a jwt token request + * @returns {string} + */ + private getBearerHeader(); + /** + * Build a refresh header string + * @returns {string} + */ + private getRefreshHeader(); + /** + * Retrieve the token from the remote API + * @param endpoint + * @param authHeader + * @returns {IPromise} + */ + private retrieveAndProcessToken(endpoint, authHeader); + /** + * Parse the raw token + * @param rawToken + * @returns {IJwtToken} + */ + private readToken(rawToken); + /** + * Validate JWT Token + * @param rawToken + * @returns {any} + */ + validateToken(rawToken: string): boolean; + /** + * Prompt user for their login credentials, and attempt to login + * @returns {ng.IPromise} + */ + promptLogin(): angular.IPromise; + /** + * Read and save the raw token to storage, kick off timer to attempt refresh + * @param rawToken + * @returns {IUser} + */ + processNewToken(rawToken: string): ng.IPromise; + private loadTokenFromStorage(); + /** + * Check if the endpoint is a login method (used for skipping the authentication error interceptor) + * @param url + * @returns {boolean} + */ + isLoginMethod(url: string): boolean; + getUser(): IUser; + /** + * + * @returns {IHttpPromise} + */ + getPromisedUser(): ng.IPromise; + /** + * Clear the token + */ + private clearJWTToken(); + /** + * Attempt to log in with username and password + * @param username + * @param password + * @returns {IPromise} + */ + authenticateCredentials(username: string, password: string): ng.IPromise; + /** + * Exchange an arbitrary token with a jwt token + * @param token + * @returns {ng.IPromise} + */ + exchangeToken(token: string): ng.IPromise; + /** + * Refresh an existing token + * @returns {ng.IPromise} + */ + refreshToken(): ng.IPromise; + /** + * Require that the user logs in again for a request + * 1. Check if there is already credentials promised + * 2. If not, execute the credential promise factory + * 3. Wait until the credentials are resolved + * 4. Then try to authenticateCredentials + * @returns {IPromise} + */ + requireCredentialsAndAuthenticate(): ng.IPromise; + /** + * Handle the login event + * @param user + */ + private handleLogin(user); + /** + * Find the user object within the path + * @param tokenData + * @returns {T} + */ + private getUserFromTokenData(tokenData); + /** + * Save the token + * @param rawToken + * @param tokenData + */ + private saveTokenToStorage(rawToken, tokenData); + /** + * Save to cookie + * @param rawToken + * @param tokenData + */ + private saveCookie(rawToken, tokenData); + /** + * Set the authentication token for all new requests + * @param rawToken + */ + private setJWTHeader(rawToken); + /** + * Remove the default http authorization header + */ + private unsetJWTHeader(); + /** + * Handle a request that was rejected due to unauthorised response + * 1. Require authentication + * 2. Retry the rejected $http request + * + * @param rejection + */ + handleInterceptedUnauthorisedResponse(rejection: ng.IHttpPromiseCallbackArg): ng.IPromise>; + /** + * Register the login prompt factory + * @param loginPromptFactory + * @returns {NgJwtAuth.NgJwtAuthService} + */ + registerLoginPromptFactory(loginPromptFactory: ILoginPromptFactory): NgJwtAuthService; + /** + * Register the user factory for extracting a user from data + * @param userFactory + * @returns {NgJwtAuth.NgJwtAuthService} + */ + registerUserFactory(userFactory: IUserFactory): NgJwtAuthService; + /** + * Clear the token and service properties + */ + logout(): void; + /** + * Register a login listener function + * @param loginListener + */ + registerLoginListener(loginListener: IUserEventListener): void; + /** + * Register a logout listener function + * @param logoutListener + */ + registerLogoutListener(logoutListener: IUserEventListener): void; + /** + * Get a user's token given their identifier + * @param userIdentifier + * @returns {ng.IPromise} + * + * Note this feature should be implemented very carefully as it is a security risk as it means users + * can log in as other users (impersonation). The responsibility is on the implementing app to strongly + * control permissions to access this endpoint to avoid security risks + */ + loginAsUser(userIdentifier: string | number): ng.IPromise; +} diff --git a/dist/ngJwtAuthService.js b/dist/ngJwtAuthService.js new file mode 100644 index 0000000..24c56c6 --- /dev/null +++ b/dist/ngJwtAuthService.js @@ -0,0 +1,549 @@ +"use strict"; +var moment = require("moment"); +var _ = require("lodash"); +var ngJwtAuthServiceProvider_1 = require("./ngJwtAuthServiceProvider"); +var NgJwtAuthService = (function () { + /** + * Construct the service with dependencies injected + * @param config + * @param $http + * @param $q + * @param $window + * @param $interval + * @param base64Service + * @param $cookies + * @param $location + */ + function NgJwtAuthService(config, $http, $q, $window, $interval, base64Service, $cookies, $location) { + var _this = this; + this.config = config; + this.$http = $http; + this.$q = $q; + this.$window = $window; + this.$interval = $interval; + this.base64Service = base64Service; + this.$cookies = $cookies; + this.$location = $location; + this.loginListeners = []; + this.logoutListeners = []; + this.loggedIn = false; + /** + * Handle token refresh timer + */ + this.tickRefreshTime = function () { + if (!_this.userLoggedInPromise && _this.tokenNeedsToRefreshNow()) { + _this.refreshToken(); + } + }; + this.userFactory = this.defaultUserFactory; + } + /** + * Get the current configuration + * @returns {INgJwtAuthServiceConfig} + */ + NgJwtAuthService.prototype.getConfig = function () { + return this.config; + }; + /** + * A default implementation of the user factory if the client does not provide one + */ + NgJwtAuthService.prototype.defaultUserFactory = function (subClaim, tokenData) { + return this.$q.when(_.get(tokenData, this.config.tokenUser)); + }; + /** + * Service needs an init function so runtime configuration can occur before + * bootstrapping the service. This allows the user supplied LoginPromptFactory + * to be registered + */ + NgJwtAuthService.prototype.init = function () { + var _this = this; + //attempt to load the token from storage + return this.loadTokenFromStorage() + .then(function () { + _this.startRefreshTimer(); + return true; + }); + }; + /** + * Register the refresh timer + */ + NgJwtAuthService.prototype.startRefreshTimer = function () { + //if the timer is already set, clear it so the timing is reset + if (!!this.refreshTimerPromise) { + this.cancelRefreshTimer(); + } + this.refreshTimerPromise = this.$interval(this.tickRefreshTime, this.config.checkExpiryEverySeconds * 1000, null, false); + }; + /** + * Cancel the refresh timer + */ + NgJwtAuthService.prototype.cancelRefreshTimer = function () { + this.$interval.cancel(this.refreshTimerPromise); + this.refreshTimerPromise = null; + }; + /** + * Check if the token needs to refresh now + * @returns {boolean} + */ + NgJwtAuthService.prototype.tokenNeedsToRefreshNow = function () { + if (!this.rawToken) { + return false; //cant refresh if there isn't a token + } + var latestRefresh = moment(this.tokenData.data.exp * 1000).subtract(this.config.refreshBeforeSeconds, 'seconds'), nextRefreshOpportunity = moment().add(this.config.checkExpiryEverySeconds); + //needs to refresh if the the next time we could refresh is after the configured refresh before date + return (latestRefresh <= nextRefreshOpportunity); + }; + /** + * Get the endpoint for login + * @returns {string} + */ + NgJwtAuthService.prototype.getLoginEndpoint = function () { + return this.config.apiEndpoints.base + this.config.apiEndpoints.login; + }; + /** + * Get the endpoint for exchanging a token + * @returns {string} + */ + NgJwtAuthService.prototype.getTokenExchangeEndpoint = function () { + return this.config.apiEndpoints.base + this.config.apiEndpoints.tokenExchange; + }; + /** + * Get the endpoint for getting a user's token (impersonation) + * @returns {string} + */ + NgJwtAuthService.prototype.getLoginAsUserEndpoint = function (userIdentifier) { + return this.config.apiEndpoints.base + this.config.apiEndpoints.loginAsUser + '/' + userIdentifier; + }; + /** + * Get the endpoint for refreshing a token + * @returns {string} + */ + NgJwtAuthService.prototype.getRefreshEndpoint = function () { + return this.config.apiEndpoints.base + this.config.apiEndpoints.refresh; + }; + /** + * Build a authentication basic header string + * @param username + * @param password + * @returns {string} + */ + NgJwtAuthService.getAuthHeader = function (username, password) { + return 'Basic ' + btoa(username + ':' + password); //note btoa is NOT supported <= IE9 + }; + /** + * Build a token header string + * @returns {string} + */ + NgJwtAuthService.getTokenHeader = function (token) { + return 'Token ' + token; + }; + /** + * Get the standard header for a jwt token request + * @returns {string} + */ + NgJwtAuthService.prototype.getBearerHeader = function () { + if (!this.rawToken) { + throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token is not set"); + } + return 'Bearer ' + this.rawToken; + }; + /** + * Build a refresh header string + * @returns {string} + */ + NgJwtAuthService.prototype.getRefreshHeader = function () { + if (!this.rawToken) { + throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token is not set, it cannot be refreshed"); + } + return 'Bearer ' + this.rawToken; + }; + /** + * Retrieve the token from the remote API + * @param endpoint + * @param authHeader + * @returns {IPromise} + */ + NgJwtAuthService.prototype.retrieveAndProcessToken = function (endpoint, authHeader) { + var _this = this; + var requestConfig = { + method: 'GET', + url: endpoint, + headers: { + Authorization: authHeader + }, + responseType: 'json' + }; + return this.$http(requestConfig).then(function (result) { + if (result && result.data) { + var token = _.get(result.data, _this.config.tokenLocation); + if (_.isString(token)) { + return token; + } + } + return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token could not be found in response body")); + }) + .then(function (token) { + try { + return _this.processNewToken(token); + } + catch (error) { + return _this.$q.reject(error); + } + }) + .catch(function (e) { + if (_.isError(e) || e instanceof _this.$window.Error) { + return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException(e.message)); + } + if (e.status === 401) { + return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthCredentialsFailedException("Login attempt received unauthorised response")); + } + return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException("The API reported an error - " + e.status + " " + e.statusText)); + }); + }; + /** + * Parse the raw token + * @param rawToken + * @returns {IJwtToken} + */ + NgJwtAuthService.prototype.readToken = function (rawToken) { + if ((rawToken.match(/\./g) || []).length !== 2) { + throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Raw token is has incorrect format. Format must be of form \"[header].[data].[signature]\""); + } + var pieces = rawToken.split('.'); + var jwt = { + header: angular.fromJson(this.base64Service.urldecode(pieces[0])), + data: angular.fromJson(this.base64Service.urldecode(pieces[1])), + signature: pieces[2], + }; + return jwt; + }; + /** + * Validate JWT Token + * @param rawToken + * @returns {any} + */ + NgJwtAuthService.prototype.validateToken = function (rawToken) { + try { + var tokenData = this.readToken(rawToken); + return _.isObject(tokenData); + } + catch (e) { + return false; + } + }; + /** + * Prompt user for their login credentials, and attempt to login + * @returns {ng.IPromise} + */ + NgJwtAuthService.prototype.promptLogin = function () { + return this.requireCredentialsAndAuthenticate(); + }; + /** + * Read and save the raw token to storage, kick off timer to attempt refresh + * @param rawToken + * @returns {IUser} + */ + NgJwtAuthService.prototype.processNewToken = function (rawToken) { + var _this = this; + this.rawToken = rawToken; + this.tokenData = this.readToken(rawToken); + var expiryDate = moment(this.tokenData.data.exp * 1000); + if (expiryDate < moment()) { + throw new ngJwtAuthServiceProvider_1.NgJwtAuthTokenExpiredException("Token has expired"); + } + this.saveTokenToStorage(rawToken, this.tokenData); + this.setJWTHeader(rawToken); + this.loggedIn = true; + this.startRefreshTimer(); + var userFromToken = this.getUserFromTokenData(this.tokenData); + userFromToken.then(function (user) { return _this.handleLogin(user); }); + return userFromToken; + }; + NgJwtAuthService.prototype.loadTokenFromStorage = function () { + var rawToken = this.$window.localStorage.getItem(this.config.storageKeyName); + if (!rawToken) { + return this.$q.when("No token in storage"); + } + try { + return this.processNewToken(rawToken); + } + catch (e) { + if (e instanceof ngJwtAuthServiceProvider_1.NgJwtAuthTokenExpiredException) { + return this.requireCredentialsAndAuthenticate(); + } + return this.$q.reject(e); + } + }; + /** + * Check if the endpoint is a login method (used for skipping the authentication error interceptor) + * @param url + * @returns {boolean} + */ + NgJwtAuthService.prototype.isLoginMethod = function (url) { + var loginMethods = [ + this.getLoginEndpoint(), + this.getTokenExchangeEndpoint(), + ]; + return _.contains(loginMethods, url); + }; + NgJwtAuthService.prototype.getUser = function () { + return this.user; + }; + /** + * + * @returns {IHttpPromise} + */ + NgJwtAuthService.prototype.getPromisedUser = function () { + if (this.loggedIn) { + return this.$q.when(this.user); + } + else { + return this.requireCredentialsAndAuthenticate(); + } + }; + /** + * Clear the token + */ + NgJwtAuthService.prototype.clearJWTToken = function () { + this.rawToken = null; + this.$window.localStorage.removeItem(this.config.storageKeyName); + if (this.config.cookie.enabled) { + this.$cookies.remove(this.config.cookie.name); + } + this.unsetJWTHeader(); + }; + /** + * Attempt to log in with username and password + * @param username + * @param password + * @returns {IPromise} + */ + NgJwtAuthService.prototype.authenticateCredentials = function (username, password) { + var authHeader = NgJwtAuthService.getAuthHeader(username, password); + var endpoint = this.getLoginEndpoint(); + return this.retrieveAndProcessToken(endpoint, authHeader); + }; + /** + * Exchange an arbitrary token with a jwt token + * @param token + * @returns {ng.IPromise} + */ + NgJwtAuthService.prototype.exchangeToken = function (token) { + var authHeader = NgJwtAuthService.getTokenHeader(token); + var endpoint = this.getTokenExchangeEndpoint(); + return this.retrieveAndProcessToken(endpoint, authHeader); + }; + /** + * Refresh an existing token + * @returns {ng.IPromise} + */ + NgJwtAuthService.prototype.refreshToken = function () { + var _this = this; + var authHeader = this.getRefreshHeader(); + var endpoint = this.getRefreshEndpoint(); + return this.retrieveAndProcessToken(endpoint, authHeader) + .catch(function (err) { + _this.cancelRefreshTimer(); //if token refreshing fails, stop the refresh timer + return _this.$q.reject(err); + }); + }; + /** + * Require that the user logs in again for a request + * 1. Check if there is already credentials promised + * 2. If not, execute the credential promise factory + * 3. Wait until the credentials are resolved + * 4. Then try to authenticateCredentials + * @returns {IPromise} + */ + NgJwtAuthService.prototype.requireCredentialsAndAuthenticate = function () { + var _this = this; + if (!_.isFunction(this.loginPromptFactory)) { + throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You must set a loginPromptFactory with `ngJwtAuthService.registerLoginPromptFactory()` so the user can be prompted for their credentials"); + } + if (!this.userLoggedInPromise) { + var deferredCredentials_1 = this.$q.defer(); + var loginSuccess_1 = this.$q.defer(); + deferredCredentials_1.promise + .then(null, null, function (credentials) { + return _this.authenticateCredentials(credentials.username, credentials.password).then(function (user) { + //credentials were successful; resolve the promises + deferredCredentials_1.resolve(user); + loginSuccess_1.resolve(user); + }, function (err) { + loginSuccess_1.notify(err); + }); + }); + this.userLoggedInPromise = this.loginPromptFactory(deferredCredentials_1, loginSuccess_1.promise, this.user) + .then(function () { return loginSuccess_1.promise; }, //when the user has completed the login, chain on the login success promise + function (err) { + deferredCredentials_1.reject(); //if the user aborted login, reject the credentials promise + loginSuccess_1.reject(); + return _this.$q.reject(err); //and reject the login promise + }); + } + return this.userLoggedInPromise + .then(function () { + return _this.getUser(); + }) + .finally(function () { + if (!!_this.userLoggedInPromise) { + _this.userLoggedInPromise = null; + } + }); + }; + /** + * Handle the login event + * @param user + */ + NgJwtAuthService.prototype.handleLogin = function (user) { + _.invoke(this.loginListeners, _.call, null, user); + }; + /** + * Find the user object within the path + * @param tokenData + * @returns {T} + */ + NgJwtAuthService.prototype.getUserFromTokenData = function (tokenData) { + var _this = this; + return this.userFactory(tokenData.data.sub, tokenData.data) + .then(function (user) { + _this.user = user; + return user; + }); + }; + /** + * Save the token + * @param rawToken + * @param tokenData + */ + NgJwtAuthService.prototype.saveTokenToStorage = function (rawToken, tokenData) { + this.$window.localStorage.setItem(this.config.storageKeyName, rawToken); + if (this.config.cookie.enabled) { + this.saveCookie(rawToken, tokenData); + } + }; + /** + * Save to cookie + * @param rawToken + * @param tokenData + */ + NgJwtAuthService.prototype.saveCookie = function (rawToken, tokenData) { + var cookieKey = this.config.cookie.name, expires = new Date(tokenData.data.exp * 1000); //set the cookie expiry to the same as the jwt + if (this.config.cookie.topLevelDomain) { + var hostnameParts = this.$location.host().split('.'); + var segmentCount = 1; + var testHostname = ''; + do { + testHostname = _.takeRight(hostnameParts, segmentCount).join('.'); + segmentCount++; + this.$cookies.put(cookieKey, rawToken, { + domain: testHostname, + expires: expires, + }); + if (this.$cookies.get(cookieKey)) { + return; //so exit here + } + } while (segmentCount < hostnameParts.length + 1); //try all the segment combinations, exit when all attempted + throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Could not set cookie for domain " + testHostname); + } + else { + this.$cookies.put(cookieKey, rawToken, { + expires: expires, + }); + } + }; + /** + * Set the authentication token for all new requests + * @param rawToken + */ + NgJwtAuthService.prototype.setJWTHeader = function (rawToken) { + this.$http.defaults.headers.common.Authorization = 'Bearer ' + rawToken; + }; + /** + * Remove the default http authorization header + */ + NgJwtAuthService.prototype.unsetJWTHeader = function () { + delete this.$http.defaults.headers.common.Authorization; + }; + /** + * Handle a request that was rejected due to unauthorised response + * 1. Require authentication + * 2. Retry the rejected $http request + * + * @param rejection + */ + NgJwtAuthService.prototype.handleInterceptedUnauthorisedResponse = function (rejection) { + var _this = this; + return this.requireCredentialsAndAuthenticate() + .then(function () { + //update with the new header + rejection.config.headers['Authorization'] = _this.getBearerHeader(); + return _this.$http(rejection.config); + }); + }; + /** + * Register the login prompt factory + * @param loginPromptFactory + * @returns {NgJwtAuth.NgJwtAuthService} + */ + NgJwtAuthService.prototype.registerLoginPromptFactory = function (loginPromptFactory) { + if (_.isFunction(this.loginPromptFactory)) { + throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You cannot redeclare the login prompt factory"); + } + this.loginPromptFactory = loginPromptFactory; + return this; + }; + /** + * Register the user factory for extracting a user from data + * @param userFactory + * @returns {NgJwtAuth.NgJwtAuthService} + */ + NgJwtAuthService.prototype.registerUserFactory = function (userFactory) { + this.userFactory = userFactory; + return this; + }; + /** + * Clear the token and service properties + */ + NgJwtAuthService.prototype.logout = function () { + this.clearJWTToken(); + this.loggedIn = false; + //call all logout listeners with user that is logged out + _.invoke(this.logoutListeners, _.call, null, this.user); + this.user = null; + }; + /** + * Register a login listener function + * @param loginListener + */ + NgJwtAuthService.prototype.registerLoginListener = function (loginListener) { + this.loginListeners.push(loginListener); + }; + /** + * Register a logout listener function + * @param logoutListener + */ + NgJwtAuthService.prototype.registerLogoutListener = function (logoutListener) { + this.logoutListeners.push(logoutListener); + }; + /** + * Get a user's token given their identifier + * @param userIdentifier + * @returns {ng.IPromise} + * + * Note this feature should be implemented very carefully as it is a security risk as it means users + * can log in as other users (impersonation). The responsibility is on the implementing app to strongly + * control permissions to access this endpoint to avoid security risks + */ + NgJwtAuthService.prototype.loginAsUser = function (userIdentifier) { + if (!this.loggedIn) { + throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You must be logged in to retrieve a user's token"); + } + var authHeader = this.getBearerHeader(); + var endpoint = this.getLoginAsUserEndpoint(userIdentifier); + return this.retrieveAndProcessToken(endpoint, authHeader); + }; + return NgJwtAuthService; +}()); +exports.NgJwtAuthService = NgJwtAuthService; +//# sourceMappingURL=ngJwtAuthService.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthService.js.map b/dist/ngJwtAuthService.js.map new file mode 100644 index 0000000..d81f96f --- /dev/null +++ b/dist/ngJwtAuthService.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ngJwtAuthService.js","sourceRoot":"","sources":["../src/ngJwtAuthService.ts"],"names":[],"mappings":";AAAA,IAAY,MAAM,WAAM,QAAQ,CAAC,CAAA;AACjC,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAa5B,yCAGO,4BAA4B,CAAC,CAAA;AAEpC;IAiBI;;;;;;;;;;OAUG;IACH,0BAAoB,MAA8B,EAC9B,KAAqB,EACrB,EAAe,EACf,OAAyB,EACzB,SAA6B,EAC7B,aAA4B,EAC5B,QAAmC,EACnC,SAA6B;QAnCrD,iBAyrBC;QA7pBuB,WAAM,GAAN,MAAM,CAAwB;QAC9B,UAAK,GAAL,KAAK,CAAgB;QACrB,OAAE,GAAF,EAAE,CAAa;QACf,YAAO,GAAP,OAAO,CAAkB;QACzB,cAAS,GAAT,SAAS,CAAoB;QAC7B,kBAAa,GAAb,aAAa,CAAe;QAC5B,aAAQ,GAAR,QAAQ,CAA2B;QACnC,cAAS,GAAT,SAAS,CAAoB;QA9BzC,mBAAc,GAAwB,EAAE,CAAC;QACzC,oBAAe,GAAwB,EAAE,CAAC;QAQ3C,aAAQ,GAAW,KAAK,CAAC;QA8EhC;;WAEG;QACK,oBAAe,GAAG;YAEtB,EAAE,CAAC,CAAC,CAAC,KAAI,CAAC,mBAAmB,IAAI,KAAI,CAAC,sBAAsB,EAAE,CAAC,CAAC,CAAC;gBAC7D,KAAI,CAAC,YAAY,EAAE,CAAC;YACxB,CAAC;QAEL,CAAC,CAAC;QAhEE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,kBAAkB,CAAC;IAE/C,CAAC;IAED;;;OAGG;IACI,oCAAS,GAAhB;QACI,MAAM,CAAC,IAAI,CAAC,MAAM,CAA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,CAAC,CAAC;IAC9D,CAAC;IAEL,uBAAC;AAAD,CAAC,AAzrBD,IAyrBC;AAzrBY,wBAAgB,mBAyrB5B,CAAA"} \ No newline at end of file diff --git a/dist/ngJwtAuthServiceProvider.d.ts b/dist/ngJwtAuthServiceProvider.d.ts new file mode 100644 index 0000000..1cd1303 --- /dev/null +++ b/dist/ngJwtAuthServiceProvider.d.ts @@ -0,0 +1,31 @@ +import { IEndpointDefinition } from "./ngJwtAuthInterfaces"; +import { NgJwtAuthService } from "./ngJwtAuthService"; +export declare class Error { + name: string; + message: string; + stack: string; + constructor(message?: string); +} +export declare class NgJwtAuthException extends Error { + message: string; + constructor(message: string); + toString(): string; +} +export declare class NgJwtAuthTokenExpiredException extends NgJwtAuthException { +} +export declare class NgJwtAuthCredentialsFailedException extends NgJwtAuthException { +} +export declare class NgJwtAuthServiceProvider implements ng.IServiceProvider { + private config; + /** + * Initialise the service provider + */ + constructor(); + /** + * Set the configuration + * @param config + * @returns {NgJwtAuth.NgJwtAuthServiceProvider} + */ + configure(config: IEndpointDefinition): NgJwtAuthServiceProvider; + $get: (string | (($http: any, $q: any, $window: any, $interval: any, base64: any, $cookies: any, $location: any) => NgJwtAuthService))[]; +} diff --git a/dist/ngJwtAuthServiceProvider.js b/dist/ngJwtAuthServiceProvider.js new file mode 100644 index 0000000..5e4810f --- /dev/null +++ b/dist/ngJwtAuthServiceProvider.js @@ -0,0 +1,84 @@ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var ngJwtAuthService_1 = require("./ngJwtAuthService"); +var NgJwtAuthException = (function (_super) { + __extends(NgJwtAuthException, _super); + function NgJwtAuthException(message) { + _super.call(this, message); + this.message = message; + this.name = 'NgJwtAuthException'; + this.message = message; + this.stack = (new Error()).stack; + } + NgJwtAuthException.prototype.toString = function () { + return this.name + ': ' + this.message; + }; + return NgJwtAuthException; +}(Error)); +exports.NgJwtAuthException = NgJwtAuthException; +var NgJwtAuthTokenExpiredException = (function (_super) { + __extends(NgJwtAuthTokenExpiredException, _super); + function NgJwtAuthTokenExpiredException() { + _super.apply(this, arguments); + } + return NgJwtAuthTokenExpiredException; +}(NgJwtAuthException)); +exports.NgJwtAuthTokenExpiredException = NgJwtAuthTokenExpiredException; +var NgJwtAuthCredentialsFailedException = (function (_super) { + __extends(NgJwtAuthCredentialsFailedException, _super); + function NgJwtAuthCredentialsFailedException() { + _super.apply(this, arguments); + } + return NgJwtAuthCredentialsFailedException; +}(NgJwtAuthException)); +exports.NgJwtAuthCredentialsFailedException = NgJwtAuthCredentialsFailedException; +var NgJwtAuthServiceProvider = (function () { + /** + * Initialise the service provider + */ + function NgJwtAuthServiceProvider() { + this.$get = ['$http', '$q', '$window', '$interval', 'base64', '$cookies', '$location', function NgJwtAuthServiceFactory($http, $q, $window, $interval, base64, $cookies, $location) { + return new ngJwtAuthService_1.NgJwtAuthService(this.config, $http, $q, $window, $interval, base64, $cookies, $location); + }]; + //initialise service config + this.config = { + tokenLocation: 'token', + tokenUser: '#user', + apiEndpoints: { + base: '/api/auth', + login: '/login', + tokenExchange: '/token', + loginAsUser: '/user', + refresh: '/refresh', + }, + storageKeyName: 'NgJwtAuthToken', + refreshBeforeSeconds: 60 * 2, + checkExpiryEverySeconds: 60, + cookie: { + enabled: false, + name: 'ngJwtAuthToken', + topLevelDomain: false, + } + }; + } + /** + * Set the configuration + * @param config + * @returns {NgJwtAuth.NgJwtAuthServiceProvider} + */ + NgJwtAuthServiceProvider.prototype.configure = function (config) { + var mismatchedConfig = _.difference(_.keys(config), _.keys(this.config)); + if (mismatchedConfig.length > 0) { + throw new NgJwtAuthException("Invalid properties [" + mismatchedConfig.join(',') + "] passed to config)"); + } + this.config = _.defaultsDeep(config, this.config); + return this; + }; + return NgJwtAuthServiceProvider; +}()); +exports.NgJwtAuthServiceProvider = NgJwtAuthServiceProvider; +//# sourceMappingURL=ngJwtAuthServiceProvider.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthServiceProvider.js.map b/dist/ngJwtAuthServiceProvider.js.map new file mode 100644 index 0000000..62bdaba --- /dev/null +++ b/dist/ngJwtAuthServiceProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ngJwtAuthServiceProvider.js","sourceRoot":"","sources":["../src/ngJwtAuthServiceProvider.ts"],"names":[],"mappings":";;;;;;AAEA,iCAA+B,oBAAoB,CAAC,CAAA;AASpD;IAAwC,sCAAK;IAEzC,4BAAmB,OAAe;QAC9B,kBAAM,OAAO,CAAC,CAAC;QADA,YAAO,GAAP,OAAO,CAAQ;QAE9B,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,CAAM,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC;IAC1C,CAAC;IACD,qCAAQ,GAAR;QACI,MAAM,CAAC,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC;IAC3C,CAAC;IACL,yBAAC;AAAD,CAAC,AAXD,CAAwC,KAAK,GAW5C;AAXY,0BAAkB,qBAW9B,CAAA;AAED;IAAoD,kDAAkB;IAAtE;QAAoD,8BAAkB;IAAC,CAAC;IAAD,qCAAC;AAAD,CAAC,AAAxE,CAAoD,kBAAkB,GAAE;AAA3D,sCAA8B,iCAA6B,CAAA;AACxE;IAAyD,uDAAkB;IAA3E;QAAyD,8BAAkB;IAAC,CAAC;IAAD,0CAAC;AAAD,CAAC,AAA7E,CAAyD,kBAAkB,GAAE;AAAhE,2CAAmC,sCAA6B,CAAA;AAE7E;IAII;;OAEG;IACH;QAyCO,SAAI,GAAG,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,iCAAiC,KAAK,EAAE,EA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C;IAChB,CAAC;IAML,+BAAC;AAAD,CAAC,AApDD,IAoDC;AApDY,gCAAwB,2BAoDpC,CAAA"} \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..2c4ebde --- /dev/null +++ b/index.js @@ -0,0 +1,8 @@ +// Should already be required, here for clarity +require('angular'); + +// Now load Angular Material +require('./angular-jwt-auth'); + +// Export namespace +module.exports = 'ngJwtAuth'; diff --git a/karma.conf.js b/karma.conf.js index 1d11f8b..9e2e875 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,13 +1,20 @@ +require('phantomjs-polyfill'); + module.exports = function(config) { config.set({ frameworks: ['chai-as-promised', 'mocha', 'sinon', 'sinon-chai'], - //plugins: ['karma-mocha', 'karma-phantomjs-launcher', 'karma-coverage', 'karma-sinon-chai'], preprocessors: { - 'dist/**/*.js': ['coverage'] + 'dist/**/*.js': ['commonjs', 'coverage'] }, + files: [ + './node_modules/phantomjs-polyfill/bind-polyfill.js', + 'dist/**/*.js', + 'test/tmp/test/**/*.spec.js' + ], + reporters: ['mocha', 'coverage'], port: 9018, @@ -16,7 +23,8 @@ module.exports = function(config) { autoWatch: false, browsers: [ - 'PhantomJS' + // 'PhantomJS', + 'Chrome', ], client: { @@ -26,7 +34,7 @@ module.exports = function(config) { } }, - logLevel: config.LOG_INFO, + logLevel: config.LOG_VERBOSE, coverageReporter: { // specify a common output directory diff --git a/package.json b/package.json index e96185c..f53db2e 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,26 @@ { "name": "angular-jwt-auth", - "version": "3.6.0", + "version": "4.0.0", "description": "Angular JSON Web Token Authentication Module", "main": "dist/ngJwtAuth.js", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/spira/angular-jwt-auth" + }, "scripts": { - "test": "gulp test", - "postinstall": "./node_modules/.bin/tsd reinstall --config tsd.json && ./node_modules/.bin/bower install" + "build": "tsc --project tsconfig.build.json --declaration --pretty --listFiles", + "pretest": "tsc --project tsconfig.test.json", + "test": "karma start --NODE_ENV=test", + "postinstall": "typings i" + }, + "dependencies": { + "angular": "^1.5.3", + "angular-cookies": "^1.5.3", + "angular-utf8-base64": "0.0.2", + "lodash": "^4.8.2", + "moment": "^2.12.0" }, - "dependencies": {}, "devDependencies": { "bower": "^1.4.1", "del": "^1.2.0", @@ -32,27 +45,30 @@ "gulp-typescript": "^2.7.6", "gulp-util": "^3.0.5", "inquirer": "^0.8.5", - "istanbul": "bryanforbes/istanbul#source-map-resolve", - "karma": "^0.12.31", + "karma": "0.13.19", "karma-chai": "^0.1.0", "karma-chai-as-promised": "^0.1.2", "karma-chai-plugins": "^0.6.0", "karma-chrome-launcher": "^0.2.0", - "karma-coverage": "gotwarlost/karma-coverage.git#source-lookup", + "karma-commonjs": "0.0.13", + "karma-coverage": "0.5.3", "karma-mocha": "^0.2.0", "karma-mocha-reporter": "^1.0.2", - "karma-phantomjs-launcher": "^0.1.4", - "sinon": "1.14.1", + "karma-phantomjs-launcher": "1.0.0", "karma-sinon": "^1.0.4", - "karma-sinon-chai": "^1.0.0", - "lodash": "^3.9.3", - "main-bower-files": "^2.8.2", + "karma-sinon-chai": "^1.2.0", + "karma-sourcemap-loader": "0.3.7", + "karma-spec-reporter": "0.0.23", + "lolex": "^1.4.0", "merge2": "^0.3.6", "minimatch": "^2.0.8", "mocha": "^2.2.5", + "phantomjs-polyfill": "0.0.1", + "phantomjs-prebuilt": "2.1.3", "requirejs": "^2.1.18", "run-sequence": "^1.1.1", - "tsd": "^0.6.3", - "typescript": "^1.5.0-beta" + "sinon": "^1.17.3", + "typescript": "^1.8.9", + "typings": "^0.7.12" } } diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..28908f0 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,13 @@ +import "angular"; +import {NgJwtAuthServiceProvider} from "./ngJwtAuthServiceProvider"; +import {NgJwtAuthInterceptor} from "./ngJwtAuthInterceptor"; + + +angular.module('ngJwtAuth', ['ab-base64', 'ngCookies']) + .provider('ngJwtAuthService', NgJwtAuthServiceProvider) + .service('ngJwtAuthInterceptor', NgJwtAuthInterceptor) + .config(['$httpProvider', '$injector', ($httpProvider:ng.IHttpProvider) => { + + $httpProvider.interceptors.push('ngJwtAuthInterceptor'); + }]) +; \ No newline at end of file diff --git a/src/ngJwtAuthInterceptor.ts b/src/ngJwtAuthInterceptor.ts index 2ce5273..05b17ca 100644 --- a/src/ngJwtAuthInterceptor.ts +++ b/src/ngJwtAuthInterceptor.ts @@ -1,71 +1,71 @@ -module NgJwtAuth { - export class NgJwtAuthInterceptor { - //list injected dependencies - private $http: ng.IHttpService; - private $q: ng.IQService; - private $injector: ng.auto.IInjectorService; - private ngJwtAuthService: NgJwtAuthService; +import {NgJwtAuthService} from "./ngJwtAuthService"; +export class NgJwtAuthInterceptor { - /** - * Construct the service with dependencies injected - * @param _$q - * @param _$injector - */ - static $inject = ['$q', '$injector']; - constructor(_$q: ng.IQService, _$injector: ng.auto.IInjectorService) { + //list injected dependencies + private $http:ng.IHttpService; + private $q:ng.IQService; + private $injector:ng.auto.IInjectorService; + private ngJwtAuthService:NgJwtAuthService; - this.$q = _$q; - this.$injector = _$injector; - } + /** + * Construct the service with dependencies injected + * @param _$q + * @param _$injector + */ + static $inject = ['$q', '$injector']; - private getNgJwtAuthService = (): NgJwtAuthService=> { - if (this.ngJwtAuthService == null) { - this.ngJwtAuthService = this.$injector.get('ngJwtAuthService'); - } - return this.ngJwtAuthService; - }; + constructor(_$q:ng.IQService, _$injector:ng.auto.IInjectorService) { - public response = (response: ng.IHttpPromiseCallbackArg): ng.IHttpPromiseCallbackArg => { + this.$q = _$q; + this.$injector = _$injector; + } - let updateHeader = response.headers('Authorization-Update'); + private getNgJwtAuthService = ():NgJwtAuthService=> { + if (this.ngJwtAuthService == null) { + this.ngJwtAuthService = this.$injector.get('ngJwtAuthService'); + } + return this.ngJwtAuthService; + }; - if (updateHeader){ + public response = (response:ng.IHttpPromiseCallbackArg):ng.IHttpPromiseCallbackArg => { - let newToken = updateHeader.replace('Bearer ', ''); + let updateHeader = response.headers('Authorization-Update'); - let ngJwtAuthService = this.getNgJwtAuthService(); + if (updateHeader) { - if (!ngJwtAuthService.validateToken(newToken)){ - return response; //if it is not a valid JWT, just return the response as it might be some other kind of token that is being updated. - } + let newToken = updateHeader.replace('Bearer ', ''); - ngJwtAuthService.processNewToken(newToken); + let ngJwtAuthService = this.getNgJwtAuthService(); + + if (!ngJwtAuthService.validateToken(newToken)) { + return response; //if it is not a valid JWT, just return the response as it might be some other kind of token that is being updated. } - return response; - }; + ngJwtAuthService.processNewToken(newToken); + } - public responseError = (rejection):any => { + return response; + }; - let ngJwtAuthService = this.getNgJwtAuthService(); + public responseError = (rejection):any => { - //if the response is on a login method, reject immediately - if (ngJwtAuthService.isLoginMethod(rejection.config.url)){ + let ngJwtAuthService = this.getNgJwtAuthService(); - return this.$q.reject(rejection); - } + //if the response is on a login method, reject immediately + if (ngJwtAuthService.isLoginMethod(rejection.config.url)) { - if (401 === rejection.status) { + return this.$q.reject(rejection); + } - return ngJwtAuthService.handleInterceptedUnauthorisedResponse(rejection); - } + if (401 === rejection.status) { - return this.$q.reject(rejection); + return ngJwtAuthService.handleInterceptedUnauthorisedResponse(rejection); } + return this.$q.reject(rejection); } -} +} \ No newline at end of file diff --git a/src/ngJwtAuthInterfaces.ts b/src/ngJwtAuthInterfaces.ts index 5a3dab9..b7ca940 100644 --- a/src/ngJwtAuthInterfaces.ts +++ b/src/ngJwtAuthInterfaces.ts @@ -1,107 +1,75 @@ -/// - -module NgJwtAuth { - - export interface INgJwtAuthService { - loggedIn: boolean; - rawToken:string; - getConfig():INgJwtAuthServiceConfig; - init():void; - isLoginMethod(url:string): boolean; - promptLogin():ng.IPromise; - getUser():Object; - getPromisedUser():ng.IPromise; - processNewToken(rawToken:string):ng.IPromise; - loginAsUser(userIdentifier:string|number):ng.IPromise; - authenticateCredentials(username:string, password:string):ng.IPromise; - validateToken(rawToken:string):boolean - exchangeToken(token:string):ng.IPromise; - requireCredentialsAndAuthenticate():ng.IPromise; - registerLoginPromptFactory(promiseFactory:ILoginPromptFactory):NgJwtAuthService; - registerUserFactory(userFactory:IUserFactory):NgJwtAuthService; - logout():void; - } - - export interface INgJwtAuthServiceProvider { - configure(config:INgJwtAuthServiceConfig): NgJwtAuthServiceProvider; - } - - export interface IEndpointDefinition { - base?: string; - login?: string; - loginAsUser?: string; - tokenExchange?: string; - refresh?: string; - } - - export interface ICookieConfig { - enabled: boolean; - name?: string; - topLevelDomain?:boolean; - } - - export interface INgJwtAuthServiceConfig { - tokenLocation?: string; - tokenUser?: string; - apiEndpoints?: IEndpointDefinition; - storageKeyName?: string; - refreshBeforeSeconds?: number; - checkExpiryEverySeconds?: number; - cookie?:ICookieConfig; - } - +export interface IEndpointDefinition { + base?:string; + login?:string; + loginAsUser?:string; + tokenExchange?:string; + refresh?:string; +} +export interface ICookieConfig { + enabled:boolean; + name?:string; + topLevelDomain?:boolean; +} - export interface IJwtClaims { - iss: string; - aud: string; - sub: string; - nbf?: number; - iat: number; - exp: number; - jti: string; - } +export interface INgJwtAuthServiceConfig { + tokenLocation?:string; + tokenUser?:string; + apiEndpoints?:IEndpointDefinition; + storageKeyName?:string; + refreshBeforeSeconds?:number; + checkExpiryEverySeconds?:number; + cookie?:ICookieConfig; +} - export interface IJwtToken { +export interface IJwtClaims { + iss:string; + aud:string; + sub:string; + nbf?:number; + iat:number; + exp:number; + jti:string; +} - header: { - alg: string, - typ: string - }; - data: IJwtClaims; - signature: string; - } +export interface IJwtToken { - export interface IUser { - userId: any; - email: string, - firstName?: string, - lastName?: string, - } + header:{ + alg:string, + typ:string + }; + data:IJwtClaims; + signature:string; +} - export interface ICredentials { - username: string; - password: string; - } +export interface IUser { + userId:any; + email:string, + firstName?:string, + lastName?:string, +} - export interface ILoginPromptFactory { - (deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:IUser): ng.IPromise; - } +export interface ICredentials { + username:string; + password:string; +} - export interface IUserFactory { - (subClaim:string, tokenData:IJwtClaims): ng.IPromise; - } +export interface ILoginPromptFactory { + (deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:IUser):ng.IPromise; +} - export interface IUserEventListener { - (user:IUser):void; - } +export interface IUserFactory { + (subClaim:string, tokenData:IJwtClaims):ng.IPromise; +} - export interface IBase64Service { - encode(string:string):string; - decode(string:string):string; +export interface IUserEventListener { + (user:IUser):void; +} - urldecode(string:string):string; - urldecode(string:string):string; - } +export interface IBase64Service { + encode(string:string):string; + decode(string:string):string; -} + urldecode(string:string):string; + urldecode(string:string):string; +} \ No newline at end of file diff --git a/src/ngJwtAuthService.ts b/src/ngJwtAuthService.ts index 68ccf6c..e9683a1 100644 --- a/src/ngJwtAuthService.ts +++ b/src/ngJwtAuthService.ts @@ -1,487 +1,502 @@ -module NgJwtAuth { - - export class NgJwtAuthService implements INgJwtAuthService { - - //private properties - private userFactory:IUserFactory; - private loginPromptFactory:ILoginPromptFactory; - private loginListeners:IUserEventListener[] = []; - private logoutListeners:IUserEventListener[] = []; - private userLoggedInPromise:ng.IPromise; - - private refreshTimerPromise:ng.IPromise; - private tokenData:IJwtToken; - - //public properties - public user:IUser; - public loggedIn:boolean = false; - public rawToken:string; - - /** - * Construct the service with dependencies injected - * @param config - * @param $http - * @param $q - * @param $window - * @param $interval - * @param base64Service - * @param $cookies - * @param $location - */ - constructor(private config:INgJwtAuthServiceConfig, - private $http:ng.IHttpService, - private $q:ng.IQService, - private $window:ng.IWindowService, - private $interval:ng.IIntervalService, - private base64Service:IBase64Service, - private $cookies:ng.cookies.ICookiesService, - private $location:ng.ILocationService) { - - this.userFactory = this.defaultUserFactory; +import * as moment from "moment"; +import * as _ from "lodash"; + +import { + IUserFactory, + ILoginPromptFactory, + IUserEventListener, + IJwtToken, + IUser, + INgJwtAuthServiceConfig, + IBase64Service, + IJwtClaims, ICredentials, +} from "./ngJwtAuthInterfaces"; + +import { + NgJwtAuthException, NgJwtAuthCredentialsFailedException, + NgJwtAuthTokenExpiredException +} from "./ngJwtAuthServiceProvider"; + +export class NgJwtAuthService { + + //private properties + private userFactory:IUserFactory; + private loginPromptFactory:ILoginPromptFactory; + private loginListeners:IUserEventListener[] = []; + private logoutListeners:IUserEventListener[] = []; + private userLoggedInPromise:ng.IPromise; + + private refreshTimerPromise:ng.IPromise; + private tokenData:IJwtToken; + + //public properties + public user:IUser; + public loggedIn:boolean = false; + public rawToken:string; + + /** + * Construct the service with dependencies injected + * @param config + * @param $http + * @param $q + * @param $window + * @param $interval + * @param base64Service + * @param $cookies + * @param $location + */ + constructor(private config:INgJwtAuthServiceConfig, + private $http:ng.IHttpService, + private $q:ng.IQService, + private $window:ng.IWindowService, + private $interval:ng.IIntervalService, + private base64Service:IBase64Service, + private $cookies:ng.cookies.ICookiesService, + private $location:ng.ILocationService) { + + this.userFactory = this.defaultUserFactory; - } + } - /** - * Get the current configuration - * @returns {INgJwtAuthServiceConfig} - */ - public getConfig():INgJwtAuthServiceConfig { - return this.config; - } + /** + * Get the current configuration + * @returns {INgJwtAuthServiceConfig} + */ + public getConfig():INgJwtAuthServiceConfig { + return this.config; + } - /** - * A default implementation of the user factory if the client does not provide one - */ - private defaultUserFactory(subClaim:string, tokenData:IJwtClaims):ng.IPromise { + /** + * A default implementation of the user factory if the client does not provide one + */ + private defaultUserFactory(subClaim:string, tokenData:IJwtClaims):ng.IPromise { - return this.$q.when(_.get(tokenData, this.config.tokenUser)); - } - - /** - * Service needs an init function so runtime configuration can occur before - * bootstrapping the service. This allows the user supplied LoginPromptFactory - * to be registered - */ - public init():ng.IPromise { - - //attempt to load the token from storage - return this.loadTokenFromStorage() - .then(() => { - this.startRefreshTimer(); - return true; - }); + return this.$q.when(_.get(tokenData, this.config.tokenUser)); + } - } + /** + * Service needs an init function so runtime configuration can occur before + * bootstrapping the service. This allows the user supplied LoginPromptFactory + * to be registered + */ + public init():ng.IPromise { - /** - * Register the refresh timer - */ - private startRefreshTimer() { - //if the timer is already set, clear it so the timing is reset - if (!!this.refreshTimerPromise){ - this.cancelRefreshTimer(); - } - this.refreshTimerPromise = this.$interval(this.tickRefreshTime, this.config.checkExpiryEverySeconds * 1000, null, false); - } + //attempt to load the token from storage + return this.loadTokenFromStorage() + .then(() => { + this.startRefreshTimer(); + return true; + }); + } - /** - * Cancel the refresh timer - */ - private cancelRefreshTimer():void { - this.$interval.cancel(this.refreshTimerPromise); - this.refreshTimerPromise = null; + /** + * Register the refresh timer + */ + private startRefreshTimer() { + //if the timer is already set, clear it so the timing is reset + if (!!this.refreshTimerPromise) { + this.cancelRefreshTimer(); } + this.refreshTimerPromise = this.$interval(this.tickRefreshTime, this.config.checkExpiryEverySeconds * 1000, null, false); + } - /** - * Handle token refresh timer - */ - private tickRefreshTime = ():void => { - - if (!this.userLoggedInPromise && this.tokenNeedsToRefreshNow()) { - this.refreshToken(); - } + /** + * Cancel the refresh timer + */ + private cancelRefreshTimer():void { + this.$interval.cancel(this.refreshTimerPromise); + this.refreshTimerPromise = null; + } - }; + /** + * Handle token refresh timer + */ + private tickRefreshTime = ():void => { - /** - * Check if the token needs to refresh now - * @returns {boolean} - */ - private tokenNeedsToRefreshNow():boolean { + if (!this.userLoggedInPromise && this.tokenNeedsToRefreshNow()) { + this.refreshToken(); + } - if (!this.rawToken) { - return false; //cant refresh if there isn't a token - } + }; - let latestRefresh = moment(this.tokenData.data.exp * 1000).subtract(this.config.refreshBeforeSeconds, 'seconds'), - nextRefreshOpportunity = moment().add(this.config.checkExpiryEverySeconds) - ; + /** + * Check if the token needs to refresh now + * @returns {boolean} + */ + private tokenNeedsToRefreshNow():boolean { - //needs to refresh if the the next time we could refresh is after the configured refresh before date - return (latestRefresh <= nextRefreshOpportunity); + if (!this.rawToken) { + return false; //cant refresh if there isn't a token } - /** - * Get the endpoint for login - * @returns {string} - */ - private getLoginEndpoint():string { - return this.config.apiEndpoints.base + this.config.apiEndpoints.login; - } + let latestRefresh = moment(this.tokenData.data.exp * 1000).subtract(this.config.refreshBeforeSeconds, 'seconds'), + nextRefreshOpportunity = moment().add(this.config.checkExpiryEverySeconds) + ; - /** - * Get the endpoint for exchanging a token - * @returns {string} - */ - private getTokenExchangeEndpoint():string { - return this.config.apiEndpoints.base + this.config.apiEndpoints.tokenExchange; - } + //needs to refresh if the the next time we could refresh is after the configured refresh before date + return (latestRefresh <= nextRefreshOpportunity); + } - /** - * Get the endpoint for getting a user's token (impersonation) - * @returns {string} - */ - private getLoginAsUserEndpoint(userIdentifier:string|number):string { - return this.config.apiEndpoints.base + this.config.apiEndpoints.loginAsUser + '/' + userIdentifier; - } + /** + * Get the endpoint for login + * @returns {string} + */ + private getLoginEndpoint():string { + return this.config.apiEndpoints.base + this.config.apiEndpoints.login; + } - /** - * Get the endpoint for refreshing a token - * @returns {string} - */ - private getRefreshEndpoint():string { - return this.config.apiEndpoints.base + this.config.apiEndpoints.refresh; - } + /** + * Get the endpoint for exchanging a token + * @returns {string} + */ + private getTokenExchangeEndpoint():string { + return this.config.apiEndpoints.base + this.config.apiEndpoints.tokenExchange; + } - /** - * Build a authentication basic header string - * @param username - * @param password - * @returns {string} - */ - private static getAuthHeader(username:string, password:string):string { - return 'Basic ' + btoa(username + ':' + password); //note btoa is NOT supported <= IE9 - } + /** + * Get the endpoint for getting a user's token (impersonation) + * @returns {string} + */ + private getLoginAsUserEndpoint(userIdentifier:string|number):string { + return this.config.apiEndpoints.base + this.config.apiEndpoints.loginAsUser + '/' + userIdentifier; + } - /** - * Build a token header string - * @returns {string} - */ - private static getTokenHeader(token:string):string { - return 'Token ' + token; - } + /** + * Get the endpoint for refreshing a token + * @returns {string} + */ + private getRefreshEndpoint():string { + return this.config.apiEndpoints.base + this.config.apiEndpoints.refresh; + } - /** - * Get the standard header for a jwt token request - * @returns {string} - */ - private getBearerHeader():string { - if (!this.rawToken) { - throw new NgJwtAuthException("Token is not set"); - } + /** + * Build a authentication basic header string + * @param username + * @param password + * @returns {string} + */ + private static getAuthHeader(username:string, password:string):string { + return 'Basic ' + btoa(username + ':' + password); //note btoa is NOT supported <= IE9 + } + + /** + * Build a token header string + * @returns {string} + */ + private static getTokenHeader(token:string):string { + return 'Token ' + token; + } - return 'Bearer ' + this.rawToken; + /** + * Get the standard header for a jwt token request + * @returns {string} + */ + private getBearerHeader():string { + if (!this.rawToken) { + throw new NgJwtAuthException("Token is not set"); } - /** - * Build a refresh header string - * @returns {string} - */ - private getRefreshHeader():string { - if (!this.rawToken) { - throw new NgJwtAuthException("Token is not set, it cannot be refreshed"); - } + return 'Bearer ' + this.rawToken; + } - return 'Bearer ' + this.rawToken; + /** + * Build a refresh header string + * @returns {string} + */ + private getRefreshHeader():string { + if (!this.rawToken) { + throw new NgJwtAuthException("Token is not set, it cannot be refreshed"); } - /** - * Retrieve the token from the remote API - * @param endpoint - * @param authHeader - * @returns {IPromise} - */ - private retrieveAndProcessToken(endpoint:string, authHeader:string):ng.IPromise { - - var requestConfig:ng.IRequestConfig = { - method: 'GET', - url: endpoint, - headers: { - Authorization: authHeader - }, - responseType: 'json' - }; - - return this.$http(requestConfig).then((result:ng.IHttpPromiseCallbackArg) => { - - if (result && result.data){ - let token = _.get(result.data, this.config.tokenLocation); - - if (_.isString(token)){ - return token; - } - } + return 'Bearer ' + this.rawToken; + } - return this.$q.reject(new NgJwtAuthException("Token could not be found in response body")); - }) - .then((token:string) => { + /** + * Retrieve the token from the remote API + * @param endpoint + * @param authHeader + * @returns {IPromise} + */ + private retrieveAndProcessToken(endpoint:string, authHeader:string):ng.IPromise { + + var requestConfig:ng.IRequestConfig = { + method: 'GET', + url: endpoint, + headers: { + Authorization: authHeader + }, + responseType: 'json' + }; - try { + return this.$http(requestConfig).then((result:ng.IHttpPromiseCallbackArg) => { - return this.processNewToken(token); + if (result && result.data) { + let token = _.get(result.data, this.config.tokenLocation); - } catch (error) { - return this.$q.reject(error); + if (_.isString(token)) { + return token; } + } - }) - .catch((e:any) => { + return this.$q.reject(new NgJwtAuthException("Token could not be found in response body")); + }) + .then((token:string) => { - if (_.isError(e) || e instanceof (this.$window).Error) { - return this.$q.reject(new NgJwtAuthException(e.message)); - } + try { - if (e.status === 401) { + return this.processNewToken(token); - return this.$q.reject(new NgJwtAuthCredentialsFailedException("Login attempt received unauthorised response")); - } + } catch (error) { + return this.$q.reject(error); + } - return this.$q.reject(new NgJwtAuthException("The API reported an error - " + e.status + " " + e.statusText)); - }) + }) + .catch((e:any) => { - } + if (_.isError(e) || e instanceof (this.$window).Error) { + return this.$q.reject(new NgJwtAuthException(e.message)); + } - /** - * Parse the raw token - * @param rawToken - * @returns {IJwtToken} - */ - private readToken(rawToken:string):IJwtToken { + if (e.status === 401) { - if ((rawToken.match(/\./g) || []).length !== 2) { - throw new NgJwtAuthException("Raw token is has incorrect format. Format must be of form \"[header].[data].[signature]\""); - } + return this.$q.reject(new NgJwtAuthCredentialsFailedException("Login attempt received unauthorised response")); + } + + return this.$q.reject(new NgJwtAuthException("The API reported an error - " + e.status + " " + e.statusText)); + }) - var pieces = rawToken.split('.'); + } - var jwt:IJwtToken = { - header: angular.fromJson(this.base64Service.urldecode(pieces[0])), - data: angular.fromJson(this.base64Service.urldecode(pieces[1])), - signature: pieces[2], - }; + /** + * Parse the raw token + * @param rawToken + * @returns {IJwtToken} + */ + private readToken(rawToken:string):IJwtToken { - return jwt; + if ((rawToken.match(/\./g) || []).length !== 2) { + throw new NgJwtAuthException("Raw token is has incorrect format. Format must be of form \"[header].[data].[signature]\""); } - /** - * Validate JWT Token - * @param rawToken - * @returns {any} - */ - public validateToken(rawToken:string):boolean { + var pieces = rawToken.split('.'); - try { - let tokenData = this.readToken(rawToken); + var jwt:IJwtToken = { + header: angular.fromJson(this.base64Service.urldecode(pieces[0])), + data: angular.fromJson(this.base64Service.urldecode(pieces[1])), + signature: pieces[2], + }; - return _.isObject(tokenData); + return jwt; + } - } catch (e) { - return false; - } + /** + * Validate JWT Token + * @param rawToken + * @returns {any} + */ + public validateToken(rawToken:string):boolean { - } + try { + let tokenData = this.readToken(rawToken); - /** - * Prompt user for their login credentials, and attempt to login - * @returns {ng.IPromise} - */ - public promptLogin():angular.IPromise { + return _.isObject(tokenData); - return this.requireCredentialsAndAuthenticate(); + } catch (e) { + return false; } - /** - * Read and save the raw token to storage, kick off timer to attempt refresh - * @param rawToken - * @returns {IUser} - */ - public processNewToken(rawToken:string):ng.IPromise { + } - this.rawToken = rawToken; + /** + * Prompt user for their login credentials, and attempt to login + * @returns {ng.IPromise} + */ + public promptLogin():angular.IPromise { - this.tokenData = this.readToken(rawToken); + return this.requireCredentialsAndAuthenticate(); + } - var expiryDate = moment(this.tokenData.data.exp * 1000); + /** + * Read and save the raw token to storage, kick off timer to attempt refresh + * @param rawToken + * @returns {IUser} + */ + public processNewToken(rawToken:string):ng.IPromise { - if (expiryDate < moment()) { - throw new NgJwtAuthTokenExpiredException("Token has expired"); - } + this.rawToken = rawToken; - this.saveTokenToStorage(rawToken, this.tokenData); + this.tokenData = this.readToken(rawToken); - this.setJWTHeader(rawToken); + var expiryDate = moment(this.tokenData.data.exp * 1000); - this.loggedIn = true; + if (expiryDate < moment()) { + throw new NgJwtAuthTokenExpiredException("Token has expired"); + } - this.startRefreshTimer(); + this.saveTokenToStorage(rawToken, this.tokenData); - let userFromToken = this.getUserFromTokenData(this.tokenData); + this.setJWTHeader(rawToken); - userFromToken.then((user) => this.handleLogin(user)); + this.loggedIn = true; - return userFromToken; - } + this.startRefreshTimer(); - private loadTokenFromStorage():ng.IPromise { + let userFromToken = this.getUserFromTokenData(this.tokenData); - let rawToken = this.$window.localStorage.getItem(this.config.storageKeyName); + userFromToken.then((user) => this.handleLogin(user)); - if (!rawToken) { - return this.$q.when("No token in storage"); - } + return userFromToken; + } - try { - return this.processNewToken(rawToken); - } catch (e) { - if (e instanceof NgJwtAuthTokenExpiredException) { - return this.requireCredentialsAndAuthenticate(); - } + private loadTokenFromStorage():ng.IPromise { - return this.$q.reject(e); + let rawToken = this.$window.localStorage.getItem(this.config.storageKeyName); + + if (!rawToken) { + return this.$q.when("No token in storage"); + } + try { + return this.processNewToken(rawToken); + } catch (e) { + if (e instanceof NgJwtAuthTokenExpiredException) { + return this.requireCredentialsAndAuthenticate(); } + return this.$q.reject(e); + } - /** - * Check if the endpoint is a login method (used for skipping the authentication error interceptor) - * @param url - * @returns {boolean} - */ - public isLoginMethod(url:string):boolean { + } - let loginMethods = [ - this.getLoginEndpoint(), - this.getTokenExchangeEndpoint(), - ]; + /** + * Check if the endpoint is a login method (used for skipping the authentication error interceptor) + * @param url + * @returns {boolean} + */ + public isLoginMethod(url:string):boolean { - return _.contains(loginMethods, url); - } + let loginMethods = [ + this.getLoginEndpoint(), + this.getTokenExchangeEndpoint(), + ]; - public getUser():IUser { - return this.user; - } + return _.contains(loginMethods, url); + } - /** - * - * @returns {IHttpPromise} - */ - public getPromisedUser():ng.IPromise { + public getUser():IUser { + return this.user; + } - if (this.loggedIn) { //if we are already logged in, resolve the user immediately - return this.$q.when(this.user); - } else { //otherwise require login then return the user - return this.requireCredentialsAndAuthenticate(); - } + /** + * + * @returns {IHttpPromise} + */ + public getPromisedUser():ng.IPromise { + if (this.loggedIn) { //if we are already logged in, resolve the user immediately + return this.$q.when(this.user); + } else { //otherwise require login then return the user + return this.requireCredentialsAndAuthenticate(); } + } - /** - * Clear the token - */ - private clearJWTToken():void { - this.rawToken = null; - this.$window.localStorage.removeItem(this.config.storageKeyName); - - if (this.config.cookie.enabled) { + /** + * Clear the token + */ + private clearJWTToken():void { + this.rawToken = null; + this.$window.localStorage.removeItem(this.config.storageKeyName); - this.$cookies.remove(this.config.cookie.name); - } + if (this.config.cookie.enabled) { - this.unsetJWTHeader(); + this.$cookies.remove(this.config.cookie.name); } - /** - * Attempt to log in with username and password - * @param username - * @param password - * @returns {IPromise} - */ - public authenticateCredentials(username:string, password:string):ng.IPromise { + this.unsetJWTHeader(); + } - let authHeader = NgJwtAuthService.getAuthHeader(username, password); - let endpoint = this.getLoginEndpoint(); + /** + * Attempt to log in with username and password + * @param username + * @param password + * @returns {IPromise} + */ + public authenticateCredentials(username:string, password:string):ng.IPromise { - return this.retrieveAndProcessToken(endpoint, authHeader); + let authHeader = NgJwtAuthService.getAuthHeader(username, password); + let endpoint = this.getLoginEndpoint(); - } + return this.retrieveAndProcessToken(endpoint, authHeader); - /** - * Exchange an arbitrary token with a jwt token - * @param token - * @returns {ng.IPromise} - */ - public exchangeToken(token:string):ng.IPromise { + } - let authHeader = NgJwtAuthService.getTokenHeader(token); - let endpoint = this.getTokenExchangeEndpoint(); + /** + * Exchange an arbitrary token with a jwt token + * @param token + * @returns {ng.IPromise} + */ + public exchangeToken(token:string):ng.IPromise { - return this.retrieveAndProcessToken(endpoint, authHeader); - } + let authHeader = NgJwtAuthService.getTokenHeader(token); + let endpoint = this.getTokenExchangeEndpoint(); - /** - * Refresh an existing token - * @returns {ng.IPromise} - */ - public refreshToken():ng.IPromise { + return this.retrieveAndProcessToken(endpoint, authHeader); + } - let authHeader = this.getRefreshHeader(); - let endpoint = this.getRefreshEndpoint(); + /** + * Refresh an existing token + * @returns {ng.IPromise} + */ + public refreshToken():ng.IPromise { - return this.retrieveAndProcessToken(endpoint, authHeader) - .catch((err) => { - this.cancelRefreshTimer(); //if token refreshing fails, stop the refresh timer - return this.$q.reject(err); - }); + let authHeader = this.getRefreshHeader(); + let endpoint = this.getRefreshEndpoint(); - } + return this.retrieveAndProcessToken(endpoint, authHeader) + .catch((err) => { + this.cancelRefreshTimer(); //if token refreshing fails, stop the refresh timer + return this.$q.reject(err); + }); - /** - * Require that the user logs in again for a request - * 1. Check if there is already credentials promised - * 2. If not, execute the credential promise factory - * 3. Wait until the credentials are resolved - * 4. Then try to authenticateCredentials - * @returns {IPromise} - */ - public requireCredentialsAndAuthenticate():ng.IPromise { - - if (!_.isFunction(this.loginPromptFactory)) { - throw new NgJwtAuthException("You must set a loginPromptFactory with `ngJwtAuthService.registerLoginPromptFactory()` so the user can be prompted for their credentials"); - } + } - if (!this.userLoggedInPromise) { - let deferredCredentials = this.$q.defer(); + /** + * Require that the user logs in again for a request + * 1. Check if there is already credentials promised + * 2. If not, execute the credential promise factory + * 3. Wait until the credentials are resolved + * 4. Then try to authenticateCredentials + * @returns {IPromise} + */ + public requireCredentialsAndAuthenticate():ng.IPromise { - let loginSuccess = this.$q.defer(); + if (!_.isFunction(this.loginPromptFactory)) { + throw new NgJwtAuthException("You must set a loginPromptFactory with `ngJwtAuthService.registerLoginPromptFactory()` so the user can be prompted for their credentials"); + } + + if (!this.userLoggedInPromise) { + let deferredCredentials = this.$q.defer(); - deferredCredentials.promise - .then(null, null, (credentials:ICredentials) => { //check on notify + let loginSuccess = this.$q.defer(); - return this.authenticateCredentials(credentials.username, credentials.password).then((user) => { - //credentials were successful; resolve the promises - deferredCredentials.resolve(user); - loginSuccess.resolve(user); - }, (err) => { //pass notification to loginSuccess - loginSuccess.notify(err); - }); - }) - ; + deferredCredentials.promise + .then(null, null, (credentials:ICredentials) => { //check on notify - this.userLoggedInPromise = this.loginPromptFactory(deferredCredentials, loginSuccess.promise, this.user) - .then( + return this.authenticateCredentials(credentials.username, credentials.password).then((user) => { + //credentials were successful; resolve the promises + deferredCredentials.resolve(user); + loginSuccess.resolve(user); + }, (err) => { //pass notification to loginSuccess + loginSuccess.notify(err); + }); + }) + ; + + this.userLoggedInPromise = this.loginPromptFactory(deferredCredentials, loginSuccess.promise, this.user) + .then( () => loginSuccess.promise, //when the user has completed the login, chain on the login success promise (err) => { deferredCredentials.reject(); //if the user aborted login, reject the credentials promise @@ -489,220 +504,214 @@ module NgJwtAuth { return this.$q.reject(err); //and reject the login promise } ) - ; - - } + ; - return this.userLoggedInPromise - .then(() => { - return this.getUser(); - }) - .finally(() => { + } - if (!!this.userLoggedInPromise) { //deregister the userLoggedInPromise - this.userLoggedInPromise = null; - } + return this.userLoggedInPromise + .then(() => { + return this.getUser(); + }) + .finally(() => { - }) - ; + if (!!this.userLoggedInPromise) { //deregister the userLoggedInPromise + this.userLoggedInPromise = null; + } - } + }) + ; - /** - * Handle the login event - * @param user - */ - private handleLogin(user:IUser):void { + } - _.invoke(this.loginListeners, _.call, null, user); + /** + * Handle the login event + * @param user + */ + private handleLogin(user:IUser):void { - } + _.invoke(this.loginListeners, _.call, null, user); - /** - * Find the user object within the path - * @param tokenData - * @returns {T} - */ - private getUserFromTokenData(tokenData:IJwtToken):ng.IPromise { - - return this.userFactory(tokenData.data.sub, tokenData.data) - .then((user:IUser) => { - this.user = user; - return user; - }); - } + } - /** - * Save the token - * @param rawToken - * @param tokenData - */ - private saveTokenToStorage(rawToken:string, tokenData:IJwtToken):void { + /** + * Find the user object within the path + * @param tokenData + * @returns {T} + */ + private getUserFromTokenData(tokenData:IJwtToken):ng.IPromise { + + return this.userFactory(tokenData.data.sub, tokenData.data) + .then((user:IUser) => { + this.user = user; + return user; + }); + } - this.$window.localStorage.setItem(this.config.storageKeyName, rawToken); + /** + * Save the token + * @param rawToken + * @param tokenData + */ + private saveTokenToStorage(rawToken:string, tokenData:IJwtToken):void { - if (this.config.cookie.enabled) { - this.saveCookie(rawToken, tokenData); - } + this.$window.localStorage.setItem(this.config.storageKeyName, rawToken); + if (this.config.cookie.enabled) { + this.saveCookie(rawToken, tokenData); } - /** - * Save to cookie - * @param rawToken - * @param tokenData - */ - private saveCookie(rawToken, tokenData):void { - - let cookieKey = this.config.cookie.name, - expires = new Date(tokenData.data.exp*1000); //set the cookie expiry to the same as the jwt - - if (this.config.cookie.topLevelDomain) { - - let hostnameParts = this.$location.host().split('.'); - let segmentCount = 1; - let testHostname = ''; - do { - //definitely typed does not have a definition for lodash's _.takeRight - testHostname = (_).takeRight(hostnameParts, segmentCount).join('.'); - - segmentCount++; - this.$cookies.put(cookieKey, rawToken, { - domain: testHostname, - expiry: expires, - }); + } - if (this.$cookies.get(cookieKey)) { //saving the cookie worked, it must be the top level domain - return; //so exit here - } + /** + * Save to cookie + * @param rawToken + * @param tokenData + */ + private saveCookie(rawToken, tokenData):void { - } while (segmentCount < hostnameParts.length + 1); //try all the segment combinations, exit when all attempted + let cookieKey = this.config.cookie.name, + expires = new Date(tokenData.data.exp * 1000); //set the cookie expiry to the same as the jwt - throw new NgJwtAuthException("Could not set cookie for domain " + testHostname); + if (this.config.cookie.topLevelDomain) { - } else { //use the default domain + let hostnameParts = this.$location.host().split('.'); + let segmentCount = 1; + let testHostname = ''; + do { + testHostname = _.takeRight(hostnameParts, segmentCount).join('.'); + segmentCount++; this.$cookies.put(cookieKey, rawToken, { + domain: testHostname, expires: expires, }); - } - } + if (this.$cookies.get(cookieKey)) { //saving the cookie worked, it must be the top level domain + return; //so exit here + } - /** - * Set the authentication token for all new requests - * @param rawToken - */ - private setJWTHeader(rawToken:String):void { + } while (segmentCount < hostnameParts.length + 1); //try all the segment combinations, exit when all attempted - this.$http.defaults.headers.common.Authorization = 'Bearer ' + rawToken; - } + throw new NgJwtAuthException("Could not set cookie for domain " + testHostname); - /** - * Remove the default http authorization header - */ - private unsetJWTHeader():void { - delete this.$http.defaults.headers.common.Authorization; - } + } else { //use the default domain + + this.$cookies.put(cookieKey, rawToken, { + expires: expires, + }); - /** - * Handle a request that was rejected due to unauthorised response - * 1. Require authentication - * 2. Retry the rejected $http request - * - * @param rejection - */ - public handleInterceptedUnauthorisedResponse(rejection:ng.IHttpPromiseCallbackArg):ng.IPromise> { - - return this.requireCredentialsAndAuthenticate() - .then(() => { - //update with the new header - rejection.config.headers.Authorization = this.getBearerHeader(); - - return this.$http(rejection.config); - }) - ; } + } - /** - * Register the login prompt factory - * @param loginPromptFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - public registerLoginPromptFactory(loginPromptFactory:ILoginPromptFactory):NgJwtAuthService { + /** + * Set the authentication token for all new requests + * @param rawToken + */ + private setJWTHeader(rawToken:String):void { - if (_.isFunction(this.loginPromptFactory)) { - throw new NgJwtAuthException("You cannot redeclare the login prompt factory"); - } + this.$http.defaults.headers.common.Authorization = 'Bearer ' + rawToken; + } - this.loginPromptFactory = loginPromptFactory; + /** + * Remove the default http authorization header + */ + private unsetJWTHeader():void { + delete this.$http.defaults.headers.common.Authorization; + } - return this; - } + /** + * Handle a request that was rejected due to unauthorised response + * 1. Require authentication + * 2. Retry the rejected $http request + * + * @param rejection + */ + public handleInterceptedUnauthorisedResponse(rejection:ng.IHttpPromiseCallbackArg):ng.IPromise> { + + return this.requireCredentialsAndAuthenticate() + .then(() => { + //update with the new header + rejection.config.headers['Authorization'] = this.getBearerHeader(); + + return this.$http(rejection.config); + }); + } + /** + * Register the login prompt factory + * @param loginPromptFactory + * @returns {NgJwtAuth.NgJwtAuthService} + */ + public registerLoginPromptFactory(loginPromptFactory:ILoginPromptFactory):NgJwtAuthService { - /** - * Register the user factory for extracting a user from data - * @param userFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - public registerUserFactory(userFactory:IUserFactory):NgJwtAuthService { + if (_.isFunction(this.loginPromptFactory)) { + throw new NgJwtAuthException("You cannot redeclare the login prompt factory"); + } - this.userFactory = userFactory; + this.loginPromptFactory = loginPromptFactory; - return this; - } + return this; + } - /** - * Clear the token and service properties - */ - public logout():void { - this.clearJWTToken(); - this.loggedIn = false; + /** + * Register the user factory for extracting a user from data + * @param userFactory + * @returns {NgJwtAuth.NgJwtAuthService} + */ + public registerUserFactory(userFactory:IUserFactory):NgJwtAuthService { - //call all logout listeners with user that is logged out - _.invoke(this.logoutListeners, _.call, null, this.user); - this.user = null; - } + this.userFactory = userFactory; + return this; + } - /** - * Register a login listener function - * @param loginListener - */ - public registerLoginListener(loginListener:IUserEventListener):void { - this.loginListeners.push(loginListener); - } + /** + * Clear the token and service properties + */ + public logout():void { + this.clearJWTToken(); + this.loggedIn = false; - /** - * Register a logout listener function - * @param logoutListener - */ - public registerLogoutListener(logoutListener:IUserEventListener):void { - this.logoutListeners.push(logoutListener); - } + //call all logout listeners with user that is logged out + _.invoke(this.logoutListeners, _.call, null, this.user); + this.user = null; + } - /** - * Get a user's token given their identifier - * @param userIdentifier - * @returns {ng.IPromise} - * - * Note this feature should be implemented very carefully as it is a security risk as it means users - * can log in as other users (impersonation). The responsibility is on the implementing app to strongly - * control permissions to access this endpoint to avoid security risks - */ - public loginAsUser(userIdentifier:string|number):ng.IPromise { - - if (!this.loggedIn){ - throw new NgJwtAuthException("You must be logged in to retrieve a user's token"); - } + /** + * Register a login listener function + * @param loginListener + */ + public registerLoginListener(loginListener:IUserEventListener):void { + this.loginListeners.push(loginListener); + } + + /** + * Register a logout listener function + * @param logoutListener + */ + public registerLogoutListener(logoutListener:IUserEventListener):void { + this.logoutListeners.push(logoutListener); + } - let authHeader = this.getBearerHeader(); - let endpoint = this.getLoginAsUserEndpoint(userIdentifier); + /** + * Get a user's token given their identifier + * @param userIdentifier + * @returns {ng.IPromise} + * + * Note this feature should be implemented very carefully as it is a security risk as it means users + * can log in as other users (impersonation). The responsibility is on the implementing app to strongly + * control permissions to access this endpoint to avoid security risks + */ + public loginAsUser(userIdentifier:string|number):ng.IPromise { - return this.retrieveAndProcessToken(endpoint, authHeader); + if (!this.loggedIn) { + throw new NgJwtAuthException("You must be logged in to retrieve a user's token"); } + let authHeader = this.getBearerHeader(); + let endpoint = this.getLoginAsUserEndpoint(userIdentifier); + + return this.retrieveAndProcessToken(endpoint, authHeader); } } diff --git a/src/ngJwtAuthServiceProvider.ts b/src/ngJwtAuthServiceProvider.ts index 36d8d68..24ba097 100644 --- a/src/ngJwtAuthServiceProvider.ts +++ b/src/ngJwtAuthServiceProvider.ts @@ -1,91 +1,80 @@ -module NgJwtAuth { - export declare class Error { - public name: string; - public message: string; - public stack: string; - constructor(message?: string); - } - - export class NgJwtAuthException extends Error { - - constructor(public message: string) { - super(message); - this.name = 'NgJwtAuthException'; - this.message = message; - this.stack = (new Error()).stack; - } - toString() { - return this.name + ': ' + this.message; - } - } - - export class NgJwtAuthTokenExpiredException extends NgJwtAuthException{} - export class NgJwtAuthCredentialsFailedException extends NgJwtAuthException{} - - export class NgJwtAuthServiceProvider implements ng.IServiceProvider, INgJwtAuthServiceProvider { - - private config: INgJwtAuthServiceConfig; - - /** - * Initialise the service provider - */ - constructor() { +import {INgJwtAuthServiceConfig, IEndpointDefinition} from "./ngJwtAuthInterfaces"; +import {NgJwtAuthService} from "./ngJwtAuthService"; - //initialise service config - this.config = { - tokenLocation: 'token', - tokenUser: '#user', - apiEndpoints: { - base: '/api/auth', - login: '/login', - tokenExchange: '/token', - loginAsUser: '/user', - refresh: '/refresh', - }, - storageKeyName: 'NgJwtAuthToken', - refreshBeforeSeconds: 60 * 2, //2 mins - checkExpiryEverySeconds: 60, //2 mins - cookie: { - enabled: false, - name: 'ngJwtAuthToken', - topLevelDomain: false, - } - }; +export declare class Error { + public name: string; + public message: string; + public stack: string; + constructor(message?: string); +} - } +export class NgJwtAuthException extends Error { - /** - * Set the configuration - * @param config - * @returns {NgJwtAuth.NgJwtAuthServiceProvider} - */ - public configure(config:IEndpointDefinition) : NgJwtAuthServiceProvider { + constructor(public message: string) { + super(message); + this.name = 'NgJwtAuthException'; + this.message = message; + this.stack = (new Error()).stack; + } + toString() { + return this.name + ': ' + this.message; + } +} - let mismatchedConfig = _.difference(_.keys(config), _.keys(this.config)); - if (mismatchedConfig.length > 0){ - throw new NgJwtAuthException("Invalid properties ["+mismatchedConfig.join(',')+"] passed to config)"); +export class NgJwtAuthTokenExpiredException extends NgJwtAuthException{} +export class NgJwtAuthCredentialsFailedException extends NgJwtAuthException{} + +export class NgJwtAuthServiceProvider implements ng.IServiceProvider { + + private config: INgJwtAuthServiceConfig; + + /** + * Initialise the service provider + */ + constructor() { + + //initialise service config + this.config = { + tokenLocation: 'token', + tokenUser: '#user', + apiEndpoints: { + base: '/api/auth', + login: '/login', + tokenExchange: '/token', + loginAsUser: '/user', + refresh: '/refresh', + }, + storageKeyName: 'NgJwtAuthToken', + refreshBeforeSeconds: 60 * 2, //2 mins + checkExpiryEverySeconds: 60, //2 mins + cookie: { + enabled: false, + name: 'ngJwtAuthToken', + topLevelDomain: false, } - - this.config = _.defaultsDeep(config, this.config); - return this; - } - - public $get = ['$http', '$q', '$window', '$interval', 'base64', '$cookies', '$location', function NgJwtAuthServiceFactory($http, $q, $window, $interval, base64, $cookies, $location) { - return new NgJwtAuthService(this.config, $http, $q, $window, $interval, base64, $cookies, $location); - }]; + }; } + /** + * Set the configuration + * @param config + * @returns {NgJwtAuth.NgJwtAuthServiceProvider} + */ + public configure(config:IEndpointDefinition) : NgJwtAuthServiceProvider { + let mismatchedConfig = _.difference(_.keys(config), _.keys(this.config)); + if (mismatchedConfig.length > 0){ + throw new NgJwtAuthException("Invalid properties ["+mismatchedConfig.join(',')+"] passed to config)"); + } - angular.module('ngJwtAuth', ['ab-base64', 'ngCookies']) - .provider('ngJwtAuthService', NgJwtAuthServiceProvider) - .service('ngJwtAuthInterceptor', NgJwtAuthInterceptor) - .config(['$httpProvider', '$injector', ($httpProvider:ng.IHttpProvider) => { + this.config = _.defaultsDeep(config, this.config); + return this; + } - $httpProvider.interceptors.push('ngJwtAuthInterceptor'); - }]) - ; + public $get = ['$http', '$q', '$window', '$interval', 'base64', '$cookies', '$location', function NgJwtAuthServiceFactory($http, $q, $window, $interval, base64, $cookies, $location) { + return new NgJwtAuthService(this.config, $http, $q, $window, $interval, base64, $cookies, $location); + }]; } diff --git a/test/test.ts b/test/test.spec.ts similarity index 93% rename from test/test.ts rename to test/test.spec.ts index d4d2f35..4514270 100644 --- a/test/test.ts +++ b/test/test.spec.ts @@ -1,8 +1,13 @@ -/// -/// +import { + NgJwtAuthServiceProvider, NgJwtAuthException, + NgJwtAuthCredentialsFailedException +} from "../src/ngJwtAuthServiceProvider"; +import {NgJwtAuthService} from "../src/ngJwtAuthService"; +import {INgJwtAuthServiceConfig, IJwtToken, ICredentials, IJwtClaims, IUser} from "../src/ngJwtAuthInterfaces"; - -let expect = chai.expect; +import {expect} from "chai"; +import {Chance} from "chance"; +import * as _ from "lodash"; let seededChance = new Chance(1); let fixtures = { @@ -42,7 +47,7 @@ let fixtures = { signature: 'this-is-the-signed-hash' }; - let token:NgJwtAuth.IJwtToken = _.merge(defaultConfig, overrides); + let token:IJwtToken = _.merge(defaultConfig, overrides); return btoa(JSON.stringify(token.data)) + '.' + btoa(JSON.stringify(token.data)) @@ -106,15 +111,15 @@ let cookiesFactoryMock = (allowDomain) => { }; }; -let defaultAuthServiceProvider:NgJwtAuth.NgJwtAuthServiceProvider; +let defaultAuthServiceProvider:NgJwtAuthServiceProvider; describe('Default configuration', function () { - let defaultAuthService:NgJwtAuth.NgJwtAuthService; + let defaultAuthService:NgJwtAuthService; beforeEach(() => { - module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { + angular.mock.module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { defaultAuthServiceProvider = _ngJwtAuthServiceProvider_; //register injection of service provider }); @@ -148,9 +153,9 @@ describe('Default configuration', function () { describe('Custom configuration', function () { - let authServiceProvider:NgJwtAuth.NgJwtAuthServiceProvider; - let customAuthService:NgJwtAuth.NgJwtAuthService; - let partialCustomConfig:NgJwtAuth.INgJwtAuthServiceConfig = { + let authServiceProvider:NgJwtAuthServiceProvider; + let customAuthService:NgJwtAuthService; + let partialCustomConfig:INgJwtAuthServiceConfig = { tokenLocation: 'token-custom', tokenUser: '#user-custom', apiEndpoints: { @@ -164,7 +169,7 @@ describe('Custom configuration', function () { beforeEach(() => { - module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { + angular.mock.module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { authServiceProvider = _ngJwtAuthServiceProvider_; //register injection of service provider authServiceProvider.configure(partialCustomConfig); @@ -178,7 +183,7 @@ describe('Custom configuration', function () { authServiceProvider.configure({invalid:'config'}); }; - expect(testInvalidConfigurationFn).to.throw(NgJwtAuth.NgJwtAuthException); + expect(testInvalidConfigurationFn).to.throw(NgJwtAuthException); }); @@ -207,7 +212,7 @@ describe('Service tests', () => { let $httpBackend:ng.IHttpBackendService; let $http:ng.IHttpService; - let ngJwtAuthService:NgJwtAuth.NgJwtAuthService; + let ngJwtAuthService:NgJwtAuthService; let $rootScope:ng.IRootScopeService; let $cookies:ng.cookies.ICookiesService; let $q:ng.IQService; @@ -219,7 +224,7 @@ describe('Service tests', () => { beforeEach(()=>{ - module(function ($provide) { + angular.mock.module(function ($provide) { $provide.factory('$cookies', cookiesFactoryMock(cookieDomain)); @@ -227,9 +232,9 @@ describe('Service tests', () => { }); - angular.module('ngCookies',[]); //register the module as being overriden + angular.mock.module('ngCookies',[]); //register the angular.mock.module as being overriden - module('ngJwtAuth'); + angular.mock.module('ngJwtAuth'); inject((_$httpBackend_, _ngJwtAuthService_, _$http_, _$rootScope_, _$cookies_, _$q_) => { @@ -389,7 +394,7 @@ describe('Service tests', () => { let authPromise = ngJwtAuthService.authenticateCredentials(fixtures.user.email, fixtures.user.password); - expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuth.NgJwtAuthException); + expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuthException); $httpBackend.flush(); @@ -402,7 +407,7 @@ describe('Service tests', () => { let authPromise = ngJwtAuthService.authenticateCredentials(fixtures.user.email, fixtures.user.password); - expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuth.NgJwtAuthException); + expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuthException); $httpBackend.flush(); @@ -415,7 +420,7 @@ describe('Service tests', () => { let authPromise = ngJwtAuthService.authenticateCredentials(fixtures.user.email, fixtures.user.password); - expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuth.NgJwtAuthException); + expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuthException); $httpBackend.flush(); @@ -427,7 +432,7 @@ describe('Service tests', () => { let authPromise = ngJwtAuthService.authenticateCredentials(fixtures.user.email, fixtures.user.password); - expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuth.NgJwtAuthCredentialsFailedException); + expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuthCredentialsFailedException); $httpBackend.flush(); @@ -439,7 +444,7 @@ describe('Service tests', () => { let authPromise = ngJwtAuthService.authenticateCredentials(fixtures.user.email, fixtures.user.password); - expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuth.NgJwtAuthException); + expect(authPromise).to.eventually.be.rejectedWith(NgJwtAuthException); $httpBackend.flush(); @@ -467,9 +472,9 @@ describe('Service tests', () => { let rejectPromise = false; let loginSuccess:ng.IPromise = null; let spy = { - loginPromptFactory: (deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:NgJwtAuth.IUser): ng.IPromise => { + loginPromptFactory: (deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:IUser): ng.IPromise => { - let credentials:NgJwtAuth.ICredentials = { + let credentials:ICredentials = { username: fixtures.user.email, password: fixtures.user.password, }; @@ -503,7 +508,7 @@ describe('Service tests', () => { ngJwtAuthService.promptLogin(); }; - expect(testLoginPromptFactoryFn).to.throw(NgJwtAuth.NgJwtAuthException); + expect(testLoginPromptFactoryFn).to.throw(NgJwtAuthException); }); @@ -524,7 +529,7 @@ describe('Service tests', () => { }; - expect(setFactoryFn).to.throw(NgJwtAuth.NgJwtAuthException); + expect(setFactoryFn).to.throw(NgJwtAuthException); }); @@ -661,7 +666,7 @@ describe('Service tests', () => { userPromise.then(() => { progressSpy.should.have.been.calledTwice; - progressSpy.should.have.been.calledWith(sinon.match.instanceOf(NgJwtAuth.NgJwtAuthException)); + progressSpy.should.have.been.calledWith(sinon.match.instanceOf(NgJwtAuthException)); done(); }); @@ -703,7 +708,7 @@ describe('Service tests', () => { ngJwtAuthService.refreshToken(); }; - expect(refreshFn).to.throw(NgJwtAuth.NgJwtAuthException); //if not logged it, exception should be thrown on attempt to refresh + expect(refreshFn).to.throw(NgJwtAuthException); //if not logged it, exception should be thrown on attempt to refresh $httpBackend.expectGET('/api/auth/login').respond({token: fixtures.token}); ngJwtAuthService.authenticateCredentials(fixtures.user.email, fixtures.user.password); @@ -739,7 +744,7 @@ describe('Service tests', () => { let refreshPromise = ngJwtAuthService.refreshToken(); - expect(refreshPromise).to.eventually.be.rejectedWith(NgJwtAuth.NgJwtAuthException); + expect(refreshPromise).to.eventually.be.rejectedWith(NgJwtAuthException); refreshPromise.catch(()=>{ expect((ngJwtAuthService).refreshTimerPromise).to.be.null; @@ -761,7 +766,7 @@ describe('Service tests', () => { let refreshPromise = ngJwtAuthService.refreshToken(); - expect(refreshPromise).to.eventually.be.rejectedWith(NgJwtAuth.NgJwtAuthException); + expect(refreshPromise).to.eventually.be.rejectedWith(NgJwtAuthException); $httpBackend.flush(); @@ -791,7 +796,7 @@ describe('Service tests', () => { ngJwtAuthService.loginAsUser('any'); }; - expect(expectedExceptionFn).to.throw(NgJwtAuth.NgJwtAuthException); + expect(expectedExceptionFn).to.throw(NgJwtAuthException); }); it('should not be able to retrieve a bearer token if the user is not logged in', () => { @@ -802,7 +807,7 @@ describe('Service tests', () => { (ngJwtAuthService).getBearerHeader(); }; - expect(expectedExceptionFn).to.throw(NgJwtAuth.NgJwtAuthException); + expect(expectedExceptionFn).to.throw(NgJwtAuthException); }); /** @@ -921,8 +926,8 @@ describe('Service tests', () => { describe('Cookie interaction', () => { - let originalConfig:NgJwtAuth.INgJwtAuthServiceConfig; - let config:NgJwtAuth.INgJwtAuthServiceConfig; + let originalConfig:INgJwtAuthServiceConfig; + let config:INgJwtAuthServiceConfig; beforeEach(() => { originalConfig = ngJwtAuthService.getConfig(); @@ -1042,7 +1047,7 @@ describe('Service tests', () => { }; - expect(expectedExceptionFn).to.throw(NgJwtAuth.NgJwtAuthException); + expect(expectedExceptionFn).to.throw(NgJwtAuthException); }); @@ -1056,12 +1061,12 @@ describe('Service tests', () => { describe('Service Reloading', () => { let $httpBackend:ng.IHttpBackendService; - let ngJwtAuthService:NgJwtAuth.NgJwtAuthService; + let ngJwtAuthService:NgJwtAuthService; let $rootScope:ng.IRootScopeService; beforeEach(()=>{ - module(function ($provide) { + angular.mock.module(function ($provide) { $provide.factory('$cookies', cookiesFactoryMock('example.com')); @@ -1069,7 +1074,7 @@ describe('Service Reloading', () => { }); - module('ngJwtAuth'); + angular.mock.module('ngJwtAuth'); inject((_$httpBackend_, _ngJwtAuthService_, _$rootScope_) => { @@ -1082,9 +1087,9 @@ describe('Service Reloading', () => { let $q = (ngJwtAuthService).$q; - ngJwtAuthService.registerLoginPromptFactory((deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:NgJwtAuth.IUser): ng.IPromise => { + ngJwtAuthService.registerLoginPromptFactory((deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:IUser): ng.IPromise => { - let credentials:NgJwtAuth.ICredentials = { + let credentials:ICredentials = { username: fixtures.user.email, password: fixtures.user.password, }; @@ -1136,7 +1141,7 @@ describe('Service Reloading', () => { let init = ngJwtAuthService.init(); - expect(init).eventually.to.be.rejectedWith(sinon.match.instanceOf(NgJwtAuth.NgJwtAuthException)); + expect(init).eventually.to.be.rejectedWith(sinon.match.instanceOf(NgJwtAuthException)); }); @@ -1258,7 +1263,7 @@ describe('Service Reloading', () => { describe('Custom user factory', () => { - let mockUserFactory = (subClaim:string, tokenData:NgJwtAuth.IJwtClaims):ng.IPromise => { + let mockUserFactory = (subClaim:string, tokenData:IJwtClaims):ng.IPromise => { let user = _.get(tokenData, '#user'); (user).custom = 'this is a custom property'; diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..9ecc2b3 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "es5", + "noImplicitAny": false, + "removeComments": false, + "sourceMap": true, + "module": "commonjs", + "experimentalDecorators": true, + "outDir": "dist" + }, + "exclude": [ + "out", + "node_modules", + "dist", + "dev", + "typings/main.d.ts", + "typings/main", + "reports", + "test" + ], + "version": "1.8.9" +} \ No newline at end of file diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 0000000..bbddaf6 --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es5", + "noImplicitAny": false, + "removeComments": true, + "sourceMap": true, + "module": "commonjs", + "experimentalDecorators": true, + "outDir": "test/tmp" + }, + "exclude": [ + "out", + "node_modules", + "dist", + "dev", + "typings/main.d.ts", + "typings/main", + "reports" + ], + "version": "1.8.9" +} \ No newline at end of file diff --git a/tsd.json b/tsd.json deleted file mode 100644 index 3dcd20e..0000000 --- a/tsd.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "version": "v4", - "repo": "borisyankov/DefinitelyTyped", - "ref": "master", - "path": "typings", - "bundle": "typings/tsd.d.ts", - "installed": { - "mocha/mocha.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "chai/chai.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "angularjs/angular.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "lodash/lodash.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "jquery/jquery.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "angularjs/angular-mocks.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "sinon-chai/sinon-chai.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "sinon/sinon.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "moment/moment.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "moment/moment-node.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "chance/chance.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "chai-as-promised/chai-as-promised.d.ts": { - "commit": "6f04d25ad38982d372cc3cda62fa4c0eef9e24d7" - }, - "angularjs/angular-cookies.d.ts": { - "commit": "338f9db37074d197764e95a487ddb865c5f2d73c" - } - } -} diff --git a/typings.json b/typings.json new file mode 100644 index 0000000..e19aeeb --- /dev/null +++ b/typings.json @@ -0,0 +1,18 @@ +{ + "ambientDependencies": { + "angular": "registry:dt/angular#1.5.0+20160328125810", + "angular-cookies": "registry:dt/angular-cookies#1.4.0+20160317120654", + "angular-mocks": "registry:dt/angular-mocks#1.3.0+20160322011350", + "chai": "registry:dt/chai#3.4.0+20160317120654", + "chai-as-promised": "registry:dt/chai-as-promised#0.0.0+20160317120654", + "chance": "registry:dt/chance#0.7.3+20160317120654", + "jquery": "registry:dt/jquery#1.10.0+20160316155526", + "lodash": "registry:dt/lodash#3.10.0+20160330154726", + "mocha": "registry:dt/mocha#2.2.5+20160317120654", + "moment": "registry:dt/moment#2.8.0+20160316155526", + "moment-node": "registry:dt/moment-node#2.11.1+20160329220348", + "promises-a-plus": "registry:dt/promises-a-plus#0.0.0+20160317120654", + "sinon": "registry:dt/sinon#1.16.0+20160317120654", + "sinon-chai": "registry:dt/sinon-chai#2.7.0+20160317120654" + } +} diff --git a/typings/angularjs/angular-cookies.d.ts b/typings/angularjs/angular-cookies.d.ts deleted file mode 100644 index ab4849e..0000000 --- a/typings/angularjs/angular-cookies.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Type definitions for Angular JS 1.4 (ngCookies module) -// Project: http://angularjs.org -// Definitions by: Diego Vilar , Anthony Ciccarello -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -declare module "angular-cookies" { - var _: string; - export = _; -} - -/** - * ngCookies module (angular-cookies.js) - */ -declare module angular.cookies { - - /** - * CookieService - * see http://docs.angularjs.org/api/ngCookies.$cookies - */ - interface ICookiesService { - [index: string]: any; - } - - /** - * CookieStoreService - * see http://docs.angularjs.org/api/ngCookies.$cookieStore - */ - interface ICookiesService { - get(key: string): string; - getObject(key: string): any; - getAll(): any; - put(key: string, value: string, options?: any): void; - putObject(key: string, value: any, options?: any): void; - remove(key: string, options?: any): void; - } - - /** - * CookieStoreService DEPRECATED - * see https://code.angularjs.org/1.2.26/docs/api/ngCookies/service/$cookieStore - */ - interface ICookieStoreService { - /** - * Returns the value of given cookie key - * @param key Id to use for lookup - */ - get(key: string): any; - /** - * Sets a value for given cookie key - * @param key Id for the value - * @param value Value to be stored - */ - put(key: string, value: any): void; - /** - * Remove given cookie - * @param key Id of the key-value pair to delete - */ - remove(key: string): void; - } - -} diff --git a/typings/angularjs/angular-mocks.d.ts b/typings/angularjs/angular-mocks.d.ts deleted file mode 100644 index 1d7c80c..0000000 --- a/typings/angularjs/angular-mocks.d.ts +++ /dev/null @@ -1,239 +0,0 @@ -// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) -// Project: http://angularjs.org -// Definitions by: Diego Vilar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "angular-mocks/ngMock" { - var _: string; - export = _; -} - -declare module "angular-mocks/ngAnimateMock" { - var _: string; - export = _; -} - -/////////////////////////////////////////////////////////////////////////////// -// functions attached to global object (window) -/////////////////////////////////////////////////////////////////////////////// -declare var module: (...modules: any[]) => any; -declare var inject: (...fns: Function[]) => any; - -/////////////////////////////////////////////////////////////////////////////// -// ngMock module (angular-mocks.js) -/////////////////////////////////////////////////////////////////////////////// -declare module angular { - - /////////////////////////////////////////////////////////////////////////// - // AngularStatic - // We reopen it to add the MockStatic definition - /////////////////////////////////////////////////////////////////////////// - interface IAngularStatic { - mock: IMockStatic; - } - - interface IMockStatic { - // see http://docs.angularjs.org/api/angular.mock.dump - dump(obj: any): string; - - // see http://docs.angularjs.org/api/angular.mock.inject - inject: { - (...fns: Function[]): any; - (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works - strictDi(val?: boolean): void; - } - - // see http://docs.angularjs.org/api/angular.mock.module - module(...modules: any[]): any; - - // see http://docs.angularjs.org/api/angular.mock.TzDate - TzDate(offset: number, timestamp: number): Date; - TzDate(offset: number, timestamp: string): Date; - } - - /////////////////////////////////////////////////////////////////////////// - // ExceptionHandlerService - // see http://docs.angularjs.org/api/ngMock.$exceptionHandler - // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider - /////////////////////////////////////////////////////////////////////////// - interface IExceptionHandlerProvider extends IServiceProvider { - mode(mode: string): void; - } - - /////////////////////////////////////////////////////////////////////////// - // TimeoutService - // see http://docs.angularjs.org/api/ngMock.$timeout - // Augments the original service - /////////////////////////////////////////////////////////////////////////// - interface ITimeoutService { - flush(delay?: number): void; - flushNext(expectedDelay?: number): void; - verifyNoPendingTasks(): void; - } - - /////////////////////////////////////////////////////////////////////////// - // IntervalService - // see http://docs.angularjs.org/api/ngMock.$interval - // Augments the original service - /////////////////////////////////////////////////////////////////////////// - interface IIntervalService { - flush(millis?: number): number; - } - - /////////////////////////////////////////////////////////////////////////// - // LogService - // see http://docs.angularjs.org/api/ngMock.$log - // Augments the original service - /////////////////////////////////////////////////////////////////////////// - interface ILogService { - assertEmpty(): void; - reset(): void; - } - - interface ILogCall { - logs: string[]; - } - - /////////////////////////////////////////////////////////////////////////// - // HttpBackendService - // see http://docs.angularjs.org/api/ngMock.$httpBackend - /////////////////////////////////////////////////////////////////////////// - interface IHttpBackendService { - flush(count?: number): void; - resetExpectations(): void; - verifyNoOutstandingExpectation(): void; - verifyNoOutstandingRequest(): void; - - expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; - - expectDELETE(url: string, headers?: Object): mock.IRequestHandler; - expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; - expectGET(url: string, headers?: Object): mock.IRequestHandler; - expectGET(url: RegExp, headers?: Object): mock.IRequestHandler; - expectHEAD(url: string, headers?: Object): mock.IRequestHandler; - expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; - expectJSONP(url: string): mock.IRequestHandler; - expectJSONP(url: RegExp): mock.IRequestHandler; - - expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; - expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - - expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; - expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - - expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; - expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - - when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; - - whenDELETE(url: string, headers?: Object): mock.IRequestHandler; - whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; - whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - - whenGET(url: string, headers?: Object): mock.IRequestHandler; - whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - whenGET(url: RegExp, headers?: Object): mock.IRequestHandler; - whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - - whenHEAD(url: string, headers?: Object): mock.IRequestHandler; - whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; - whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - - whenJSONP(url: string): mock.IRequestHandler; - whenJSONP(url: RegExp): mock.IRequestHandler; - - whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; - whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - - whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; - whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - - whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; - whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - } - - export module mock { - - // returned interface by the the mocked HttpBackendService expect/when methods - interface IRequestHandler { - respond(func: Function): void; - respond(status: number, data?: any, headers?: any): void; - respond(data: any, headers?: any): void; - - // Available wehn ngMockE2E is loaded - passThrough(): void; - } - - } - -} diff --git a/typings/angularjs/angular.d.ts b/typings/angularjs/angular.d.ts deleted file mode 100644 index 0ea364d..0000000 --- a/typings/angularjs/angular.d.ts +++ /dev/null @@ -1,1715 +0,0 @@ -// Type definitions for Angular JS 1.4+ -// Project: http://angularjs.org -// Definitions by: Diego Vilar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -declare var angular: angular.IAngularStatic; - -// Support for painless dependency injection -interface Function { - $inject?: string[]; -} - -// Collapse angular into ng -import ng = angular; -// Support AMD require -declare module 'angular' { - export = angular; -} - -/////////////////////////////////////////////////////////////////////////////// -// ng module (angular.js) -/////////////////////////////////////////////////////////////////////////////// -declare module angular { - - // not directly implemented, but ensures that constructed class implements $get - interface IServiceProviderClass { - new (...args: any[]): IServiceProvider; - } - - interface IServiceProviderFactory { - (...args: any[]): IServiceProvider; - } - - // All service providers extend this interface - interface IServiceProvider { - $get: any; - } - - interface IAngularBootstrapConfig { - strictDi?: boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // AngularStatic - // see http://docs.angularjs.org/api - /////////////////////////////////////////////////////////////////////////// - interface IAngularStatic { - bind(context: any, fn: Function, ...args: any[]): Function; - - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: string, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: string, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: string, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: JQuery, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: JQuery, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: JQuery, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: Element, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: Element, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: Element, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: Document, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: Document, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: Document, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; - - /** - * Creates a deep copy of source, which should be an object or an array. - * - * - If no destination is supplied, a copy of the object or array is created. - * - If a destination is provided, all of its elements (for array) or properties (for objects) are deleted and then all elements/properties from the source are copied to it. - * - If source is not an object or array (inc. null and undefined), source is returned. - * - If source is identical to 'destination' an exception will be thrown. - * - * @param source The source that will be used to make a copy. Can be any type, including primitives, null, and undefined. - * @param destination Destination into which the source is copied. If provided, must be of the same type as source. - */ - copy(source: T, destination?: T): T; - - /** - * Wraps a raw DOM element or HTML string as a jQuery element. - * - * 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; - equals(value1: any, value2: any): boolean; - extend(destination: any, ...sources: any[]): any; - - /** - * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * - * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * - * @param obj Object to iterate over. - * @param iterator Iterator function. - * @param context Object to become context (this) for the iterator function. - */ - forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; - /** - * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * - * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * - * @param obj Object to iterate over. - * @param iterator Iterator function. - * @param context Object to become context (this) for the iterator function. - */ - forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; - /** - * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * - * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * - * @param obj Object to iterate over. - * @param iterator Iterator function. - * @param context Object to become context (this) for the iterator function. - */ - forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; - - fromJson(json: string): any; - identity(arg?: any): any; - injector(modules?: any[]): auto.IInjectorService; - isArray(value: any): boolean; - isDate(value: any): boolean; - isDefined(value: any): boolean; - isElement(value: any): boolean; - isFunction(value: any): boolean; - isNumber(value: any): boolean; - isObject(value: any): boolean; - isString(value: any): boolean; - isUndefined(value: any): boolean; - lowercase(str: string): string; - - /** - * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2). - * - * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. - * - * @param dst Destination object. - * @param src Source object(s). - */ - merge(dst: any, ...src: any[]): any; - - /** - * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. - * - * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. - * - * @param name The name of the module to create or retrieve. - * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. - * @param configFn Optional configuration function for the module. - */ - module( - name: string, - requires?: string[], - configFn?: Function): IModule; - - noop(...args: any[]): void; - reloadWithDebugInfo(): void; - toJson(obj: any, pretty?: boolean): string; - uppercase(str: string): string; - version: { - full: string; - major: number; - minor: number; - dot: number; - codeName: string; - }; - } - - /////////////////////////////////////////////////////////////////////////// - // Module - // see http://docs.angularjs.org/api/angular.Module - /////////////////////////////////////////////////////////////////////////// - interface IModule { - animation(name: string, animationFactory: Function): IModule; - animation(name: string, inlineAnnotatedFunction: any[]): IModule; - animation(object: Object): IModule; - /** - * Use this method to register work which needs to be performed on module loading. - * - * @param configFn Execute this function on module load. Useful for service configuration. - */ - config(configFn: Function): IModule; - /** - * Use this method to register work which needs to be performed on module loading. - * - * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. - */ - config(inlineAnnotatedFunction: any[]): IModule; - /** - * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * - * @param name The name of the constant. - * @param value The constant value. - */ - constant(name: string, value: any): IModule; - constant(object: Object): IModule; - /** - * The $controller service is used by Angular to create new controllers. - * - * This provider allows controller registration via the register method. - * - * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. - * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). - */ - controller(name: string, controllerConstructor: Function): IModule; - /** - * The $controller service is used by Angular to create new controllers. - * - * This provider allows controller registration via the register method. - * - * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. - * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). - */ - controller(name: string, inlineAnnotatedConstructor: any[]): IModule; - controller(object: Object): IModule; - /** - * Register a new directive with the compiler. - * - * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) - * @param directiveFactory An injectable directive factory function. - */ - directive(name: string, directiveFactory: IDirectiveFactory): IModule; - /** - * Register a new directive with the compiler. - * - * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) - * @param directiveFactory An injectable directive factory function. - */ - directive(name: string, inlineAnnotatedFunction: any[]): IModule; - directive(object: Object): IModule; - /** - * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * - * @param name The name of the instance. - * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). - */ - factory(name: string, $getFn: Function): IModule; - /** - * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * - * @param name The name of the instance. - * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). - */ - factory(name: string, inlineAnnotatedFunction: any[]): IModule; - factory(object: Object): IModule; - filter(name: string, filterFactoryFunction: Function): IModule; - filter(name: string, inlineAnnotatedFunction: any[]): IModule; - filter(object: Object): IModule; - provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; - provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; - provider(name: string, inlineAnnotatedConstructor: any[]): IModule; - provider(name: string, providerObject: IServiceProvider): IModule; - provider(object: Object): IModule; - /** - * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. - */ - run(initializationFunction: Function): IModule; - /** - * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. - */ - run(inlineAnnotatedFunction: any[]): IModule; - service(name: string, serviceConstructor: Function): IModule; - service(name: string, inlineAnnotatedConstructor: any[]): IModule; - service(object: Object): IModule; - /** - * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. - - Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator. - * - * @param name The name of the instance. - * @param value The value. - */ - value(name: string, value: any): IModule; - value(object: Object): IModule; - - /** - * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * @param name The name of the service to decorate - * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. - */ - decorator(name:string, decoratorConstructor: Function): IModule; - decorator(name:string, inlineAnnotatedConstructor: any[]): IModule; - - // Properties - name: string; - requires: string[]; - } - - /////////////////////////////////////////////////////////////////////////// - // Attributes - // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes - /////////////////////////////////////////////////////////////////////////// - interface IAttributes { - /** - * this is necessary to be able to access the scoped attributes. it's not very elegant - * because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way - * this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 - */ - [name: string]: any; - - /** - * Adds the CSS class value specified by the classVal parameter to the - * element. If animations are enabled then an animation will be triggered - * for the class addition. - */ - $addClass(classVal: string): void; - - /** - * Removes the CSS class value specified by the classVal parameter from the - * element. If animations are enabled then an animation will be triggered for - * the class removal. - */ - $removeClass(classVal: string): void; - - /** - * Set DOM element attribute value. - */ - $set(key: string, value: any): void; - - /** - * Observes an interpolated attribute. - * The observer function will be invoked once during the next $digest - * following compilation. The observer is then invoked whenever the - * interpolated value changes. - */ - $observe(name: string, fn: (value?: any) => any): Function; - - /** - * A map of DOM element attribute names to the normalized name. This is needed - * to do reverse lookup from normalized name back to actual name. - */ - $attr: Object; - } - - /** - * form.FormController - type in module ng - * see https://docs.angularjs.org/api/ng/type/form.FormController - */ - interface IFormController { - - /** - * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 - */ - [name: string]: any; - - $pristine: boolean; - $dirty: boolean; - $valid: boolean; - $invalid: boolean; - $submitted: boolean; - $error: any; - $addControl(control: INgModelController): void; - $removeControl(control: INgModelController): void; - $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; - $setDirty(): void; - $setPristine(): void; - $commitViewValue(): void; - $rollbackViewValue(): void; - $setSubmitted(): void; - $setUntouched(): void; - } - - /////////////////////////////////////////////////////////////////////////// - // NgModelController - // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController - /////////////////////////////////////////////////////////////////////////// - interface INgModelController { - $render(): void; - $setValidity(validationErrorKey: string, isValid: boolean): void; - // Documentation states viewValue and modelValue to be a string but other - // types do work and it's common to use them. - $setViewValue(value: any, trigger?: string): void; - $setPristine(): void; - $setDirty(): void; - $validate(): void; - $setTouched(): void; - $setUntouched(): void; - $rollbackViewValue(): void; - $commitViewValue(): void; - $isEmpty(value: any): boolean; - - $viewValue: any; - - $modelValue: any; - - $parsers: IModelParser[]; - $formatters: IModelFormatter[]; - $viewChangeListeners: IModelViewChangeListener[]; - $error: any; - $name: string; - - $touched: boolean; - $untouched: boolean; - - $validators: IModelValidators; - $asyncValidators: IAsyncModelValidators; - - $pending: any; - $pristine: boolean; - $dirty: boolean; - $valid: boolean; - $invalid: boolean; - } - - interface IModelValidators { - [index: string]: (modelValue: any, viewValue: string) => boolean; - } - - interface IAsyncModelValidators { - [index: string]: (modelValue: any, viewValue: string) => IPromise; - } - - interface IModelParser { - (value: any): any; - } - - interface IModelFormatter { - (value: any): any; - } - - interface IModelViewChangeListener { - (): void; - } - - /** - * $rootScope - $rootScopeProvider - service in module ng - * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope - */ - interface IRootScopeService { - [index: string]: any; - - $apply(): any; - $apply(exp: string): any; - $apply(exp: (scope: IScope) => any): any; - - $applyAsync(): any; - $applyAsync(exp: string): any; - $applyAsync(exp: (scope: IScope) => any): any; - - /** - * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. - * - * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. - * - * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. - * - * @param name Event name to broadcast. - * @param args Optional one or more arguments which will be passed onto the event listeners. - */ - $broadcast(name: string, ...args: any[]): IAngularEvent; - $destroy(): void; - $digest(): void; - /** - * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. - * - * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it. - * - * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. - * - * @param name Event name to emit. - * @param args Optional one or more arguments which will be passed onto the event listeners. - */ - $emit(name: string, ...args: any[]): IAngularEvent; - - $eval(): any; - $eval(expression: string, locals?: Object): any; - $eval(expression: (scope: IScope) => any, locals?: Object): any; - - $evalAsync(): void; - $evalAsync(expression: string): void; - $evalAsync(expression: (scope: IScope) => any): void; - - // Defaults to false by the implementation checking strategy - $new(isolate?: boolean, parent?: IScope): IScope; - - /** - * Listens on events of a given type. See $emit for discussion of event life cycle. - * - * The event listener function format is: function(event, args...). - * - * @param name Event name to listen on. - * @param listener Function to call when the event is emitted. - */ - $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - - $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; - $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; - $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function; - $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; - - $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; - $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; - - $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; - $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; - - $parent: IScope; - $root: IRootScopeService; - $id: number; - - // Hidden members - $$isolateBindings: any; - $$phase: any; - } - - interface IScope extends IRootScopeService { } - - /** - * $scope for ngRepeat directive. - * see https://docs.angularjs.org/api/ng/directive/ngRepeat - */ - interface IRepeatScope extends IScope { - - /** - * iterator offset of the repeated element (0..length-1). - */ - $index: number; - - /** - * true if the repeated element is first in the iterator. - */ - $first: boolean; - - /** - * true if the repeated element is between the first and last in the iterator. - */ - $middle: boolean; - - /** - * true if the repeated element is last in the iterator. - */ - $last: boolean; - - /** - * true if the iterator position $index is even (otherwise false). - */ - $even: boolean; - - /** - * true if the iterator position $index is odd (otherwise false). - */ - $odd: boolean; - - } - - interface IAngularEvent { - /** - * the scope on which the event was $emit-ed or $broadcast-ed. - */ - targetScope: IScope; - /** - * the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null. - */ - currentScope: IScope; - /** - * name of the event. - */ - name: string; - /** - * calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed). - */ - stopPropagation?: Function; - /** - * calling preventDefault sets defaultPrevented flag to true. - */ - preventDefault: Function; - /** - * true if preventDefault was called. - */ - defaultPrevented: boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // WindowService - // see http://docs.angularjs.org/api/ng.$window - /////////////////////////////////////////////////////////////////////////// - interface IWindowService extends Window { - [key: string]: any; - } - - /////////////////////////////////////////////////////////////////////////// - // BrowserService - // TODO undocumented, so we need to get it from the source code - /////////////////////////////////////////////////////////////////////////// - interface IBrowserService { - defer: angular.ITimeoutService; - [key: string]: any; - } - - /////////////////////////////////////////////////////////////////////////// - // TimeoutService - // see http://docs.angularjs.org/api/ng.$timeout - /////////////////////////////////////////////////////////////////////////// - interface ITimeoutService { - (func: Function, delay?: number, invokeApply?: boolean): IPromise; - cancel(promise: IPromise): boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // IntervalService - // see http://docs.angularjs.org/api/ng.$interval - /////////////////////////////////////////////////////////////////////////// - interface IIntervalService { - (func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise; - cancel(promise: IPromise): boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // AngularProvider - // see http://docs.angularjs.org/api/ng/provider/$animateProvider - /////////////////////////////////////////////////////////////////////////// - interface IAnimateProvider { - /** - * Registers a new injectable animation factory function. - * - * @param name The name of the animation. - * @param factory The factory function that will be executed to return the animation object. - */ - register(name: string, factory: () => IAnimateCallbackObject): void; - - /** - * Gets and/or sets the CSS class expression that is checked when performing an animation. - * - * @param expression The className expression which will be checked against all animations. - * @returns The current CSS className expression value. If null then there is no expression value. - */ - classNameFilter(expression?: RegExp): RegExp; - } - - /** - * The animation object which contains callback functions for each event that is expected to be animated. - */ - interface IAnimateCallbackObject { - eventFn(element: Node, doneFn: () => void): Function; - } - - /** - * $filter - $filterProvider - service in module ng - * - * Filters are used for formatting data displayed to the user. - * - * see https://docs.angularjs.org/api/ng/service/$filter - */ - interface IFilterService { - /** - * Usage: - * $filter(name); - * - * @param name Name of the filter function to retrieve - */ - (name: string): Function; - } - - /** - * $filterProvider - $filter - provider in module ng - * - * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function. - * - * see https://docs.angularjs.org/api/ng/provider/$filterProvider - */ - interface IFilterProvider extends IServiceProvider { - /** - * register(name); - * - * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx). - */ - register(name: string | {}): IServiceProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // LocaleService - // see http://docs.angularjs.org/api/ng.$locale - /////////////////////////////////////////////////////////////////////////// - interface ILocaleService { - id: string; - - // These are not documented - // Check angular's i18n files for exemples - NUMBER_FORMATS: ILocaleNumberFormatDescriptor; - DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; - pluralCat: (num: any) => string; - } - - interface ILocaleNumberFormatDescriptor { - DECIMAL_SEP: string; - GROUP_SEP: string; - PATTERNS: ILocaleNumberPatternDescriptor[]; - CURRENCY_SYM: string; - } - - interface ILocaleNumberPatternDescriptor { - minInt: number; - minFrac: number; - maxFrac: number; - posPre: string; - posSuf: string; - negPre: string; - negSuf: string; - gSize: number; - lgSize: number; - } - - interface ILocaleDateTimeFormatDescriptor { - MONTH: string[]; - SHORTMONTH: string[]; - DAY: string[]; - SHORTDAY: string[]; - AMPMS: string[]; - medium: string; - short: string; - fullDate: string; - longDate: string; - mediumDate: string; - shortDate: string; - mediumTime: string; - shortTime: string; - } - - /////////////////////////////////////////////////////////////////////////// - // LogService - // see http://docs.angularjs.org/api/ng.$log - // see http://docs.angularjs.org/api/ng.$logProvider - /////////////////////////////////////////////////////////////////////////// - interface ILogService { - debug: ILogCall; - error: ILogCall; - info: ILogCall; - log: ILogCall; - warn: ILogCall; - } - - interface ILogProvider { - debugEnabled(): boolean; - debugEnabled(enabled: boolean): ILogProvider; - } - - // We define this as separate interface so we can reopen it later for - // the ngMock module. - interface ILogCall { - (...args: any[]): void; - } - - /////////////////////////////////////////////////////////////////////////// - // ParseService - // see http://docs.angularjs.org/api/ng.$parse - // see http://docs.angularjs.org/api/ng.$parseProvider - /////////////////////////////////////////////////////////////////////////// - interface IParseService { - (expression: string): ICompiledExpression; - } - - interface IParseProvider { - logPromiseWarnings(): boolean; - logPromiseWarnings(value: boolean): IParseProvider; - - unwrapPromises(): boolean; - unwrapPromises(value: boolean): IParseProvider; - } - - interface ICompiledExpression { - (context: any, locals?: any): any; - - // If value is not provided, undefined is gonna be used since the implementation - // does not check the parameter. Let's force a value for consistency. If consumer - // whants to undefine it, pass the undefined value explicitly. - assign(context: any, value: any): any; - } - - /** - * $location - $locationProvider - service in module ng - * see https://docs.angularjs.org/api/ng/service/$location - */ - interface ILocationService { - absUrl(): string; - hash(): string; - hash(newHash: string): ILocationService; - host(): string; - - /** - * Return path of current url - */ - path(): string; - - /** - * Change path when called with parameter and return $location. - * Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing. - * - * @param path New path - */ - path(path: string): ILocationService; - - port(): number; - protocol(): string; - replace(): ILocationService; - - /** - * Return search part (as object) of current url - */ - search(): any; - - /** - * Change search part when called with parameter and return $location. - * - * @param search When called with a single argument the method acts as a setter, setting the search component of $location to the specified value. - * - * If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url. - */ - search(search: any): ILocationService; - - /** - * Change search part when called with parameter and return $location. - * - * @param search New search params - * @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign. - */ - search(search: string, paramValue: string|number|string[]|boolean): ILocationService; - - state(): any; - state(state: any): ILocationService; - url(): string; - url(url: string): ILocationService; - } - - interface ILocationProvider extends IServiceProvider { - hashPrefix(): string; - hashPrefix(prefix: string): ILocationProvider; - html5Mode(): boolean; - - // Documentation states that parameter is string, but - // implementation tests it as boolean, which makes more sense - // since this is a toggler - html5Mode(active: boolean): ILocationProvider; - html5Mode(mode: { enabled?: boolean; requireBase?: boolean; rewriteLinks?: boolean; }): ILocationProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // DocumentService - // see http://docs.angularjs.org/api/ng.$document - /////////////////////////////////////////////////////////////////////////// - interface IDocumentService extends IAugmentedJQuery {} - - /////////////////////////////////////////////////////////////////////////// - // ExceptionHandlerService - // see http://docs.angularjs.org/api/ng.$exceptionHandler - /////////////////////////////////////////////////////////////////////////// - interface IExceptionHandlerService { - (exception: Error, cause?: string): void; - } - - /////////////////////////////////////////////////////////////////////////// - // RootElementService - // see http://docs.angularjs.org/api/ng.$rootElement - /////////////////////////////////////////////////////////////////////////// - interface IRootElementService extends JQuery {} - - interface IQResolveReject { - (): void; - (value: T): void; - } - /** - * $q - service in module ng - * A promise/deferred implementation inspired by Kris Kowal's Q. - * See http://docs.angularjs.org/api/ng/service/$q - */ - interface IQService { - new (resolver: (resolve: IQResolveReject) => any): IPromise; - new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; - new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; - - /** - * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * - * Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * - * @param promises An array of promises. - */ - all(promises: IPromise[]): IPromise; - /** - * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * - * Returns a single promise that will be resolved with a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * - * @param promises A hash of promises. - */ - all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; - /** - * Creates a Deferred object which represents a task which will finish in the future. - */ - defer(): IDeferred; - /** - * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. - * - * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. - * - * @param reason Constant, message, exception or an object representing the rejection reason. - */ - reject(reason?: any): IPromise; - /** - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * - * @param value Value or a promise - */ - when(value: IPromise|T): IPromise; - /** - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * - * @param value Value or a promise - */ - when(): IPromise; - } - - interface IPromise { - /** - * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. - * - * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. - */ - then(successCallback: (promiseValue: T) => IHttpPromise|IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; - - /** - * Shorthand for promise.then(null, errorCallback) - */ - catch(onRejected: (reason: any) => IHttpPromise|IPromise|TResult): IPromise; - - /** - * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. - * - * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. - */ - finally(finallyCallback: () => any): IPromise; - } - - interface IDeferred { - resolve(value?: T): void; - reject(reason?: any): void; - notify(state?: any): void; - promise: IPromise; - } - - /////////////////////////////////////////////////////////////////////////// - // AnchorScrollService - // see http://docs.angularjs.org/api/ng.$anchorScroll - /////////////////////////////////////////////////////////////////////////// - interface IAnchorScrollService { - (): void; - yOffset: any; - } - - interface IAnchorScrollProvider extends IServiceProvider { - disableAutoScrolling(): void; - } - - /** - * $cacheFactory - service in module ng - * - * Factory that constructs Cache objects and gives access to them. - * - * see https://docs.angularjs.org/api/ng/service/$cacheFactory - */ - interface ICacheFactoryService { - /** - * Factory that constructs Cache objects and gives access to them. - * - * @param cacheId Name or id of the newly created cache. - * @param optionsMap Options object that specifies the cache behavior. Properties: - * - * capacity — turns the cache into LRU cache. - */ - (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; - - /** - * Get information about all the caches that have been created. - * @returns key-value map of cacheId to the result of calling cache#info - */ - info(): any; - - /** - * Get access to a cache object by the cacheId used when it was created. - * - * @param cacheId Name or id of a cache to access. - */ - get(cacheId: string): ICacheObject; - } - - /** - * $cacheFactory.Cache - type in module ng - * - * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. - * - * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache - */ - interface ICacheObject { - /** - * Retrieve information regarding a particular Cache. - */ - info(): { - /** - * the id of the cache instance - */ - id: string; - - /** - * the number of entries kept in the cache instance - */ - size: number; - - //...: any additional properties from the options object when creating the cache. - }; - - /** - * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set. - * - * It will not insert undefined values into the cache. - * - * @param key the key under which the cached data is stored. - * @param value the value to store alongside the key. If it is undefined, the key will not be stored. - */ - put(key: string, value?: T): T; - - /** - * Retrieves named data stored in the Cache object. - * - * @param key the key of the data to be retrieved - */ - get(key: string): any; - - /** - * Removes an entry from the Cache object. - * - * @param key the key of the entry to be removed - */ - remove(key: string): void; - - /** - * Clears the cache object of any entries. - */ - removeAll(): void; - - /** - * Destroys the Cache object entirely, removing it from the $cacheFactory set. - */ - destroy(): void; - } - - /////////////////////////////////////////////////////////////////////////// - // CompileService - // see http://docs.angularjs.org/api/ng.$compile - // see http://docs.angularjs.org/api/ng.$compileProvider - /////////////////////////////////////////////////////////////////////////// - interface ICompileService { - (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; - (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; - (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; - } - - interface ICompileProvider extends IServiceProvider { - directive(name: string, directiveFactory: Function): ICompileProvider; - - // Undocumented, but it is there... - directive(directivesMap: any): ICompileProvider; - - aHrefSanitizationWhitelist(): RegExp; - aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; - - imgSrcSanitizationWhitelist(): RegExp; - imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; - - debugInfoEnabled(enabled?: boolean): any; - } - - interface ICloneAttachFunction { - // Let's hint but not force cloneAttachFn's signature - (clonedElement?: JQuery, scope?: IScope): any; - } - - // This corresponds to the "publicLinkFn" returned by $compile. - interface ITemplateLinkingFunction { - (scope: IScope, cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; - } - - // 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; - // If one argument is provided, then it's assumed to be the cloneAttachFn. - (cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; - } - - /////////////////////////////////////////////////////////////////////////// - // ControllerService - // see http://docs.angularjs.org/api/ng.$controller - // see http://docs.angularjs.org/api/ng.$controllerProvider - /////////////////////////////////////////////////////////////////////////// - interface IControllerService { - // Although the documentation doesn't state this, locals are optional - (controllerConstructor: Function, locals?: any): any; - (controllerName: string, locals?: any): any; - } - - interface IControllerProvider extends IServiceProvider { - register(name: string, controllerConstructor: Function): void; - register(name: string, dependencyAnnotatedConstructor: any[]): void; - allowGlobals(): void; - } - - /** - * HttpService - * see http://docs.angularjs.org/api/ng/service/$http - */ - interface IHttpService { - /** - * Object describing the request to be made and how it should be processed. - */ - (config: IRequestConfig): IHttpPromise; - - /** - * Shortcut method to perform GET request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param config Optional configuration object - */ - get(url: string, config?: IRequestShortcutConfig): IHttpPromise; - - /** - * Shortcut method to perform DELETE request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param config Optional configuration object - */ - delete(url: string, config?: IRequestShortcutConfig): IHttpPromise; - - /** - * Shortcut method to perform HEAD request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param config Optional configuration object - */ - head(url: string, config?: IRequestShortcutConfig): IHttpPromise; - - /** - * Shortcut method to perform JSONP request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param config Optional configuration object - */ - jsonp(url: string, config?: IRequestShortcutConfig): IHttpPromise; - - /** - * Shortcut method to perform POST request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param data Request content - * @param config Optional configuration object - */ - post(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; - - /** - * Shortcut method to perform PUT request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param data Request content - * @param config Optional configuration object - */ - put(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; - - /** - * Shortcut method to perform PATCH request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param data Request content - * @param config Optional configuration object - */ - patch(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; - - /** - * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations. - */ - defaults: IRequestConfig; - - /** - * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. - */ - pendingRequests: any[]; - } - - /** - * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage - */ - interface IRequestShortcutConfig { - /** - * {Object.} - * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. - */ - params?: any; - - /** - * Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. - */ - headers?: any; - - /** - * Name of HTTP header to populate with the XSRF token. - */ - xsrfHeaderName?: string; - - /** - * Name of cookie containing the XSRF token. - */ - xsrfCookieName?: string; - - /** - * {boolean|Cache} - * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. - */ - cache?: any; - - /** - * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information. - */ - withCredentials?: boolean; - - /** - * {string|Object} - * Data to be sent as the request message data. - */ - data?: any; - - /** - * {function(data, headersGetter)|Array.} - * Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. - */ - transformRequest?: any; - - /** - * {function(data, headersGetter)|Array.} - * Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version. - */ - transformResponse?: any; - - /** - * {number|Promise} - * Timeout in milliseconds, or promise that should abort the request when resolved. - */ - timeout?: any; - - /** - * See requestType. - */ - responseType?: string; - } - - /** - * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage - */ - interface IRequestConfig extends IRequestShortcutConfig { - /** - * HTTP method (e.g. 'GET', 'POST', etc) - */ - method: string; - /** - * Absolute or relative URL of the resource that is being requested. - */ - url: string; - } - - interface IHttpHeadersGetter { - (): { [name: string]: string; }; - (headerName: string): string; - } - - interface IHttpPromiseCallback { - (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void; - } - - interface IHttpPromiseCallbackArg { - data?: T; - status?: number; - headers?: IHttpHeadersGetter; - config?: IRequestConfig; - statusText?: string; - } - - interface IHttpPromise extends IPromise> { - success(callback: IHttpPromiseCallback): IHttpPromise; - error(callback: IHttpPromiseCallback): IHttpPromise; - then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise|TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; - } - - /** - * Object that controls the defaults for $http provider - * https://docs.angularjs.org/api/ng/service/$http#defaults - */ - interface IHttpProviderDefaults { - cache?: boolean; - xsrfCookieName?: string; - xsrfHeaderName?: string; - withCredentials?: boolean; - headers?: { - common?: any; - post?: any; - put?: any; - patch?: any; - } - } - - interface IHttpProvider extends IServiceProvider { - defaults: IHttpProviderDefaults; - interceptors: any[]; - useApplyAsync(): boolean; - useApplyAsync(value: boolean): IHttpProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // HttpBackendService - // see http://docs.angularjs.org/api/ng.$httpBackend - // You should never need to use this service directly. - /////////////////////////////////////////////////////////////////////////// - interface IHttpBackendService { - // XXX Perhaps define callback signature in the future - (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void; - } - - /////////////////////////////////////////////////////////////////////////// - // InterpolateService - // see http://docs.angularjs.org/api/ng.$interpolate - // see http://docs.angularjs.org/api/ng.$interpolateProvider - /////////////////////////////////////////////////////////////////////////// - interface IInterpolateService { - (text: string, mustHaveExpression?: boolean, trustedContext?: string, allOrNothing?: boolean): IInterpolationFunction; - endSymbol(): string; - startSymbol(): string; - } - - interface IInterpolationFunction { - (context: any): string; - } - - interface IInterpolateProvider extends IServiceProvider { - startSymbol(): string; - startSymbol(value: string): IInterpolateProvider; - endSymbol(): string; - endSymbol(value: string): IInterpolateProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // TemplateCacheService - // see http://docs.angularjs.org/api/ng.$templateCache - /////////////////////////////////////////////////////////////////////////// - interface ITemplateCacheService extends ICacheObject {} - - /////////////////////////////////////////////////////////////////////////// - // SCEService - // see http://docs.angularjs.org/api/ng.$sce - /////////////////////////////////////////////////////////////////////////// - interface ISCEService { - getTrusted(type: string, mayBeTrusted: any): any; - getTrustedCss(value: any): any; - getTrustedHtml(value: any): any; - getTrustedJs(value: any): any; - getTrustedResourceUrl(value: any): any; - getTrustedUrl(value: any): any; - parse(type: string, expression: string): (context: any, locals: any) => any; - parseAsCss(expression: string): (context: any, locals: any) => any; - parseAsHtml(expression: string): (context: any, locals: any) => any; - parseAsJs(expression: string): (context: any, locals: any) => any; - parseAsResourceUrl(expression: string): (context: any, locals: any) => any; - parseAsUrl(expression: string): (context: any, locals: any) => any; - trustAs(type: string, value: any): any; - trustAsHtml(value: any): any; - trustAsJs(value: any): any; - trustAsResourceUrl(value: any): any; - trustAsUrl(value: any): any; - isEnabled(): boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // SCEProvider - // see http://docs.angularjs.org/api/ng.$sceProvider - /////////////////////////////////////////////////////////////////////////// - interface ISCEProvider extends IServiceProvider { - enabled(value: boolean): void; - } - - /////////////////////////////////////////////////////////////////////////// - // SCEDelegateService - // see http://docs.angularjs.org/api/ng.$sceDelegate - /////////////////////////////////////////////////////////////////////////// - interface ISCEDelegateService { - getTrusted(type: string, mayBeTrusted: any): any; - trustAs(type: string, value: any): any; - valueOf(value: any): any; - } - - - /////////////////////////////////////////////////////////////////////////// - // SCEDelegateProvider - // see http://docs.angularjs.org/api/ng.$sceDelegateProvider - /////////////////////////////////////////////////////////////////////////// - interface ISCEDelegateProvider extends IServiceProvider { - resourceUrlBlacklist(blacklist: any[]): void; - resourceUrlWhitelist(whitelist: any[]): void; - } - - /** - * $templateRequest service - * see http://docs.angularjs.org/api/ng/service/$templateRequest - */ - interface ITemplateRequestService { - /** - * Downloads a template using $http and, upon success, stores the - * contents inside of $templateCache. - * - * If the HTTP request fails or the response data of the HTTP request is - * empty then a $compile error will be thrown (unless - * {ignoreRequestError} is set to true). - * - * @param tpl The template URL. - * @param ignoreRequestError Whether or not to ignore the exception - * when the request fails or the template is - * empty. - * - * @return A promise whose value is the template content. - */ - (tpl: string, ignoreRequestError?: boolean): IPromise; - /** - * total amount of pending template requests being downloaded. - * @type {number} - */ - totalPendingRequests: number; - } - - /////////////////////////////////////////////////////////////////////////// - // Directive - // see http://docs.angularjs.org/api/ng.$compileProvider#directive - // and http://docs.angularjs.org/guide/directive - /////////////////////////////////////////////////////////////////////////// - - interface IDirectiveFactory { - (...args: any[]): IDirective; - } - - interface IDirectiveLinkFn { - ( - scope: IScope, - instanceElement: IAugmentedJQuery, - instanceAttributes: IAttributes, - controller: any, - transclude: ITranscludeFunction - ): void; - } - - interface IDirectivePrePost { - pre?: IDirectiveLinkFn; - post?: IDirectiveLinkFn; - } - - interface IDirectiveCompileFn { - ( - templateElement: IAugmentedJQuery, - templateAttributes: IAttributes, - transclude: ITranscludeFunction - ): IDirectivePrePost; - } - - interface IDirective { - compile?: IDirectiveCompileFn; - controller?: any; - controllerAs?: string; - bindToController?: boolean|Object; - link?: IDirectiveLinkFn | IDirectivePrePost; - name?: string; - priority?: number; - replace?: boolean; - require?: any; - restrict?: string; - scope?: any; - template?: any; - templateUrl?: any; - terminal?: boolean; - transclude?: any; - } - - /** - * 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 - */ - 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; - isolateScope(): IScope; - - inheritedData(key: string, value: any): JQuery; - inheritedData(obj: { [key: string]: any; }): JQuery; - inheritedData(key?: string): any; - } - - /////////////////////////////////////////////////////////////////////// - // AnimateService - // see http://docs.angularjs.org/api/ng.$animate - /////////////////////////////////////////////////////////////////////// - interface IAnimateService { - addClass(element: JQuery, className: string, done?: Function): IPromise; - enter(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; - leave(element: JQuery, done?: Function): void; - move(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; - removeClass(element: JQuery, className: string, done?: Function): void; - } - - /////////////////////////////////////////////////////////////////////////// - // AUTO module (angular.js) - /////////////////////////////////////////////////////////////////////////// - export module auto { - - /////////////////////////////////////////////////////////////////////// - // InjectorService - // see http://docs.angularjs.org/api/AUTO.$injector - /////////////////////////////////////////////////////////////////////// - interface IInjectorService { - annotate(fn: Function): string[]; - annotate(inlineAnnotatedFunction: any[]): string[]; - get(name: string): any; - has(name: string): boolean; - instantiate(typeConstructor: Function, locals?: any): any; - invoke(inlineAnnotatedFunction: any[]): any; - invoke(func: Function, context?: any, locals?: any): any; - } - - /////////////////////////////////////////////////////////////////////// - // ProvideService - // see http://docs.angularjs.org/api/AUTO.$provide - /////////////////////////////////////////////////////////////////////// - interface IProvideService { - // Documentation says it returns the registered instance, but actual - // implementation does not return anything. - // constant(name: string, value: any): any; - /** - * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * - * @param name The name of the constant. - * @param value The constant value. - */ - constant(name: string, value: any): void; - - /** - * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * - * @param name The name of the service to decorate. - * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * - * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. - */ - decorator(name: string, decorator: Function): void; - /** - * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * - * @param name The name of the service to decorate. - * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * - * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. - */ - decorator(name: string, inlineAnnotatedFunction: any[]): void; - factory(name: string, serviceFactoryFunction: Function): IServiceProvider; - factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; - provider(name: string, provider: IServiceProvider): IServiceProvider; - provider(name: string, serviceProviderConstructor: Function): IServiceProvider; - service(name: string, constructor: Function): IServiceProvider; - value(name: string, value: any): IServiceProvider; - } - - } -} diff --git a/typings/chai-as-promised/chai-as-promised.d.ts b/typings/chai-as-promised/chai-as-promised.d.ts deleted file mode 100644 index 106bbf4..0000000 --- a/typings/chai-as-promised/chai-as-promised.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Type definitions for chai-as-promised -// Project: https://github.com/domenic/chai-as-promised/ -// Definitions by: jt000 -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module 'chai-as-promised' { - function chaiAsPromised(chai: any, utils: any): void; - export = chaiAsPromised; -} - -declare module Chai { - - interface Assertion { - become(expected: any): Assertion; - fulfilled: Assertion; - rejected: Assertion; - rejectedWith(expected: any): Assertion; - notify(fn: Function): Assertion; - } - - interface LanguageChains { - eventually: Assertion; - } - - interface Assert { - eventually: Assert; - isFulfilled(promise: any, message?: string): void; - becomes(promise: any, expected: any, message?: string): void; - doesNotBecome(promise: any, expected: any, message?: string): void; - isRejected(promise: any, message?: string): void; - isRejected(promise: any, expected: any, message?: string): void; - isRejected(promise: any, match: RegExp, message?: string): void; - } -} diff --git a/typings/chai/chai.d.ts b/typings/chai/chai.d.ts deleted file mode 100644 index cb685f3..0000000 --- a/typings/chai/chai.d.ts +++ /dev/null @@ -1,308 +0,0 @@ -// Type definitions for chai 2.0.0 -// Project: http://chaijs.com/ -// Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module Chai { - - interface ChaiStatic { - expect: ExpectStatic; - should(): Should; - /** - * Provides a way to extend the internals of Chai - */ - use(fn: (chai: any, utils: any) => void): any; - assert: AssertStatic; - config: Config; - } - - export interface ExpectStatic extends AssertionStatic { - } - - export interface AssertStatic extends Assert { - } - - export interface AssertionStatic { - (target: any, message?: string): Assertion; - } - - interface ShouldAssertion { - equal(value1: any, value2: any, message?: string): void; - Throw: ShouldThrow; - throw: ShouldThrow; - exist(value: any, message?: string): void; - } - - interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: string): void; - } - - interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; - (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; - } - - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - a: TypeComparison; - an: TypeComparison; - include: Include; - contain: Include; - ok: Assertion; - true: Assertion; - false: Assertion; - null: Assertion; - undefined: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - length: Length; - lengthOf: Length; - match(regexp: RegExp|string, message?: string): Assertion; - string(string: string, message?: string): Assertion; - keys: Keys; - key(string: string): Assertion; - throw: Throw; - throws: Throw; - Throw: Throw; - respondTo(method: string, message?: string): Assertion; - itself: Assertion; - satisfy(matcher: Function, message?: string): Assertion; - closeTo(expected: number, delta: number, message?: string): Assertion; - members: Members; - } - - interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; - } - - interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; - } - - interface NumberComparer { - (value: number, message?: string): Assertion; - } - - interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; - } - - interface InstanceOf { - (constructor: Object, message?: string): Assertion; - } - - interface Deep { - equal: Equal; - include: Include; - property: Property; - } - - interface Equal { - (value: any, message?: string): Assertion; - } - - interface Property { - (name: string, value?: any, message?: string): Assertion; - } - - interface OwnProperty { - (name: string, message?: string): Assertion; - } - - interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; - } - - interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; - keys: Keys; - members: Members; - } - - interface Keys { - (...keys: string[]): Assertion; - (keys: any[]): Assertion; - } - - interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; - } - - interface Members { - (set: any[], message?: string): Assertion; - } - - export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - - ok(val: any, msg?: string): void; - notOk(val: any, msg?: string): void; - - equal(act: any, exp: any, msg?: string): void; - notEqual(act: any, exp: any, msg?: string): void; - - strictEqual(act: any, exp: any, msg?: string): void; - notStrictEqual(act: any, exp: any, msg?: string): void; - - deepEqual(act: any, exp: any, msg?: string): void; - notDeepEqual(act: any, exp: any, msg?: string): void; - - isTrue(val: any, msg?: string): void; - isFalse(val: any, msg?: string): void; - - isNull(val: any, msg?: string): void; - isNotNull(val: any, msg?: string): void; - - isUndefined(val: any, msg?: string): void; - isDefined(val: any, msg?: string): void; - - isFunction(val: any, msg?: string): void; - isNotFunction(val: any, msg?: string): void; - - isObject(val: any, msg?: string): void; - isNotObject(val: any, msg?: string): void; - - isArray(val: any, msg?: string): void; - isNotArray(val: any, msg?: string): void; - - isString(val: any, msg?: string): void; - isNotString(val: any, msg?: string): void; - - isNumber(val: any, msg?: string): void; - isNotNumber(val: any, msg?: string): void; - - isBoolean(val: any, msg?: string): void; - isNotBoolean(val: any, msg?: string): void; - - typeOf(val: any, type: string, msg?: string): void; - notTypeOf(val: any, type: string, msg?: string): void; - - instanceOf(val: any, type: Function, msg?: string): void; - notInstanceOf(val: any, type: Function, msg?: string): void; - - include(exp: string, inc: any, msg?: string): void; - include(exp: any[], inc: any, msg?: string): void; - - notInclude(exp: string, inc: any, msg?: string): void; - notInclude(exp: any[], inc: any, msg?: string): void; - - match(exp: any, re: RegExp, msg?: string): void; - notMatch(exp: any, re: RegExp, msg?: string): void; - - property(obj: Object, prop: string, msg?: string): void; - notProperty(obj: Object, prop: string, msg?: string): void; - deepProperty(obj: Object, prop: string, msg?: string): void; - notDeepProperty(obj: Object, prop: string, msg?: string): void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - lengthOf(exp: any, len: number, msg?: string): void; - //alias frenzy - throw(fn: Function, msg?: string): void; - throw(fn: Function, regExp: RegExp): void; - throw(fn: Function, errType: Function, msg?: string): void; - throw(fn: Function, errType: Function, regExp: RegExp): void; - - throws(fn: Function, msg?: string): void; - throws(fn: Function, regExp: RegExp): void; - throws(fn: Function, errType: Function, msg?: string): void; - throws(fn: Function, errType: Function, regExp: RegExp): void; - - Throw(fn: Function, msg?: string): void; - Throw(fn: Function, regExp: RegExp): void; - Throw(fn: Function, errType: Function, msg?: string): void; - Throw(fn: Function, errType: Function, regExp: RegExp): void; - - doesNotThrow(fn: Function, msg?: string): void; - doesNotThrow(fn: Function, regExp: RegExp): void; - doesNotThrow(fn: Function, errType: Function, msg?: string): void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - - operator(val: any, operator: string, val2: any, msg?: string): void; - closeTo(act: number, exp: number, delta: number, msg?: string): void; - - sameMembers(set1: any[], set2: any[], msg?: string): void; - includeMembers(set1: any[], set2: any[], msg?: string): void; - - ifError(val: any, msg?: string): void; - } - - export interface Config { - includeStack: boolean; - } - - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } -} - -declare var chai: Chai.ChaiStatic; - -declare module "chai" { - export = chai; -} - -interface Object { - should: Chai.Assertion; -} diff --git a/typings/chance/chance.d.ts b/typings/chance/chance.d.ts deleted file mode 100644 index 2af960e..0000000 --- a/typings/chance/chance.d.ts +++ /dev/null @@ -1,213 +0,0 @@ -// Type definitions for Chance 0.7.3 -// Project: http://chancejs.com -// Definitions by: Chris Bowdon -// Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Chance { - - interface ChanceStatic { - Chance(): Chance; - new(): Chance; - new(seed: number): Chance; - new(generator: () => any): Chance; - } - - interface Chance { - - // Basics - bool(opts?: Options): boolean; - character(opts?: Options): string; - floating(opts?: Options): number; - integer(opts?: Options): number; - natural(opts?: Options): number; - string(opts?: Options): string; - - // Text - paragraph(opts?: Options): string; - sentence(opts?: Options): string; - syllable(opts?: Options): string; - word(opts?: Options): string; - - // Person - age(opts?: Options): number; - birthday(): Date; - birthday(opts?: Options): Date|string; - cpf(): string; - first(opts?: Options): string; - last(opts?: Options): string; - name(opts?: Options): string; - name_prefix(opts?: Options): string; - name_suffix(opts?: Options): string; - prefix(opts?: Options): string; - ssn(opts?: Options): string; - suffix(opts?: Options): string; - - // Mobile - android_id(): string; - apple_token(): string; - bb_pin(): string; - wp7_anid(): string; - wp8_anid2(): string; - - // Web - color(opts?: Options): string; - domain(opts?: Options): string; - email(opts?: Options): string; - fbid(): string; - google_analytics(): string; - hashtag(): string; - ip(): string; - ipv6(): string; - klout(): string; - tld(): string; - twitter(): string; - url(opts?: Options): string; - - // Location - address(opts?: Options): string; - altitude(opts?: Options): number; - areacode(): string; - city(): string; - coordinates(opts?: Options): string; - country(opts?: Options): string; - depth(opts?: Options): number; - geohash(opts?: Options): string; - latitude(opts?: Options): number; - longitude(opts?: Options): number; - phone(opts?: Options): string; - postal(): string; - province(opts?: Options): string; - state(opts?: Options): string; - street(opts?: Options): string; - zip(opts?: Options): string; - - // Time - ampm(): string; - date(): Date; - date(opts: DateOptions): Date|string; - hammertime(): number; - hour(opts?: Options): number; - millisecond(): number; - minute(): number; - month(): string; - month(opts: Options): Month; - second(): number; - timestamp(): number; - year(opts?: Options): string; - - // Finance - cc(opts?: Options): string; - cc_type(): string; - cc_type(opts: Options): string|CreditCardType; - currency(): Currency; - currency_pair(): [ Currency, Currency ]; - dollar(opts?: Options): string; - exp(): string; - exp(opts: Options): string|CreditCardExpiration; - exp_month(opts?: Options): string; - exp_year(opts?: Options): string; - - // Helpers - capitalize(str: string): string; - mixin(desc: MixinDescriptor): any; - pad(num: number, width: number, padChar?: string): string; - pick(arr: T[]): T; - pick(arr: T[], count: number): T[]; - set: Setter; - shuffle(arr: T[]): T[]; - - // Miscellaneous - d4(): number; - d6(): number; - d8(): number; - d10(): number; - d12(): number; - d20(): number; - d30(): number; - d100(): number; - guid(): string; - hash(opts?: Options): string; - n(generator: () => T, count: number, opts?: Options): T[]; - normal(opts?: Options): string; - radio(opts?: Options): string; - rpg(dice: string): number[]; - rpg(dice: string, opts?: Options): number[]|number; - tv(opts?: Options): string; - unique(generator: () => T, count: number, opts?: Options): T[]; - weighted(values: T[], weights: number[]): T; - - // "Hidden" - cc_types(): CreditCardType[]; - mersenne_twister(seed?: number): any; // API return type not defined in docs - months(): Month[]; - name_prefixes(): Name[]; - provinces(): Name[]; - states(): Name[]; - street_suffix(): Name; - street_suffixes(): Name[]; - } - - // A more rigorous approach might be to produce - // the correct options interfaces for each method - interface Options { [id: string]: any; } - - interface DateOptions { - string?: boolean; - american?: boolean; - year?: number; - month?: number; - day?: number; - } - - interface Month { - name: string; - short_name: string; - numeric: string; - } - - interface CreditCardType { - name: string; - short_name: string; - prefix: string; - length: number; - } - - interface Currency { - code: string; - name: string; - } - - interface CreditCardExpiration { - month: string; - year: string; - } - - interface MixinDescriptor { [id: string]: () => any; } - - interface Setter { - (key: 'firstNames', values: string[]): any; - (key: 'lastNames', values: string[]): any; - (key: 'provinces', values: string[]): any; - (key: 'us_states_and_dc', values: string[]): any; - (key: 'territories', values: string[]): any; - (key: 'armed_forces', values: string[]): any; - (key: 'street_suffixes', values: string[]): any; - (key: 'months', values: string[]): any; - (key: 'cc_types', values: string[]): any; - (key: 'currency_types', values: string[]): any; - (key: string, values: T[]): any; - } - - interface Name { - name: string; - abbreviation: string; - } -} - -// window.chance -declare var chance: Chance.Chance; -declare var Chance: Chance.ChanceStatic; - -// import Chance = require('chance'); -declare module 'chance' { - export = Chance; -} diff --git a/typings/jquery/jquery.d.ts b/typings/jquery/jquery.d.ts deleted file mode 100644 index 4653239..0000000 --- a/typings/jquery/jquery.d.ts +++ /dev/null @@ -1,3170 +0,0 @@ -// Type definitions for jQuery 1.10.x / 2.0.x -// Project: http://jquery.com/ -// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - - -/** - * Interface for the AJAX setting that will configure the AJAX request - */ -interface JQueryAjaxSettings { - /** - * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. - */ - accepts?: any; - /** - * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). - */ - async?: boolean; - /** - * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. - */ - beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; - /** - * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. - */ - cache?: boolean; - /** - * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. - */ - complete? (jqXHR: JQueryXHR, textStatus: string): any; - /** - * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) - */ - contents?: { [key: string]: any; }; - //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" - // https://github.com/borisyankov/DefinitelyTyped/issues/742 - /** - * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. - */ - contentType?: any; - /** - * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). - */ - context?: any; - /** - * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) - */ - converters?: { [key: string]: any; }; - /** - * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) - */ - crossDomain?: boolean; - /** - * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). - */ - data?: any; - /** - * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. - */ - dataFilter? (data: any, ty: any): any; - /** - * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). - */ - dataType?: string; - /** - * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. - */ - error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; - /** - * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. - */ - global?: boolean; - /** - * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) - */ - headers?: { [key: string]: any; }; - /** - * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. - */ - ifModified?: boolean; - /** - * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) - */ - isLocal?: boolean; - /** - * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } - */ - jsonp?: any; - /** - * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. - */ - jsonpCallback?: any; - /** - * A mime type to override the XHR mime type. (version added: 1.5.1) - */ - mimeType?: string; - /** - * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - password?: string; - /** - * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. - */ - processData?: boolean; - /** - * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. - */ - scriptCharset?: string; - /** - * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) - */ - statusCode?: { [key: string]: any; }; - /** - * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. - */ - success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; - /** - * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. - */ - timeout?: number; - /** - * Set this to true if you wish to use the traditional style of param serialization. - */ - traditional?: boolean; - /** - * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. - */ - type?: string; - /** - * A string containing the URL to which the request is sent. - */ - url?: string; - /** - * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - username?: string; - /** - * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. - */ - xhr?: any; - /** - * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) - */ - xhrFields?: { [key: string]: any; }; -} - -/** - * Interface for the jqXHR object - */ -interface JQueryXHR extends XMLHttpRequest, JQueryPromise { - /** - * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). - */ - overrideMimeType(mimeType: string): any; - /** - * Cancel the request. - * - * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" - */ - abort(statusText?: string): void; - /** - * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. - */ - then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; - /** - * Property containing the parsed response if the response Content-Type is json - */ - responseJSON?: any; -} - -/** - * Interface for the JQuery callback - */ -interface JQueryCallback { - /** - * Add a callback or a collection of callbacks to a callback list. - * - * @param callbacks A function, or array of functions, that are to be added to the callback list. - */ - add(callbacks: Function): JQueryCallback; - /** - * Add a callback or a collection of callbacks to a callback list. - * - * @param callbacks A function, or array of functions, that are to be added to the callback list. - */ - add(callbacks: Function[]): JQueryCallback; - - /** - * Disable a callback list from doing anything more. - */ - disable(): JQueryCallback; - - /** - * Determine if the callbacks list has been disabled. - */ - disabled(): boolean; - - /** - * Remove all of the callbacks from a list. - */ - empty(): JQueryCallback; - - /** - * Call all of the callbacks with the given arguments - * - * @param arguments The argument or list of arguments to pass back to the callback list. - */ - fire(...arguments: any[]): JQueryCallback; - - /** - * Determine if the callbacks have already been called at least once. - */ - fired(): boolean; - - /** - * Call all callbacks in a list with the given context and arguments. - * - * @param context A reference to the context in which the callbacks in the list should be fired. - * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. - */ - fireWith(context?: any, ...args: any[]): JQueryCallback; - - /** - * Determine whether a supplied callback is in a list - * - * @param callback The callback to search for. - */ - has(callback: Function): boolean; - - /** - * Lock a callback list in its current state. - */ - lock(): JQueryCallback; - - /** - * Determine if the callbacks list has been locked. - */ - locked(): boolean; - - /** - * Remove a callback or a collection of callbacks from a callback list. - * - * @param callbacks A function, or array of functions, that are to be removed from the callback list. - */ - remove(callbacks: Function): JQueryCallback; - /** - * Remove a callback or a collection of callbacks from a callback list. - * - * @param callbacks A function, or array of functions, that are to be removed from the callback list. - */ - remove(callbacks: Function[]): JQueryCallback; -} - -/** - * Allows jQuery Promises to interop with non-jQuery promises - */ -interface JQueryGenericPromise { - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - */ - then(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; - - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - */ - then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; -} - -/** - * Interface for the JQuery promise/deferred callbacks - */ -interface JQueryPromiseCallback { - (value?: T, ...args: any[]): void; -} - -interface JQueryPromiseOperator { - (callback1: JQueryPromiseCallback|JQueryPromiseCallback[], ...callbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; -} - -/** - * Interface for the JQuery promise, part of callbacks - */ -interface JQueryPromise extends JQueryGenericPromise { - /** - * Determine the current state of a Deferred object. - */ - state(): string; - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - */ - always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - */ - done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - */ - fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. - */ - progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; - - // Deprecated - given no typings - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; -} - -/** - * Interface for the JQuery deferred, part of callbacks - */ -interface JQueryDeferred extends JQueryGenericPromise { - /** - * Determine the current state of a Deferred object. - */ - state(): string; - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - */ - always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - */ - done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - */ - fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. - */ - progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - - /** - * Call the progressCallbacks on a Deferred object with the given args. - * - * @param args Optional arguments that are passed to the progressCallbacks. - */ - notify(value?: any, ...args: any[]): JQueryDeferred; - - /** - * Call the progressCallbacks on a Deferred object with the given context and args. - * - * @param context Context passed to the progressCallbacks as the this object. - * @param args Optional arguments that are passed to the progressCallbacks. - */ - notifyWith(context: any, value?: any, ...args: any[]): JQueryDeferred; - - /** - * Reject a Deferred object and call any failCallbacks with the given args. - * - * @param args Optional arguments that are passed to the failCallbacks. - */ - reject(value?: any, ...args: any[]): JQueryDeferred; - /** - * Reject a Deferred object and call any failCallbacks with the given context and args. - * - * @param context Context passed to the failCallbacks as the this object. - * @param args An optional array of arguments that are passed to the failCallbacks. - */ - rejectWith(context: any, value?: any, ...args: any[]): JQueryDeferred; - - /** - * Resolve a Deferred object and call any doneCallbacks with the given args. - * - * @param value First argument passed to doneCallbacks. - * @param args Optional subsequent arguments that are passed to the doneCallbacks. - */ - resolve(value?: T, ...args: any[]): JQueryDeferred; - - /** - * Resolve a Deferred object and call any doneCallbacks with the given context and args. - * - * @param context Context passed to the doneCallbacks as the this object. - * @param args An optional array of arguments that are passed to the doneCallbacks. - */ - resolveWith(context: any, value?: T, ...args: any[]): JQueryDeferred; - - /** - * Return a Deferred's Promise object. - * - * @param target Object onto which the promise methods have to be attached - */ - promise(target?: any): JQueryPromise; - - // Deprecated - given no typings - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; -} - -/** - * Interface of the JQuery extension of the W3C event object - */ -interface BaseJQueryEventObject extends Event { - data: any; - delegateTarget: Element; - isDefaultPrevented(): boolean; - isImmediatePropagationStopped(): boolean; - isPropagationStopped(): boolean; - namespace: string; - originalEvent: Event; - preventDefault(): any; - relatedTarget: Element; - result: any; - stopImmediatePropagation(): void; - stopPropagation(): void; - target: Element; - pageX: number; - pageY: number; - which: number; - metaKey: boolean; -} - -interface JQueryInputEventObject extends BaseJQueryEventObject { - altKey: boolean; - ctrlKey: boolean; - metaKey: boolean; - shiftKey: boolean; -} - -interface JQueryMouseEventObject extends JQueryInputEventObject { - button: number; - clientX: number; - clientY: number; - offsetX: number; - offsetY: number; - pageX: number; - pageY: number; - screenX: number; - screenY: number; -} - -interface JQueryKeyEventObject extends JQueryInputEventObject { - char: any; - charCode: number; - key: any; - keyCode: number; -} - -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ -} - -/* - Collection of properties of the current browser -*/ - -interface JQuerySupport { - ajax?: boolean; - boxModel?: boolean; - changeBubbles?: boolean; - checkClone?: boolean; - checkOn?: boolean; - cors?: boolean; - cssFloat?: boolean; - hrefNormalized?: boolean; - htmlSerialize?: boolean; - leadingWhitespace?: boolean; - noCloneChecked?: boolean; - noCloneEvent?: boolean; - opacity?: boolean; - optDisabled?: boolean; - optSelected?: boolean; - scriptEval? (): boolean; - style?: boolean; - submitBubbles?: boolean; - tbody?: boolean; -} - -interface JQueryParam { - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * - * @param obj An array or object to serialize. - */ - (obj: any): string; - - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * - * @param obj An array or object to serialize. - * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. - */ - (obj: any, traditional: boolean): string; -} - -/** - * The interface used to construct jQuery events (with $.Event). It is - * defined separately instead of inline in JQueryStatic to allow - * overriding the construction function with specific strings - * returning specific event objects. - */ -interface JQueryEventConstructor { - (name: string, eventProperties?: any): JQueryEventObject; - new (name: string, eventProperties?: any): JQueryEventObject; -} - -/** - * The interface used to specify coordinates. - */ -interface JQueryCoordinates { - left: number; - top: number; -} - -/** - * Elements in the array returned by serializeArray() - */ -interface JQuerySerializeArrayElement { - name: string; - value: string; -} - -interface JQueryAnimationOptions { - /** - * A string or number determining how long the animation will run. - */ - duration?: any; - /** - * A string indicating which easing function to use for the transition. - */ - easing?: string; - /** - * A function to call once the animation is complete. - */ - complete?: Function; - /** - * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. - */ - step?: (now: number, tween: any) => any; - /** - * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) - */ - progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; - /** - * A function to call when the animation begins. (version added: 1.8) - */ - start?: (animation: JQueryPromise) => any; - /** - * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) - */ - done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) - */ - fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) - */ - always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. - */ - queue?: any; - /** - * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) - */ - specialEasing?: Object; -} - -/** - * Static members of jQuery (those on $ and jQuery themselves) - */ -interface JQueryStatic { - - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(settings: JQueryAjaxSettings): JQueryXHR; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param url A string containing the URL to which the request is sent. - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; - - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param dataTypes An optional string containing one or more space-separated dataTypes - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - - ajaxSettings: JQueryAjaxSettings; - - /** - * Set default values for future Ajax requests. Its use is not recommended. - * - * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. - */ - ajaxSetup(options: JQueryAjaxSettings): void; - - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load a JavaScript file from the server using a GET HTTP request, then execute it. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - */ - param: JQueryParam; - - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - - /** - * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. - * - * @param flags An optional list of space-separated flags that change how the callback list behaves. - */ - Callbacks(flags?: string): JQueryCallback; - - /** - * Holds or releases the execution of jQuery's ready event. - * - * @param hold Indicates whether the ready hold is being requested or released - */ - holdReady(hold: boolean): void; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM Element, Document, or jQuery to use as context - */ - (selector: string, context?: Element|JQuery): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param element A DOM element to wrap in a jQuery object. - */ - (element: Element): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. - */ - (elementArray: Element[]): JQuery; - - /** - * Binds a function to be executed when the DOM has finished loading. - * - * @param callback A function to execute after the DOM is ready. - */ - (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object A plain object to wrap in a jQuery object. - */ - (object: {}): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object An existing jQuery object to clone. - */ - (object: JQuery): JQuery; - - /** - * Specify a function to execute when the DOM is fully loaded. - */ - (): JQuery; - - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. - * @param ownerDocument A document in which the new elements will be created. - */ - (html: string, ownerDocument?: Document): JQuery; - - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string defining a single, standalone, HTML element (e.g.
or
). - * @param attributes An object of attributes, events, and methods to call on the newly-created element. - */ - (html: string, attributes: Object): JQuery; - - /** - * Relinquish jQuery's control of the $ variable. - * - * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - */ - noConflict(removeAll?: boolean): Object; - - /** - * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. - * - * @param deferreds One or more Deferred objects, or plain JavaScript objects. - */ - when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; - - /** - * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. - */ - cssHooks: { [key: string]: any; }; - cssNumber: any; - - /** - * Store arbitrary data associated with the specified element. Returns the value that was set. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - * @param value The new data value. - */ - data(element: Element, key: string, value: T): T; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - */ - data(element: Element, key: string): any; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - */ - data(element: Element): any; - - /** - * Execute the next function on the queue for the matched element. - * - * @param element A DOM element from which to remove and execute a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(element: Element, queueName?: string): void; - - /** - * Determine whether an element has any jQuery data associated with it. - * - * @param element A DOM element to be checked for data. - */ - hasData(element: Element): boolean; - - /** - * Show the queue of functions to be executed on the matched element. - * - * @param element A DOM element to inspect for an attached queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(element: Element, queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element where the array of queued functions is attached. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(element: Element, queueName: string, newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element on which to add a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue. - */ - queue(element: Element, queueName: string, callback: Function): JQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param element A DOM element from which to remove data. - * @param name A string naming the piece of data to remove. - */ - removeData(element: Element, name?: string): JQuery; - - /** - * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. - * - * @param beforeStart A function that is called just before the constructor returns. - */ - Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; - - /** - * Effects - */ - fx: { - tick: () => void; - /** - * The rate (in milliseconds) at which animations fire. - */ - interval: number; - stop: () => void; - speeds: { slow: number; fast: number; }; - /** - * Globally disable all animations. - */ - off: boolean; - step: any; - }; - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fnction The function whose context will be changed. - * @param context The object to which the context (this) of the function should be set. - * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - */ - proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param context The object to which the context (this) of the function should be set. - * @param name The name of the function whose context will be changed (should be a property of the context object). - * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. - */ - proxy(context: Object, name: string, ...additionalArguments: any[]): any; - - Event: JQueryEventConstructor; - - /** - * Takes a string and throws an exception containing it. - * - * @param message The message to send out. - */ - error(message: any): JQuery; - - expr: any; - fn: any; //TODO: Decide how we want to type this - - isReady: boolean; - - // Properties - support: JQuerySupport; - - /** - * Check to see if a DOM element is a descendant of another DOM element. - * - * @param container The DOM element that may contain the other element. - * @param contained The DOM element that may be contained by (a descendant of) the other element. - */ - contains(container: Element, contained: Element): boolean; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: T[], - callback: (indexInArray: number, valueOfElement: T) => any - ): any; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: any, - callback: (indexInArray: any, valueOfElement: any) => any - ): any; - - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(target: any, object1?: any, ...objectN: any[]): any; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; - - /** - * Execute some JavaScript code globally. - * - * @param code The JavaScript code to execute. - */ - globalEval(code: string): any; - - /** - * Finds the elements of an array which satisfy a filter function. The original array is not affected. - * - * @param array The array to search through. - * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. - * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. - */ - grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; - - /** - * Search for a specified value within an array and return its index (or -1 if not found). - * - * @param value The value to search for. - * @param array An array through which to search. - * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. - */ - inArray(value: T, array: T[], fromIndex?: number): number; - - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - */ - isArray(obj: any): boolean; - /** - * Check to see if an object is empty (contains no enumerable properties). - * - * @param obj The object that will be checked to see if it's empty. - */ - isEmptyObject(obj: any): boolean; - /** - * Determine if the argument passed is a Javascript function object. - * - * @param obj Object to test whether or not it is a function. - */ - isFunction(obj: any): boolean; - /** - * Determines whether its argument is a number. - * - * @param obj The value to be tested. - */ - isNumeric(value: any): boolean; - /** - * Check to see if an object is a plain object (created using "{}" or "new Object"). - * - * @param obj The object that will be checked to see if it's a plain object. - */ - isPlainObject(obj: any): boolean; - /** - * Determine whether the argument is a window. - * - * @param obj Object to test whether or not it is a window. - */ - isWindow(obj: any): boolean; - /** - * Check to see if a DOM node is within an XML document (or is an XML document). - * - * @param node he DOM node that will be checked to see if it's in an XML document. - */ - isXMLDoc(node: Node): boolean; - - /** - * Convert an array-like object into a true JavaScript array. - * - * @param obj Any object to turn into a native Array. - */ - makeArray(obj: any): any[]; - - /** - * Translate all items in an array or object to new array of items. - * - * @param array The Array to translate. - * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. - */ - map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param arrayOrObject The Array or Object to translate. - * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. - */ - map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; - - /** - * Merge the contents of two arrays together into the first array. - * - * @param first The first array to merge, the elements of second added. - * @param second The second array to merge into the first, unaltered. - */ - merge(first: T[], second: T[]): T[]; - - /** - * An empty function. - */ - noop(): any; - - /** - * Return a number representing the current time. - */ - now(): number; - - /** - * Takes a well-formed JSON string and returns the resulting JavaScript object. - * - * @param json The JSON string to parse. - */ - parseJSON(json: string): any; - - /** - * Parses a string into an XML document. - * - * @param data a well-formed XML string to be parsed - */ - parseXML(data: string): XMLDocument; - - /** - * Remove the whitespace from the beginning and end of a string. - * - * @param str Remove the whitespace from the beginning and end of a string. - */ - trim(str: string): string; - - /** - * Determine the internal JavaScript [[Class]] of an object. - * - * @param obj Object to get the internal JavaScript [[Class]] of. - */ - type(obj: any): string; - - /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. - * - * @param array The Array of DOM elements. - */ - unique(array: Element[]): Element[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; -} - -/** - * The jQuery instance members - */ -interface JQuery { - /** - * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. - * - * @param handler The function to be invoked. - */ - ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery; - /** - * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery; - /** - * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery; - /** - * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStart(handler: () => any): JQuery; - /** - * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStop(handler: () => any): JQuery; - /** - * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery; - - /** - * Load data from the server and place the returned HTML into the matched element. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param complete A callback function that is executed when the request completes. - */ - load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; - - /** - * Encode a set of form elements as a string for submission. - */ - serialize(): string; - /** - * Encode a set of form elements as an array of names and values. - */ - serializeArray(): JQuerySerializeArrayElement[]; - - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param className One or more space-separated classes to be added to the class attribute of each matched element. - */ - addClass(className: string): JQuery; - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. - */ - addClass(func: (index: number, className: string) => string): JQuery; - - /** - * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. - */ - addBack(selector?: string): JQuery; - - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - */ - attr(attributeName: string): string; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param value A value to set for the attribute. - */ - attr(attributeName: string, value: string|number): JQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. - */ - attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributes An object of attribute-value pairs to set. - */ - attr(attributes: Object): JQuery; - - /** - * Determine whether any of the matched elements are assigned the given class. - * - * @param className The class name to search for. - */ - hasClass(className: string): boolean; - - /** - * Get the HTML contents of the first element in the set of matched elements. - */ - html(): string; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param htmlString A string of HTML to set as the content of each matched element. - */ - html(htmlString: string): JQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - html(func: (index: number, oldhtml: string) => string): JQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - - /** - * Get the value of a property for the first element in the set of matched elements. - * - * @param propertyName The name of the property to get. - */ - prop(propertyName: string): any; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param value A value to set for the property. - */ - prop(propertyName: string, value: string|number|boolean): JQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - prop(properties: Object): JQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. - */ - prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; - - /** - * Remove an attribute from each element in the set of matched elements. - * - * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. - */ - removeAttr(attributeName: string): JQuery; - - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - */ - removeClass(className?: string): JQuery; - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. - */ - removeClass(func: (index: number, className: string) => string): JQuery; - - /** - * Remove a property for the set of matched elements. - * - * @param propertyName The name of the property to remove. - */ - removeProp(propertyName: string): JQuery; - - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - */ - toggleClass(className: string, swtch?: boolean): JQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(swtch?: boolean): JQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; - - /** - * Get the current value of the first element in the set of matched elements. - */ - val(): any; - /** - * Set the value of each element in the set of matched elements. - * - * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. - */ - val(value: string|string[]): JQuery; - /** - * Set the value of each element in the set of matched elements. - * - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - val(func: (index: number, value: string) => string): JQuery; - - - /** - * Get the value of style properties for the first element in the set of matched elements. - * - * @param propertyName A CSS property. - */ - css(propertyName: string): string; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - */ - css(propertyName: string, value: string|number): JQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - css(propertyName: string, value: (index: number, value: string) => string|number): JQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - css(properties: Object): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements. - */ - height(): number; - /** - * Set the CSS height of every matched element. - * - * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). - */ - height(value: number|string): JQuery; - /** - * Set the CSS height of every matched element. - * - * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. - */ - height(func: (index: number, height: number) => number|string): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding but not border. - */ - innerHeight(): number; - - /** - * Sets the inner height on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerHeight(height: number|string): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding but not border. - */ - innerWidth(): number; - - /** - * Sets the inner width on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerWidth(width: number|string): JQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the document. - */ - offset(): JQueryCoordinates; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - */ - offset(coordinates: JQueryCoordinates): JQuery; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. - */ - offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerHeight(includeMargin?: boolean): number; - - /** - * Sets the outer height on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerHeight(height: number|string): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding and border. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerWidth(includeMargin?: boolean): number; - - /** - * Sets the outer width on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerWidth(width: number|string): JQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. - */ - position(): JQueryCoordinates; - - /** - * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. - */ - scrollLeft(): number; - /** - * Set the current horizontal position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollLeft(value: number): JQuery; - - /** - * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. - */ - scrollTop(): number; - /** - * Set the current vertical position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollTop(value: number): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements. - */ - width(): number; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - width(value: number|string): JQuery; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. - */ - width(func: (index: number, width: number) => number|string): JQuery; - - /** - * Remove from the queue all items that have not yet been run. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - clearQueue(queueName?: string): JQuery; - - /** - * Store arbitrary data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - */ - data(key: string, value: any): JQuery; - /** - * Store arbitrary data associated with the matched elements. - * - * @param obj An object of key-value pairs of data to update. - */ - data(obj: { [key: string]: any; }): JQuery; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - * - * @param key Name of the data stored. - */ - data(key: string): any; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - */ - data(): any; - - /** - * Execute the next function on the queue for the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(queueName?: string): JQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. - */ - removeData(name: string): JQuery; - /** - * Remove a previously-stored piece of data. - * - * @param list An array of strings naming the pieces of data to delete. - */ - removeData(list: string[]): JQuery; - - /** - * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. - * - * @param type The type of queue that needs to be observed. (default: fx) - * @param target Object onto which the promise methods have to be attached - */ - promise(type?: string, target?: Object): JQueryPromise; - - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, complete?: Function): JQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. (default: swing) - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param options A map of additional options to pass to the method. - */ - animate(properties: Object, options: JQueryAnimationOptions): JQuery; - - /** - * Set a timer to delay execution of subsequent items in the queue. - * - * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - delay(duration: number, queueName?: string): JQuery; - - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param options A map of additional options to pass to the method. - */ - fadeIn(options: JQueryAnimationOptions): JQuery; - - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param options A map of additional options to pass to the method. - */ - fadeOut(options: JQueryAnimationOptions): JQuery; - - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery; - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery; - - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param options A map of additional options to pass to the method. - */ - fadeToggle(options: JQueryAnimationOptions): JQuery; - - /** - * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. - * - * @param queue The name of the queue in which to stop animations. - */ - finish(queue?: string): JQuery; - - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - hide(options: JQueryAnimationOptions): JQuery; - - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - show(options: JQueryAnimationOptions): JQuery; - - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideDown(options: JQueryAnimationOptions): JQuery; - - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideToggle(options: JQueryAnimationOptions): JQuery; - - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideUp(options: JQueryAnimationOptions): JQuery; - - /** - * Stop the currently-running animation on the matched elements. - * - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - /** - * Stop the currently-running animation on the matched elements. - * - * @param queue The name of the queue in which to stop animations. - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - toggle(options: JQueryAnimationOptions): JQuery; - /** - * Display or hide the matched elements. - * - * @param showOrHide A Boolean indicating whether to show or hide the elements. - */ - toggle(showOrHide: boolean): JQuery; - - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, preventBubble: boolean): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param events An object containing one or more DOM event types and functions to execute for them. - */ - bind(events: any): JQuery; - - /** - * Trigger the "blur" event on an element - */ - blur(): JQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - blur(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "change" event on an element. - */ - change(): JQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - change(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "click" event on an element. - */ - click(): JQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - */ - click(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "dblclick" event on an element. - */ - dblclick(): JQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "focus" event on an element. - */ - focus(): JQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focus(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * - * @param handlerIn A function to execute when the mouse pointer enters the element. - * @param handlerOut A function to execute when the mouse pointer leaves the element. - */ - hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. - * - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. - */ - hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "keydown" event on an element. - */ - keydown(): JQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Trigger the "keypress" event on an element. - */ - keypress(): JQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Trigger the "keyup" event on an element. - */ - keyup(): JQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - load(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "mousedown" event on an element. - */ - mousedown(): JQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseenter" event on an element. - */ - mouseenter(): JQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseleave" event on an element. - */ - mouseleave(): JQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mousemove" event on an element. - */ - mousemove(): JQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseout" event on an element. - */ - mouseout(): JQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseover" event on an element. - */ - mouseover(): JQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseup" event on an element. - */ - mouseup(): JQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Remove an event handler. - */ - off(): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove an event handler. - * - * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - */ - off(events: { [key: string]: any; }, selector?: string): JQuery; - - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, data?: any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param data An object containing data that will be passed to the event handler. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, data?: any): JQuery; - - - /** - * Specify a function to execute when the DOM is fully loaded. - * - * @param handler A function to execute after the DOM is ready. - */ - ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; - - /** - * Trigger the "resize" event on an element. - */ - resize(): JQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - resize(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "scroll" event on an element. - */ - scroll(): JQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "select" event on an element. - */ - select(): JQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - select(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "submit" event on an element. - */ - submit(): JQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - submit(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(eventType: string, extraParameters?: any[]|Object): JQuery; - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param event A jQuery.Event object. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery; - - /** - * Execute all handlers attached to an element for an event. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters An array of additional parameters to pass along to the event handler. - */ - triggerHandler(eventType: string, ...extraParameters: any[]): Object; - - /** - * Execute all handlers attached to an element for an event. - * - * @param event A jQuery.Event object. - * @param extraParameters An array of additional parameters to pass along to the event handler. - */ - triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object; - - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param handler The function that is to be no longer executed. - */ - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). - */ - unbind(eventType: string, fls: boolean): JQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param evt A JavaScript event object as passed to an event handler. - */ - unbind(evt: any): JQuery; - - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - */ - undelegate(): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" - * @param handler A function to execute at the time the event is triggered. - */ - undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param events An object of one or more event types and previously bound functions to unbind from them. - */ - undelegate(selector: string, events: Object): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param namespace A string containing a namespace to unbind all events from. - */ - undelegate(namespace: string): JQuery; - - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - unload(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) - */ - context: Element; - - jquery: string; - - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - error(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - */ - pushStack(elements: any[]): JQuery; - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - * @param name The name of a jQuery method that generated the array of elements. - * @param arguments The arguments that were passed in to the jQuery method (for serialization). - */ - pushStack(elements: any[], name: string, arguments: any[]): JQuery; - - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. - */ - after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - after(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. - */ - append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - append(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert every element in the set of matched elements to the end of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. - */ - appendTo(target: JQuery|any[]|Element|string): JQuery; - - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. - */ - before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - before(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Create a deep copy of the set of matched elements. - * - * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. - * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). - */ - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * param selector A selector expression that filters the set of matched elements to be removed. - */ - detach(selector?: string): JQuery; - - /** - * Remove all child nodes of the set of matched elements from the DOM. - */ - empty(): JQuery; - - /** - * Insert every element in the set of matched elements after the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. - */ - insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; - - /** - * Insert every element in the set of matched elements before the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. - */ - insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; - - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. - */ - prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert every element in the set of matched elements to the beginning of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. - */ - prependTo(target: JQuery|any[]|Element|string): JQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - */ - remove(selector?: string): JQuery; - - /** - * Replace each target element with the set of matched elements. - * - * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. - */ - replaceAll(target: JQuery|any[]|Element|string): JQuery; - - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. - */ - replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param func A function that returns content with which to replace the set of matched elements. - */ - replaceWith(func: () => Element|JQuery): JQuery; - - /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - */ - text(): string; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. - */ - text(text: string|number|boolean): JQuery; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. - */ - text(func: (index: number, text: string) => string): JQuery; - - /** - * Retrieve all the elements contained in the jQuery set, as an array. - */ - toArray(): any[]; - - /** - * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - */ - unwrap(): JQuery; - - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrap(wrappingElement: JQuery|Element|string): JQuery; - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrap(func: (index: number) => string|JQuery): JQuery; - - /** - * Wrap an HTML structure around all elements in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrapAll(wrappingElement: JQuery|Element|string): JQuery; - wrapAll(func: (index: number) => string): JQuery; - - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. - */ - wrapInner(wrappingElement: JQuery|Element|string): JQuery; - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrapInner(func: (index: number) => string): JQuery; - - /** - * Iterate over a jQuery object, executing a function for each matched element. - * - * @param func A function to execute for each matched element. - */ - each(func: (index: number, elem: Element) => any): JQuery; - - /** - * Retrieve one of the elements matched by the jQuery object. - * - * @param index A zero-based integer indicating which element to retrieve. - */ - get(index: number): HTMLElement; - /** - * Retrieve the elements matched by the jQuery object. - */ - get(): any[]; - - /** - * Search for a given element from among the matched elements. - */ - index(): number; - /** - * Search for a given element from among the matched elements. - * - * @param selector A selector representing a jQuery collection in which to look for an element. - */ - index(selector: string|JQuery|Element): number; - - /** - * The number of elements in the jQuery object. - */ - length: number; - /** - * A selector representing selector passed to jQuery(), if any, when creating the original set. - * version deprecated: 1.7, removed: 1.9 - */ - selector: string; - [index: string]: any; - [index: number]: HTMLElement; - - /** - * Add elements to the set of matched elements. - * - * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. - * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. - */ - add(selector: string, context?: Element): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param elements One or more elements to add to the set of matched elements. - */ - add(...elements: Element[]): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param html An HTML fragment to add to the set of matched elements. - */ - add(html: string): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param obj An existing jQuery object to add to the set of matched elements. - */ - add(obj: JQuery): JQuery; - - /** - * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - children(selector?: string): JQuery; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - */ - closest(selector: string): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selector: string, context?: Element): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param obj A jQuery object to match elements against. - */ - closest(obj: JQuery): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param element An element to match elements against. - */ - closest(element: Element): JQuery; - - /** - * Get an array of all the elements and selectors matched against the current element up through the DOM tree. - * - * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selectors: any, context?: Element): any[]; - - /** - * Get the children of each element in the set of matched elements, including text and comment nodes. - */ - contents(): JQuery; - - /** - * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. - */ - end(): JQuery; - - /** - * Reduce the set of matched elements to the one at the specified index. - * - * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. - * - */ - eq(index: number): JQuery; - - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param selector A string containing a selector expression to match the current set of elements against. - */ - filter(selector: string): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - filter(func: (index: number, element: Element) => any): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param element An element to match the current set of elements against. - */ - filter(element: Element): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - filter(obj: JQuery): JQuery; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param selector A string containing a selector expression to match elements against. - */ - find(selector: string): JQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param element An element to match elements against. - */ - find(element: Element): JQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param obj A jQuery object to match elements against. - */ - find(obj: JQuery): JQuery; - - /** - * Reduce the set of matched elements to the first in the set. - */ - first(): JQuery; - - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - */ - has(selector: string): JQuery; - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param contained A DOM element to match elements against. - */ - has(contained: Element): JQuery; - - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - */ - is(selector: string): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. - */ - is(func: (index: number, element: Element) => boolean): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - is(obj: JQuery): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - */ - is(elements: any): boolean; - - /** - * Reduce the set of matched elements to the final one in the set. - */ - last(): JQuery; - - /** - * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. - * - * @param callback A function object that will be invoked for each element in the current set. - */ - map(callback: (index: number, domElement: Element) => any): JQuery; - - /** - * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - next(selector?: string): JQuery; - - /** - * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - nextAll(selector?: string): JQuery; - - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(selector?: string, filter?: string): JQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(element?: Element, filter?: string): JQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Remove elements from the set of matched elements. - * - * @param selector A string containing a selector expression to match elements against. - */ - not(selector: string): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - not(func: (index: number, element: Element) => boolean): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param elements One or more DOM elements to remove from the matched set. - */ - not(...elements: Element[]): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - not(obj: JQuery): JQuery; - - /** - * Get the closest ancestor element that is positioned. - */ - offsetParent(): JQuery; - - /** - * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parent(selector?: string): JQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parents(selector?: string): JQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(selector?: string, filter?: string): JQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(element?: Element, filter?: string): JQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prev(selector?: string): JQuery; - - /** - * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prevAll(selector?: string): JQuery; - - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(selector?: string, filter?: string): JQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(element?: Element, filter?: string): JQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - siblings(selector?: string): JQuery; - - /** - * Reduce the set of matched elements to a subset specified by a range of indices. - * - * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. - * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. - */ - slice(start: number, end?: number): JQuery; - - /** - * Show the queue of functions to be executed on the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(callback: Function): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(queueName: string, newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(queueName: string, callback: Function): JQuery; -} -declare module "jquery" { - export = $; -} -declare var jQuery: JQueryStatic; -declare var $: JQueryStatic; diff --git a/typings/lodash/lodash.d.ts b/typings/lodash/lodash.d.ts deleted file mode 100644 index 247a8f4..0000000 --- a/typings/lodash/lodash.d.ts +++ /dev/null @@ -1,6696 +0,0 @@ -// Type definitions for Lo-Dash -// Project: http://lodash.com/ -// Definitions by: Brian Zengel -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare var _: _.LoDashStatic; - -declare module _ { - interface LoDashStatic { - /** - * Creates a lodash object which wraps the given value to enable intuitive method chaining. - * - * In addition to Lo-Dash methods, wrappers also have the following Array methods: - * concat, join, pop, push, reverse, shift, slice, sort, splice, and unshift - * - * Chaining is supported in custom builds as long as the value method is implicitly or - * explicitly included in the build. - * - * The chainable wrapper functions are: - * after, assign, bind, bindAll, bindKey, chain, chunk, compact, compose, concat, countBy, - * createCallback, curry, debounce, defaults, defer, delay, difference, filter, flatten, - * forEach, forEachRight, forIn, forInRight, forOwn, forOwnRight, functions, groupBy, - * indexBy, initial, intersection, invert, invoke, keys, map, max, memoize, merge, min, - * object, omit, once, pairs, partial, partialRight, pick, pluck, pull, push, range, reject, - * remove, rest, reverse, sample, shuffle, slice, sort, sortBy, splice, tap, throttle, times, - * toArray, transform, union, uniq, unshift, unzip, values, where, without, wrap, and zip - * - * The non-chainable wrapper functions are: - * clone, cloneDeep, contains, escape, every, find, findIndex, findKey, findLast, - * findLastIndex, findLastKey, has, identity, indexOf, isArguments, isArray, isBoolean, - * isDate, isElement, isEmpty, isEqual, isFinite, isFunction, isNaN, isNull, isNumber, - * isObject, isPlainObject, isRegExp, isString, isUndefined, join, lastIndexOf, mixin, - * noConflict, parseInt, pop, random, reduce, reduceRight, result, shift, size, some, - * sortedIndex, runInContext, template, unescape, uniqueId, and value - * - * The wrapper functions first and last return wrapped values when n is provided, otherwise - * they return unwrapped values. - * - * Explicit chaining can be enabled by using the _.chain method. - **/ - (value: number): LoDashWrapper; - (value: string): LoDashWrapper; - (value: boolean): LoDashWrapper; - (value: Array): LoDashNumberArrayWrapper; - (value: Array): LoDashArrayWrapper; - (value: T): LoDashObjectWrapper; - (value: any): LoDashWrapper; - - /** - * The semantic version number. - **/ - VERSION: string; - - /** - * An object used to flag environments features. - **/ - support: Support; - - /** - * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby - * (ERB). Change the following template settings to use alternative delimiters. - **/ - templateSettings: TemplateSettings; - } - - /** - * By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby - * (ERB). Change the following template settings to use alternative delimiters. - **/ - interface TemplateSettings { - /** - * The "escape" delimiter. - **/ - escape?: RegExp; - - /** - * The "evaluate" delimiter. - **/ - evaluate?: RegExp; - - /** - * An object to import into the template as local variables. - **/ - imports?: Dictionary; - - /** - * The "interpolate" delimiter. - **/ - interpolate?: RegExp; - - /** - * Used to reference the data object in the template text. - **/ - variable?: string; - } - - /** - * An object used to flag environments features. - **/ - interface Support { - /** - * Detect if an arguments object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). - **/ - argsClass: boolean; - - /** - * Detect if arguments objects are Object objects (all but Narwhal and Opera < 10.5). - **/ - argsObject: boolean; - - /** - * Detect if name or message properties of Error.prototype are enumerable by default. - * (IE < 9, Safari < 5.1) - **/ - enumErrorProps: boolean; - - /** - * Detect if Function#bind exists and is inferred to be fast (all but V8). - **/ - fastBind: boolean; - - /** - * Detect if functions can be decompiled by Function#toString (all but PS3 and older Opera - * mobile browsers & avoided in Windows 8 apps). - **/ - funcDecomp: boolean; - - /** - * Detect if Function#name is supported (all but IE). - **/ - funcNames: boolean; - - /** - * Detect if arguments object indexes are non-enumerable (Firefox < 4, IE < 9, PhantomJS, - * Safari < 5.1). - **/ - nonEnumArgs: boolean; - - /** - * Detect if properties shadowing those on Object.prototype are non-enumerable. - * - * In IE < 9 an objects own properties, shadowing non-enumerable ones, are made - * non-enumerable as well (a.k.a the JScript [[DontEnum]] bug). - **/ - nonEnumShadows: boolean; - - /** - * Detect if own properties are iterated after inherited properties (all but IE < 9). - **/ - ownLast: boolean; - - /** - * Detect if Array#shift and Array#splice augment array-like objects correctly. - * - * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array shift() and splice() - * functions that fail to remove the last element, value[0], of array-like objects even - * though the length property is set to 0. The shift() method is buggy in IE 8 compatibility - * mode, while splice() is buggy regardless of mode in IE < 9 and buggy in compatibility mode - * in IE 9. - **/ - spliceObjects: boolean; - - /** - * Detect lack of support for accessing string characters by index. - * - * IE < 8 can't access characters by index and IE 8 can only access characters by index on - * string literals. - **/ - unindexedChars: boolean; - } - - interface LoDashWrapperBase { - /** - * Produces the toString result of the wrapped value. - * @return Returns the string result. - **/ - toString(): string; - - /** - * Extracts the wrapped value. - * @return The wrapped value. - **/ - valueOf(): T; - - /** - * @see valueOf - **/ - value(): T; - } - - interface LoDashWrapper extends LoDashWrapperBase> { } - - interface LoDashObjectWrapper extends LoDashWrapperBase> { } - - interface LoDashArrayWrapper extends LoDashWrapperBase> { - concat(...items: T[]): LoDashArrayWrapper; - join(seperator?: string): LoDashWrapper; - pop(): LoDashWrapper; - push(...items: T[]): void; - reverse(): LoDashArrayWrapper; - shift(): LoDashWrapper; - slice(start: number, end?: number): LoDashArrayWrapper; - sort(compareFn?: (a: T, b: T) => number): LoDashArrayWrapper; - splice(start: number): LoDashArrayWrapper; - splice(start: number, deleteCount: number, ...items: any[]): LoDashArrayWrapper; - unshift(...items: any[]): LoDashWrapper; - } - - interface LoDashNumberArrayWrapper extends LoDashArrayWrapper { } - - //_.chain - interface LoDashStatic { - /** - * Creates a lodash object that wraps the given value with explicit method chaining enabled. - * @param value The value to wrap. - * @return The wrapper object. - **/ - chain(value: number): LoDashWrapper; - chain(value: string): LoDashWrapper; - chain(value: boolean): LoDashWrapper; - chain(value: Array): LoDashArrayWrapper; - chain(value: T): LoDashObjectWrapper; - chain(value: any): LoDashWrapper; - } - - interface LoDashWrapperBase { - /** - * Enables explicit method chaining on the wrapper object. - * @see _.chain - * @return The wrapper object. - **/ - chain(): TWrapper; - } - - //_.tap - interface LoDashStatic { - /** - * Invokes interceptor with the value as the first argument and then returns value. The - * purpose of this method is to "tap into" a method chain in order to perform operations on - * intermediate results within the chain. - * @param value The value to provide to interceptor - * @param interceptor The function to invoke. - * @return value - **/ - tap( - value: T, - interceptor: (value: T) => void): T; - } - - interface LoDashWrapperBase { - /** - * @see _.tap - **/ - tap(interceptor: (value: T) => void): TWrapper; - } - - /********* - * Arrays * - **********/ - - //_.chunk - interface LoDashStatic { - /** - * Creates an array of elements split into groups the length of size. If collection can't be - * split evenly, the final chunk will be the remaining elements. - * @param array The array to process. - * @param size The length of each chunk. - * @return Returns the new array containing chunks. - **/ - chunk(array: Array, size?: number): T[][]; - - /** - * @see _.chunk - **/ - chunk(array: List, size?: number): T[][]; - } - - interface LoDashArrayWrapper { - /** - * @see _.chunk - **/ - chunk(size?: number): LoDashArrayWrapper; - } - - //_.compact - interface LoDashStatic { - /** - * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", - * undefined and NaN are all falsy. - * @param array Array to compact. - * @return (Array) Returns a new array of filtered values. - **/ - compact(array?: Array): T[]; - - /** - * @see _.compact - **/ - compact(array?: List): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.compact - **/ - compact(): LoDashArrayWrapper; - } - - //_.difference - interface LoDashStatic { - /** - * Creates an array excluding all values of the provided arrays using strict equality for comparisons - * , i.e. ===. - * @param array The array to process - * @param others The arrays of values to exclude. - * @return Returns a new array of filtered values. - **/ - difference( - array?: Array, - ...others: Array[]): T[]; - /** - * @see _.difference - **/ - difference( - array?: List, - ...others: List[]): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.difference - **/ - difference( - ...others: Array[]): LoDashArrayWrapper; - /** - * @see _.difference - **/ - difference( - ...others: List[]): LoDashArrayWrapper; - } - - //_.findIndex - interface LoDashStatic { - /** - * This method is like _.find except that it returns the index of the first element that passes - * the callback check, instead of the element itself. - * @param array The array to search. - * @param {(Function|Object|string)} callback The function called per iteration. If a property name or object is provided it will be - * used to create a ".pluck" or ".where" style callback, respectively. - * @param thisArg The this binding of callback. - * @return Returns the index of the found element, else -1. - **/ - findIndex( - array: Array, - callback: ListIterator, - thisArg?: any): number; - - /** - * @see _.findIndex - **/ - findIndex( - array: List, - callback: ListIterator, - thisArg?: any): number; - - /** - * @see _.findIndex - **/ - findIndex( - array: Array, - pluckValue: string): number; - - /** - * @see _.findIndex - **/ - findIndex( - array: List, - pluckValue: string): number; - - /** - * @see _.findIndex - **/ - findIndex( - array: Array, - whereDictionary: W): number; - - /** - * @see _.findIndex - **/ - findIndex( - array: List, - whereDictionary: W): number; - } - - //_.findLastIndex - interface LoDashStatic { - /** - * This method is like _.findIndex except that it iterates over elements of a collection from right to left. - * @param array The array to search. - * @param {(Function|Object|string)} callback The function called per iteration. If a property name or object is provided it will be - * used to create a ".pluck" or ".where" style callback, respectively. - * @param thisArg The this binding of callback. - * @return Returns the index of the found element, else -1. - **/ - findLastIndex( - array: Array, - callback: ListIterator, - thisArg?: any): number; - - /** - * @see _.findLastIndex - **/ - findLastIndex( - array: List, - callback: ListIterator, - thisArg?: any): number; - - /** - * @see _.findLastIndex - **/ - findLastIndex( - array: Array, - pluckValue: string): number; - - /** - * @see _.findLastIndex - **/ - findLastIndex( - array: List, - pluckValue: string): number; - - /** - * @see _.findLastIndex - **/ - findLastIndex( - array: Array, - whereDictionary: Dictionary): number; - - /** - * @see _.findLastIndex - **/ - findLastIndex( - array: List, - whereDictionary: Dictionary): number; - } - - //_.first - interface LoDashStatic { - /** - * Gets the first element or first n elements of an array. If a callback is provided - * elements at the beginning of the array are returned as long as the callback returns - * truey. The callback is bound to thisArg and invoked with three arguments; (value, - * index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback - * will return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return ] - * true for elements that have the properties of the given object, else false. - * @param array Retrieves the first element of this array. - * @return Returns the first element of `array`. - **/ - first(array?: Array): T; - - /** - * @see _.first - **/ - first(array?: List): T; - - /** - * @see _.first - * @param n The number of elements to return. - **/ - first( - array: Array, - n: number): T[]; - - /** - * @see _.first - * @param n The number of elements to return. - **/ - first( - array: List, - n: number): T[]; - - /** - * @see _.first - * @param callback The function called per element. - * @param [thisArg] The this binding of callback. - **/ - first( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.first - * @param callback The function called per element. - * @param [thisArg] The this binding of callback. - **/ - first( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.first - * @param pluckValue "_.pluck" style callback value - **/ - first( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.first - * @param pluckValue "_.pluck" style callback value - **/ - first( - array: List, - pluckValue: string): T[]; - - /** - * @see _.first - * @param whereValue "_.where" style callback value - **/ - first( - array: Array, - whereValue: W): T[]; - - /** - * @see _.first - * @param whereValue "_.where" style callback value - **/ - first( - array: List, - whereValue: W): T[]; - - /** - * @see _.first - **/ - head(array: Array): T; - - /** - * @see _.first - **/ - head(array: List): T; - - /** - * @see _.first - **/ - head( - array: Array, - n: number): T[]; - - /** - * @see _.first - **/ - head( - array: List, - n: number): T[]; - - /** - * @see _.first - **/ - head( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.first - **/ - head( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.first - **/ - head( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.first - **/ - head( - array: List, - pluckValue: string): T[]; - - /** - * @see _.first - **/ - head( - array: Array, - whereValue: W): T[]; - - /** - * @see _.first - **/ - head( - array: List, - whereValue: W): T[]; - - /** - * @see _.first - **/ - take(array: Array): T; - - /** - * @see _.first - **/ - take(array: List): T; - - /** - * @see _.first - **/ - take( - array: Array, - n: number): T[]; - - /** - * @see _.first - **/ - take( - array: List, - n: number): T[]; - - /** - * @see _.first - **/ - take( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.first - **/ - take( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.first - **/ - take( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.first - **/ - take( - array: List, - pluckValue: string): T[]; - - /** - * @see _.first - **/ - take( - array: Array, - whereValue: W): T[]; - - /** - * @see _.first - **/ - take( - array: List, - whereValue: W): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.first - **/ - first(): T; - - /** - * @see _.first - * @param n The number of elements to return. - **/ - first(n: number): LoDashArrayWrapper; - - /** - * @see _.first - * @param callback The function called per element. - * @param [thisArg] The this binding of callback. - **/ - first( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.first - * @param pluckValue "_.pluck" style callback value - **/ - first(pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.first - * @param whereValue "_.where" style callback value - **/ - first(whereValue: W): LoDashArrayWrapper; - - /** - * @see _.first - **/ - head(): T; - - /** - * @see _.first - * @param n The number of elements to return. - **/ - head(n: number): LoDashArrayWrapper; - - /** - * @see _.first - * @param callback The function called per element. - * @param [thisArg] The this binding of callback. - **/ - head( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.first - * @param pluckValue "_.pluck" style callback value - **/ - head(pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.first - * @param whereValue "_.where" style callback value - **/ - head(whereValue: W): LoDashArrayWrapper; - - /** - * @see _.first - **/ - take(): T; - - /** - * @see _.first - * @param n The number of elements to return. - **/ - take(n: number): LoDashArrayWrapper; - - /** - * @see _.first - * @param callback The function called per element. - * @param [thisArg] The this binding of callback. - **/ - take( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.first - * @param pluckValue "_.pluck" style callback value - **/ - take(pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.first - * @param whereValue "_.where" style callback value - **/ - take(whereValue: W): LoDashArrayWrapper; - } - - //_.flatten - interface LoDashStatic { - /** - * Flattens a nested array (the nesting can be to any depth). If isShallow is truey, the - * array will only be flattened a single level. If a callback is provided each element of - * the array is passed through the callback before flattening. The callback is bound to - * thisArg and invoked with three arguments; (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The array to flatten. - * @param shallow If true then only flatten one level, optional, default = false. - * @return `array` flattened. - **/ - flatten(array: Array, isShallow?: boolean): T[]; - - /** - * @see _.flatten - **/ - flatten(array: List, isShallow?: boolean): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - pluckValue: string): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.flatten - **/ - flatten(isShallow?: boolean): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - isShallow: boolean, - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - isShallow: boolean, - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - isShallow: boolean, - whereValue: W): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - whereValue: W): LoDashArrayWrapper; - } - - //_.indexOf - interface LoDashStatic { - /** - * Gets the index at which the first occurrence of value is found using strict equality - * for comparisons, i.e. ===. If the array is already sorted providing true for fromIndex - * will run a faster binary search. - * @param array The array to search. - * @param value The value to search for. - * @param fromIndex The index to search from. - * @return The index of `value` within `array`. - **/ - indexOf( - array: Array, - value: T): number; - - /** - * @see _.indexOf - **/ - indexOf( - array: List, - value: T): number; - - /** - * @see _.indexOf - * @param fromIndex The index to search from - **/ - indexOf( - array: Array, - value: T, - fromIndex: number): number; - - /** - * @see _.indexOf - * @param fromIndex The index to search from - **/ - indexOf( - array: List, - value: T, - fromIndex: number): number; - - /** - * @see _.indexOf - * @param isSorted True to perform a binary search on a sorted array. - **/ - indexOf( - array: Array, - value: T, - isSorted: boolean): number; - - /** - * @see _.indexOf - * @param isSorted True to perform a binary search on a sorted array. - **/ - indexOf( - array: List, - value: T, - isSorted: boolean): number; - } - - //_.initial - interface LoDashStatic { - /** - * Gets all but the last element or last n elements of an array. If a callback is provided - * elements at the end of the array are excluded from the result as long as the callback - * returns truey. The callback is bound to thisArg and invoked with three arguments; - * (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The array to query. - * @param n Leaves this many elements behind, optional. - * @return Returns everything but the last `n` elements of `array`. - **/ - initial( - array: Array): T[]; - - /** - * @see _.initial - **/ - initial( - array: List): T[]; - - /** - * @see _.initial - * @param n The number of elements to exclude. - **/ - initial( - array: Array, - n: number): T[]; - - /** - * @see _.initial - * @param n The number of elements to exclude. - **/ - initial( - array: List, - n: number): T[]; - - /** - * @see _.initial - * @param callback The function called per element - **/ - initial( - array: Array, - callback: ListIterator): T[]; - - /** - * @see _.initial - * @param callback The function called per element - **/ - initial( - array: List, - callback: ListIterator): T[]; - - /** - * @see _.initial - * @param pluckValue _.pluck style callback - **/ - initial( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.initial - * @param pluckValue _.pluck style callback - **/ - initial( - array: List, - pluckValue: string): T[]; - - /** - * @see _.initial - * @param whereValue _.where style callback - **/ - initial( - array: Array, - whereValue: W): T[]; - - /** - * @see _.initial - * @param whereValue _.where style callback - **/ - initial( - array: List, - whereValue: W): T[]; - } - - //_.intersection - interface LoDashStatic { - /** - * Creates an array of unique values present in all provided arrays using strict - * equality for comparisons, i.e. ===. - * @param arrays The arrays to inspect. - * @return Returns an array of composite values. - **/ - intersection(...arrays: Array[]): T[]; - - /** - * @see _.intersection - **/ - intersection(...arrays: List[]): T[]; - } - - //_.last - interface LoDashStatic { - /** - * Gets the last element or last n elements of an array. If a callback is provided - * elements at the end of the array are returned as long as the callback returns truey. - * The callback is bound to thisArg and invoked with three arguments; (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The array to query. - * @return Returns the last element(s) of array. - **/ - last(array: Array): T; - - /** - * @see _.last - **/ - last(array: List): T; - - /** - * @see _.last - * @param n The number of elements to return - **/ - last( - array: Array, - n: number): T[]; - - /** - * @see _.last - * @param n The number of elements to return - **/ - last( - array: List, - n: number): T[]; - - /** - * @see _.last - * @param callback The function called per element - **/ - last( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.last - * @param callback The function called per element - **/ - last( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.last - * @param pluckValue _.pluck style callback - **/ - last( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.last - * @param pluckValue _.pluck style callback - **/ - last( - array: List, - pluckValue: string): T[]; - - /** - * @see _.last - * @param whereValue _.where style callback - **/ - last( - array: Array, - whereValue: W): T[]; - - /** - * @see _.last - * @param whereValue _.where style callback - **/ - last( - array: List, - whereValue: W): T[]; - } - - //_.lastIndexOf - interface LoDashStatic { - /** - * Gets the index at which the last occurrence of value is found using strict equality - * for comparisons, i.e. ===. If fromIndex is negative, it is used as the offset from the - * end of the collection. - * @param array The array to search. - * @param value The value to search for. - * @param fromIndex The index to search from. - * @return The index of the matched value or -1. - **/ - lastIndexOf( - array: Array, - value: T, - fromIndex?: number): number; - - /** - * @see _.lastIndexOf - **/ - lastIndexOf( - array: List, - value: T, - fromIndex?: number): number; - } - - //_.pull - interface LoDashStatic { - /** - * Removes all provided values from the given array using strict equality for comparisons, - * i.e. ===. - * @param array The array to modify. - * @param values The values to remove. - * @return array. - **/ - pull( - array: Array, - ...values: any[]): any[]; - - /** - * @see _.pull - **/ - pull( - array: List, - ...values: any[]): any[]; - } - - //_.range - interface LoDashStatic { - /** - * Creates an array of numbers (positive and/or negative) progressing from start up - * to but not including end. If start is less than stop a zero-length range is created - * unless a negative step is specified. - * @param start The start of the range. - * @param end The end of the range. - * @param step The value to increment or decrement by. - * @return Returns a new range array. - **/ - range( - start: number, - stop: number, - step?: number): number[]; - - /** - * @see _.range - * @param end The end of the range. - * @return Returns a new range array. - * @note If start is not specified the implementation will never pull the step (step = arguments[2] || 0) - **/ - range(stop: number): number[]; - } - - //_.remove - interface LoDashStatic { - /** - * Removes all elements from an array that the callback returns truey for and returns - * an array of removed elements. The callback is bound to thisArg and invoked with three - * arguments; (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The array to modify. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return A new array of removed elements. - **/ - remove( - array: Array, - callback?: ListIterator, - thisArg?: any): any[]; - - /** - * @see _.remove - **/ - remove( - array: List, - callback?: ListIterator, - thisArg?: any): any[]; - - /** - * @see _.remove - * @param pluckValue _.pluck style callback - **/ - remove( - array: Array, - pluckValue?: string): any[]; - - /** - * @see _.remove - * @param pluckValue _.pluck style callback - **/ - remove( - array: List, - pluckValue?: string): any[]; - - /** - * @see _.remove - * @param whereValue _.where style callback - **/ - remove( - array: Array, - wherealue?: Dictionary): any[]; - - /** - * @see _.remove - * @param whereValue _.where style callback - **/ - remove( - array: List, - wherealue?: Dictionary): any[]; - - /** - * @see _.remove - * @param item The item to remove - **/ - remove( - array:Array, - item:T): T[]; - } - - //_.rest - interface LoDashStatic { - /** - * The opposite of _.initial this method gets all but the first element or first n elements of - * an array. If a callback function is provided elements at the beginning of the array are excluded - * from the result as long as the callback returns truey. The callback is bound to thisArg and - * invoked with three arguments; (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will return - * the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return true - * for elements that have the properties of the given object, else false. - * @param array The array to query. - * @param {(Function|Object|number|string)} [callback=1] The function called per element or the number - * of elements to exclude. If a property name or object is provided it will be used to create a - * ".pluck" or ".where" style callback, respectively. - * @param {*} [thisArg] The this binding of callback. - * @return Returns a slice of array. - **/ - rest(array: Array): T[]; - - /** - * @see _.rest - **/ - rest(array: List): T[]; - - /** - * @see _.rest - **/ - rest( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.rest - **/ - rest( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.rest - **/ - rest( - array: Array, - n: number): T[]; - - /** - * @see _.rest - **/ - rest( - array: List, - n: number): T[]; - - /** - * @see _.rest - **/ - rest( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.rest - **/ - rest( - array: List, - pluckValue: string): T[]; - - /** - * @see _.rest - **/ - rest( - array: Array, - whereValue: W): T[]; - - /** - * @see _.rest - **/ - rest( - array: List, - whereValue: W): T[]; - - /** - * @see _.rest - **/ - drop(array: Array): T[]; - - /** - * @see _.rest - **/ - drop(array: List): T[]; - - /** - * @see _.rest - **/ - drop( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.rest - **/ - drop( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.rest - **/ - drop( - array: Array, - n: number): T[]; - - /** - * @see _.rest - **/ - drop( - array: List, - n: number): T[]; - - /** - * @see _.rest - **/ - drop( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.rest - **/ - drop( - array: List, - pluckValue: string): T[]; - - /** - * @see _.rest - **/ - drop( - array: Array, - whereValue: W): T[]; - - /** - * @see _.rest - **/ - drop( - array: List, - whereValue: W): T[]; - - /** - * @see _.rest - **/ - tail(array: Array): T[]; - - /** - * @see _.rest - **/ - tail(array: List): T[]; - - /** - * @see _.rest - **/ - tail( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.rest - **/ - tail( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.rest - **/ - tail( - array: Array, - n: number): T[]; - - /** - * @see _.rest - **/ - tail( - array: List, - n: number): T[]; - - /** - * @see _.rest - **/ - tail( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.rest - **/ - tail( - array: List, - pluckValue: string): T[]; - - /** - * @see _.rest - **/ - tail( - array: Array, - whereValue: W): T[]; - - /** - * @see _.rest - **/ - tail( - array: List, - whereValue: W): T[]; - } - - //_.sortedIndex - interface LoDashStatic { - /** - * Uses a binary search to determine the smallest index at which a value should be inserted - * into a given sorted array in order to maintain the sort order of the array. If a callback - * is provided it will be executed for value and each element of array to compute their sort - * ranking. The callback is bound to thisArg and invoked with one argument; (value). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The sorted list. - * @param value The value to determine its index within `list`. - * @param callback Iterator to compute the sort ranking of each value, optional. - * @return The index at which value should be inserted into array. - **/ - sortedIndex( - array: Array, - value: T, - callback?: (x: T) => TSort, - thisArg?: any): number; - - /** - * @see _.sortedIndex - **/ - sortedIndex( - array: List, - value: T, - callback?: (x: T) => TSort, - thisArg?: any): number; - - /** - * @see _.sortedIndex - * @param pluckValue the _.pluck style callback - **/ - sortedIndex( - array: Array, - value: T, - pluckValue: string): number; - - /** - * @see _.sortedIndex - * @param pluckValue the _.pluck style callback - **/ - sortedIndex( - array: List, - value: T, - pluckValue: string): number; - - /** - * @see _.sortedIndex - * @param pluckValue the _.where style callback - **/ - sortedIndex( - array: Array, - value: T, - whereValue: W): number; - - /** - * @see _.sortedIndex - * @param pluckValue the _.where style callback - **/ - sortedIndex( - array: List, - value: T, - whereValue: W): number; - } - - //_.union - interface LoDashStatic { - /** - * Creates an array of unique values, in order, of the provided arrays using strict - * equality for comparisons, i.e. ===. - * @param arrays The arrays to inspect. - * @return Returns an array of composite values. - **/ - union(...arrays: Array[]): T[]; - - /** - * @see _.union - **/ - union(...arrays: List[]): T[]; - } - - //_.uniq - interface LoDashStatic { - /** - * Creates a duplicate-value-free version of an array using strict equality for comparisons, - * i.e. ===. If the array is sorted, providing true for isSorted will use a faster algorithm. - * If a callback is provided each element of array is passed through the callback before - * uniqueness is computed. The callback is bound to thisArg and invoked with three arguments; - * (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array Array to remove duplicates from. - * @param isSorted True if `array` is already sorted, optiona, default = false. - * @param iterator Transform the elements of `array` before comparisons for uniqueness. - * @param context 'this' object in `iterator`, optional. - * @return Copy of `array` where all elements are unique. - **/ - uniq(array: Array, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - uniq(array: List, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: Array, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: List, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq( - array: Array, - isSorted: boolean, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq( - array: List, - isSorted: boolean, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq( - array: List, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - array: Array, - isSorted: boolean, - whereValue: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - array: List, - isSorted: boolean, - whereValue: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - array: Array, - whereValue: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - array: List, - whereValue: W): T[]; - - /** - * @see _.uniq - **/ - unique(array: Array, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - unique(array: List, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - unique( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - unique( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - unique( - array: Array, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - unique( - array: List, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( - array: Array, - isSorted: boolean, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( - array: List, - isSorted: boolean, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( - array: List, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - array: Array, - whereValue?: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - array: List, - whereValue?: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - array: Array, - isSorted: boolean, - whereValue?: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - array: List, - isSorted: boolean, - whereValue?: W): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.uniq - **/ - uniq(isSorted?: boolean): LoDashArrayWrapper; - - /** - * @see _.uniq - **/ - uniq( - isSorted: boolean, - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.uniq - **/ - uniq( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq( - isSorted: boolean, - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq(pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - isSorted: boolean, - whereValue: W): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - whereValue: W): LoDashArrayWrapper; - - /** - * @see _.uniq - **/ - unique(isSorted?: boolean): LoDashArrayWrapper; - - /** - * @see _.uniq - **/ - unique( - isSorted: boolean, - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.uniq - **/ - unique( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( - isSorted: boolean, - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique(pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - isSorted: boolean, - whereValue: W): LoDashArrayWrapper; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - whereValue: W): LoDashArrayWrapper; - } - - //_.without - interface LoDashStatic { - /** - * Creates an array excluding all provided values using strict equality for comparisons, i.e. ===. - * @param array The array to filter. - * @param values The value(s) to exclude. - * @return A new array of filtered values. - **/ - without( - array: Array, - ...values: T[]): T[]; - - /** - * @see _.without - **/ - without( - array: List, - ...values: T[]): T[]; - } - - //_.xor - interface LoDashStatic { - /** - * Creates an array that is the symmetric difference of the provided arrays. - * @param array The array to process - * @param others The arrays of values to calculate the symmetric difference. - * @return Returns a new array of filtered values. - **/ - xor( - array: Array, - ...others: Array[]): T[]; - /** - * @see _.xor - **/ - xor( - array: List, - ...others: List[]): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.xor - **/ - xor( - ...others: Array[]): LoDashArrayWrapper; - /** - * @see _.xor - **/ - xor( - ...others: List[]): LoDashArrayWrapper; - } - - //_.zip - interface LoDashStatic { - /** - * Creates an array of grouped elements, the first of which contains the first - * elements of the given arrays, the second of which contains the second elements - * of the given arrays, and so on. - * @param arrays Arrays to process. - * @return A new array of grouped elements. - **/ - zip(...arrays: any[][]): any[][]; - - /** - * @see _.zip - **/ - zip(...arrays: any[]): any[]; - - /** - * @see _.zip - **/ - unzip(...arrays: any[][]): any[][]; - - /** - * @see _.zip - **/ - unzip(...arrays: any[]): any[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.zip - **/ - zip(...arrays: any[][]): _.LoDashArrayWrapper; - - /** - * @see _.zip - **/ - unzip(...arrays: any[]): _.LoDashArrayWrapper; - } - - //_.zipObject - interface LoDashStatic { - /** - * The inverse of _.pairs; this method returns an object composed from arrays of property - * names and values. Provide either a single two dimensional array, e.g. [[key1, value1], - * [key2, value2]] or two arrays, one of property names and one of corresponding values. - * @param props The property names. - * @param values The property values. - * @return Returns the new object. - **/ - zipObject( - props: List, - values?: List): TResult; - - /** - * @see _.zipObject - **/ - zipObject(props: List>): Dictionary; - - /** - * @see _.zipObject - **/ - object( - props: List, - values?: List): TResult; - - /** - * @see _.zipObject - **/ - object(props: List>): Dictionary; - } - - interface LoDashArrayWrapper { - /** - * @see _.zipObject - **/ - zipObject(values?: List): _.LoDashObjectWrapper>; - - /** - * @see _.zipObject - **/ - object(values?: List): _.LoDashObjectWrapper>; - } - - /* ************* - * Collections * - ************* */ - - //_.at - interface LoDashStatic { - /** - * Creates an array of elements from the specified indexes, or keys, of the collection. - * Indexes may be specified as individual arguments or as arrays of indexes. - * @param collection The collection to iterate over. - * @param indexes The indexes of collection to retrieve, specified as individual indexes or - * arrays of indexes. - * @return A new array of elements corresponding to the provided indexes. - **/ - at( - collection: Array, - indexes: number[]): T[]; - - /** - * @see _.at - **/ - at( - collection: List, - indexes: number[]): T[]; - - /** - * @see _.at - **/ - at( - collection: Dictionary, - indexes: number[]): T[]; - - /** - * @see _.at - **/ - at( - collection: Array, - ...indexes: number[]): T[]; - - /** - * @see _.at - **/ - at( - collection: List, - ...indexes: number[]): T[]; - - /** - * @see _.at - **/ - at( - collection: Dictionary, - ...indexes: number[]): T[]; - } - - //_.contains - interface LoDashStatic { - /** - * Checks if a given value is present in a collection using strict equality for comparisons, - * i.e. ===. If fromIndex is negative, it is used as the offset from the end of the collection. - * @param collection The collection to iterate over. - * @param target The value to check for. - * @param fromIndex The index to search from. - * @return True if the target element is found, else false. - **/ - contains( - collection: Array, - target: T, - fromIndex?: number): boolean; - - /** - * @see _.contains - **/ - contains( - collection: List, - target: T, - fromIndex?: number): boolean; - - /** - * @see _.contains - * @param dictionary The dictionary to iterate over. - * @param key The key in the dictionary to search for. - **/ - contains( - dictionary: Dictionary, - key: string, - fromIndex?: number): boolean; - - /** - * @see _.contains - * @param searchString the string to search - * @param targetString the string to search for - **/ - contains( - searchString: string, - targetString: string, - fromIndex?: number): boolean; - - /** - * @see _.contains - **/ - include( - collection: Array, - target: T, - fromIndex?: number): boolean; - - /** - * @see _.contains - **/ - include( - collection: List, - target: T, - fromIndex?: number): boolean; - - /** - * @see _.contains - **/ - include( - dictionary: Dictionary, - key: string, - fromIndex?: number): boolean; - - /** - * @see _.contains - **/ - include( - searchString: string, - targetString: string, - fromIndex?: number): boolean; - } - - //_.countBy - interface LoDashStatic { - /** - * Creates an object composed of keys generated from the results of running each element - * of collection through the callback. The corresponding value of each key is the number - * of times the key was returned by the callback. The callback is bound to thisArg and - * invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return Returns the composed aggregate object. - **/ - countBy( - collection: Array, - callback?: ListIterator, - thisArg?: any): Dictionary; - - /** - * @see _.countBy - * @param callback Function name - **/ - countBy( - collection: List, - callback?: ListIterator, - thisArg?: any): Dictionary; - - /** - * @see _.countBy - * @param callback Function name - **/ - countBy( - collection: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.countBy - * @param callback Function name - **/ - countBy( - collection: Array, - callback: string, - thisArg?: any): Dictionary; - - /** - * @see _.countBy - * @param callback Function name - **/ - countBy( - collection: List, - callback: string, - thisArg?: any): Dictionary; - - /** - * @see _.countBy - * @param callback Function name - **/ - countBy( - collection: Dictionary, - callback: string, - thisArg?: any): Dictionary; - } - - interface LoDashArrayWrapper { - /** - * @see _.countBy - **/ - countBy( - callback?: ListIterator, - thisArg?: any): LoDashObjectWrapper>; - - /** - * @see _.countBy - * @param callback Function name - **/ - countBy( - callback: string, - thisArg?: any): LoDashObjectWrapper>; - } - - //_.every - interface LoDashStatic { - /** - * Checks if the given callback returns truey value for all elements of a collection. - * The callback is bound to thisArg and invoked with three arguments; (value, index|key, - * collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return True if all elements passed the callback check, else false. - **/ - every( - collection: Array, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - every( - collection: List, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - every( - collection: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - every( - collection: Array, - pluckValue: string): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - every( - collection: List, - pluckValue: string): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - every( - collection: Dictionary, - pluckValue: string): boolean; - - /** - * @see _.every - * @param whereValue _.where style callback - **/ - every( - collection: Array, - whereValue: W): boolean; - - /** - * @see _.every - * @param whereValue _.where style callback - **/ - every( - collection: List, - whereValue: W): boolean; - - /** - * @see _.every - * @param whereValue _.where style callback - **/ - every( - collection: Dictionary, - whereValue: W): boolean; - - /** - * @see _.every - **/ - all( - collection: Array, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.every - **/ - all( - collection: List, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.every - **/ - all( - collection: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - all( - collection: Array, - pluckValue: string): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - all( - collection: List, - pluckValue: string): boolean; - - /** - * @see _.every - * @param pluckValue _.pluck style callback - **/ - all( - collection: Dictionary, - pluckValue: string): boolean; - - /** - * @see _.every - * @param whereValue _.where style callback - **/ - all( - collection: Array, - whereValue: W): boolean; - - /** - * @see _.every - * @param whereValue _.where style callback - **/ - all( - collection: List, - whereValue: W): boolean; - - /** - * @see _.every - * @param whereValue _.where style callback - **/ - all( - collection: Dictionary, - whereValue: W): boolean; - } - - //_.filter - interface LoDashStatic { - /** - * Iterates over elements of a collection, returning an array of all elements the - * callback returns truey for. The callback is bound to thisArg and invoked with three - * arguments; (value, index|key, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param context The this binding of callback. - * @return Returns a new array of elements that passed the callback check. - **/ - filter( - collection: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.filter - **/ - filter( - collection: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.filter - **/ - filter( - collection: Dictionary, - callback: DictionaryIterator, - thisArg?: any): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - collection: Array, - pluckValue: string): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - collection: List, - pluckValue: string): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - collection: Dictionary, - pluckValue: string): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - collection: Array, - whereValue: W): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - collection: List, - whereValue: W): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - collection: Dictionary, - whereValue: W): T[]; - - /** - * @see _.filter - **/ - select( - collection: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.filter - **/ - select( - collection: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.filter - **/ - select( - collection: Dictionary, - callback: DictionaryIterator, - thisArg?: any): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - collection: Array, - pluckValue: string): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - collection: List, - pluckValue: string): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - collection: Dictionary, - pluckValue: string): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - collection: Array, - whereValue: W): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - collection: List, - whereValue: W): T[]; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - collection: Dictionary, - whereValue: W): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.filter - **/ - filter( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - filter( - whereValue: W): LoDashArrayWrapper; - - /** - * @see _.filter - **/ - select( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.filter - * @param pluckValue _.pluck style callback - **/ - select( - whereValue: W): LoDashArrayWrapper; - } - - interface LoDashObjectWrapper { - /** - * @see _.filter - **/ - filter( - callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper; - } - - //_.find - interface LoDashStatic { - /** - * Iterates over elements of a collection, returning the first element that the callback - * returns truey for. The callback is bound to thisArg and invoked with three arguments; - * (value, index|key, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param collection Searches for a value in this list. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return The found element, else undefined. - **/ - find( - collection: Array, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - find( - collection: List, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - find( - collection: Dictionary, - callback: DictionaryIterator, - thisArg?: any): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - find( - collection: Array, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - find( - collection: List, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - find( - collection: Dictionary, - whereValue: W): T; - - /** - * @see _.find - * @param _.where style callback - **/ - find( - collection: Array, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - find( - collection: List, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - find( - collection: Dictionary, - pluckValue: string): T; - - /** - * @see _.find - **/ - detect( - collection: Array, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - detect( - collection: List, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - detect( - collection: Dictionary, - callback: DictionaryIterator, - thisArg?: any): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - detect( - collection: Array, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - detect( - collection: List, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - detect( - collection: Dictionary, - whereValue: W): T; - - /** - * @see _.find - * @param _.where style callback - **/ - detect( - collection: Array, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - detect( - collection: List, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - detect( - collection: Dictionary, - pluckValue: string): T; - - /** - * @see _.find - **/ - findWhere( - collection: Array, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - findWhere( - collection: List, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - findWhere( - collection: Dictionary, - callback: DictionaryIterator, - thisArg?: any): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - findWhere( - collection: Array, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - findWhere( - collection: List, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - findWhere( - collection: Dictionary, - whereValue: W): T; - - /** - * @see _.find - * @param _.where style callback - **/ - findWhere( - collection: Array, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - findWhere( - collection: List, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - findWhere( - collection: Dictionary, - pluckValue: string): T; - } - - interface LoDashArrayWrapper { - /** - * @see _.find - */ - find( - callback: ListIterator, - thisArg?: any): T; - /** - * @see _.find - * @param _.where style callback - */ - find( - whereValue: W): T; - - /** - * @see _.find - * @param _.where style callback - */ - find( - pluckValue: string): T; - } - - //_.findLast - interface LoDashStatic { - /** - * This method is like _.find except that it iterates over elements of a collection from - * right to left. - * @param collection Searches for a value in this list. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return The found element, else undefined. - **/ - findLast( - collection: Array, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - findLast( - collection: List, - callback: ListIterator, - thisArg?: any): T; - - /** - * @see _.find - **/ - findLast( - collection: Dictionary, - callback: DictionaryIterator, - thisArg?: any): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - findLast( - collection: Array, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - findLast( - collection: List, - whereValue: W): T; - - /** - * @see _.find - * @param _.pluck style callback - **/ - findLast( - collection: Dictionary, - whereValue: W): T; - - /** - * @see _.find - * @param _.where style callback - **/ - findLast( - collection: Array, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - findLast( - collection: List, - pluckValue: string): T; - - /** - * @see _.find - * @param _.where style callback - **/ - findLast( - collection: Dictionary, - pluckValue: string): T; - } - - interface LoDashArrayWrapper { - /** - * @see _.findLast - */ - findLast( - callback: ListIterator, - thisArg?: any): T; - /** - * @see _.findLast - * @param _.where style callback - */ - findLast( - whereValue: W): T; - - /** - * @see _.findLast - * @param _.where style callback - */ - findLast( - pluckValue: string): T; - } - - //_.forEach - interface LoDashStatic { - /** - * Iterates over elements of a collection, executing the callback for each element. - * The callback is bound to thisArg and invoked with three arguments; (value, index|key, - * collection). Callbacks may exit iteration early by explicitly returning false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - forEach( - collection: Array, - callback: ListIterator, - thisArg?: any): Array; - - /** - * @see _.forEach - **/ - forEach( - collection: List, - callback: ListIterator, - thisArg?: any): List; - - /** - * @see _.forEach - **/ - forEach( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.each - **/ - forEach( - object: T, - callback: ObjectIterator, - thisArg?: any): T - - /** - * @see _.forEach - **/ - each( - collection: Array, - callback: ListIterator, - thisArg?: any): Array; - - /** - * @see _.forEach - **/ - each( - collection: List, - callback: ListIterator, - thisArg?: any): List; - - /** - * @see _.forEach - * @param object The object to iterate over - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - each( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.each - **/ - each( - object: T, - callback: ObjectIterator, - thisArg?: any): T - } - - interface LoDashArrayWrapper { - /** - * @see _.forEach - **/ - forEach( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.forEach - **/ - each( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - } - - interface LoDashObjectWrapper { - /** - * @see _.forEach - **/ - forEach( - callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper; - - /** - * @see _.forEach - **/ - each( - callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper; - } - - //_.forEachRight - interface LoDashStatic { - /** - * This method is like _.forEach except that it iterates over elements of a - * collection from right to left. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - forEachRight( - collection: Array, - callback: ListIterator, - thisArg?: any): Array; - - /** - * @see _.forEachRight - **/ - forEachRight( - collection: List, - callback: ListIterator, - thisArg?: any): List; - - /** - * @see _.forEachRight - **/ - forEachRight( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.forEachRight - **/ - eachRight( - collection: Array, - callback: ListIterator, - thisArg?: any): Array; - - /** - * @see _.forEachRight - **/ - eachRight( - collection: List, - callback: ListIterator, - thisArg?: any): List; - - /** - * @see _.forEachRight - * @param object The object to iterate over - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - eachRight( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): Dictionary; - } - - interface LoDashArrayWrapper { - /** - * @see _.forEachRight - **/ - forEachRight( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.forEachRight - **/ - eachRight( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - } - - interface LoDashObjectWrapper { - /** - * @see _.forEachRight - **/ - forEachRight( - callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper>; - - /** - * @see _.forEachRight - * @param object The object to iterate over - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - eachRight( - callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper>; - } - - //_.groupBy - interface LoDashStatic { - /** - * Creates an object composed of keys generated from the results of running each element - * of a collection through the callback. The corresponding value of each key is an array - * of the elements responsible for generating the key. The callback is bound to thisArg - * and invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return Returns the composed aggregate object. - **/ - groupBy( - collection: Array, - callback?: ListIterator, - thisArg?: any): Dictionary; - - /** - * @see _.groupBy - **/ - groupBy( - collection: List, - callback?: ListIterator, - thisArg?: any): Dictionary; - - /** - * @see _.groupBy - * @param pluckValue _.pluck style callback - **/ - groupBy( - collection: Array, - pluckValue: string): Dictionary; - - /** - * @see _.groupBy - * @param pluckValue _.pluck style callback - **/ - groupBy( - collection: List, - pluckValue: string): Dictionary; - - /** - * @see _.groupBy - * @param whereValue _.where style callback - **/ - groupBy( - collection: Array, - whereValue: W): Dictionary; - - /** - * @see _.groupBy - * @param whereValue _.where style callback - **/ - groupBy( - collection: List, - whereValue: W): Dictionary; - - /** - * @see _.groupBy - **/ - groupBy( - collection: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.groupBy - * @param pluckValue _.pluck style callback - **/ - groupBy( - collection: Dictionary, - pluckValue: string): Dictionary; - - /** - * @see _.groupBy - * @param whereValue _.where style callback - **/ - groupBy( - collection: Dictionary, - whereValue: W): Dictionary; - } - - interface LoDashArrayWrapper { - /** - * @see _.groupBy - **/ - groupBy( - callback: ListIterator, - thisArg?: any): _.LoDashObjectWrapper<_.Dictionary>; - - /** - * @see _.groupBy - **/ - groupBy( - pluckValue: string): _.LoDashObjectWrapper<_.Dictionary>; - - /** - * @see _.groupBy - **/ - groupBy( - whereValue: W): _.LoDashObjectWrapper<_.Dictionary>; - } - - interface LoDashObjectWrapper { - /** - * @see _.groupBy - **/ - groupBy( - callback: ListIterator, - thisArg?: any): _.LoDashObjectWrapper<_.Dictionary>; - - /** - * @see _.groupBy - **/ - groupBy( - pluckValue: string): _.LoDashObjectWrapper<_.Dictionary>; - - /** - * @see _.groupBy - **/ - groupBy( - whereValue: W): _.LoDashObjectWrapper<_.Dictionary>; - } - - //_.indexBy - interface LoDashStatic { - /** - * Creates an object composed of keys generated from the results of running each element - * of the collection through the given callback. The corresponding value of each key is - * the last element responsible for generating the key. The callback is bound to thisArg - * and invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return Returns the composed aggregate object. - **/ - indexBy( - list: Array, - iterator: ListIterator, - context?: any): Dictionary; - - /** - * @see _.indexBy - **/ - indexBy( - list: List, - iterator: ListIterator, - context?: any): Dictionary; - - /** - * @see _.indexBy - * @param pluckValue _.pluck style callback - **/ - indexBy( - collection: Array, - pluckValue: string): Dictionary; - - /** - * @see _.indexBy - * @param pluckValue _.pluck style callback - **/ - indexBy( - collection: List, - pluckValue: string): Dictionary; - - /** - * @see _.indexBy - * @param whereValue _.where style callback - **/ - indexBy( - collection: Array, - whereValue: W): Dictionary; - - /** - * @see _.indexBy - * @param whereValue _.where style callback - **/ - indexBy( - collection: List, - whereValue: W): Dictionary; - } - - //_.invoke - interface LoDashStatic { - /** - * Invokes the method named by methodName on each element in the collection returning - * an array of the results of each invoked method. Additional arguments will be provided - * to each invoked method. If methodName is a function it will be invoked for, and this - * bound to, each element in the collection. - * @param collection The collection to iterate over. - * @param methodName The name of the method to invoke. - * @param args Arguments to invoke the method with. - **/ - invoke( - collection: Array, - methodName: string, - ...args: any[]): any; - - /** - * @see _.invoke - **/ - invoke( - collection: List, - methodName: string, - ...args: any[]): any; - - /** - * @see _.invoke - **/ - invoke( - collection: Dictionary, - methodName: string, - ...args: any[]): any; - - /** - * @see _.invoke - **/ - invoke( - collection: Array, - method: Function, - ...args: any[]): any; - - /** - * @see _.invoke - **/ - invoke( - collection: List, - method: Function, - ...args: any[]): any; - - /** - * @see _.invoke - **/ - invoke( - collection: Dictionary, - method: Function, - ...args: any[]): any; - } - - //_.map - interface LoDashStatic { - /** - * Creates an array of values by running each element in the collection through the callback. - * The callback is bound to thisArg and invoked with three arguments; (value, index|key, - * collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will return - * the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return true - * for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param theArg The this binding of callback. - * @return The mapped array result. - **/ - map( - collection: Array, - callback: ListIterator, - thisArg?: any): TResult[]; - - /** - * @see _.map - **/ - map( - collection: List, - callback: ListIterator, - thisArg?: any): TResult[]; - - /** - * @see _.map - * @param object The object to iterate over. - * @param callback The function called per iteration. - * @param thisArg `this` object in `iterator`, optional. - * @return The mapped object result. - **/ - map( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): TResult[]; - - /** - * @see _.map - * @param pluckValue _.pluck style callback - **/ - map( - collection: Array, - pluckValue: string): TResult[]; - - /** - * @see _.map - * @param pluckValue _.pluck style callback - **/ - map( - collection: List, - pluckValue: string): TResult[]; - - /** - * @see _.map - **/ - collect( - collection: Array, - callback: ListIterator, - thisArg?: any): TResult[]; - - /** - * @see _.map - **/ - collect( - collection: List, - callback: ListIterator, - thisArg?: any): TResult[]; - - /** - * @see _.map - **/ - collect( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): TResult[]; - - /** - * @see _.map - **/ - collect( - collection: Array, - pluckValue: string): TResult[]; - - /** - * @see _.map - **/ - collect( - collection: List, - pluckValue: string): TResult[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.map - **/ - map( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.map - * @param pluckValue _.pluck style callback - **/ - map( - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.map - **/ - collect( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.map - **/ - collect( - pluckValue: string): LoDashArrayWrapper; - } - - interface LoDashObjectWrapper { - /** - * @see _.map - **/ - map( - callback: ObjectIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.map - **/ - collect( - callback: ObjectIterator, - thisArg?: any): LoDashArrayWrapper; - } - - //_.max - interface LoDashStatic { - /** - * Retrieves the maximum value of a collection. If the collection is empty or falsey -Infinity is - * returned. If a callback is provided it will be executed for each value in the collection to - * generate the criterion by which the value is ranked. The callback is bound to thisArg and invoked - * with three arguments; (value, index, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will return the - * property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return true for - * elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return Returns the maximum value. - **/ - max( - collection: Array, - callback?: ListIterator, - thisArg?: any): T; - - /** - * @see _.max - **/ - max( - collection: List, - callback?: ListIterator, - thisArg?: any): T; - - /** - * @see _.max - **/ - max( - collection: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): T; - - /** - * @see _.max - * @param pluckValue _.pluck style callback - **/ - max( - collection: Array, - pluckValue: string): T; - - /** - * @see _.max - * @param pluckValue _.pluck style callback - **/ - max( - collection: List, - pluckValue: string): T; - - /** - * @see _.max - * @param pluckValue _.pluck style callback - **/ - max( - collection: Dictionary, - pluckValue: string): T; - - /** - * @see _.max - * @param whereValue _.where style callback - **/ - max( - collection: Array, - whereValue: W): T; - - /** - * @see _.max - * @param whereValue _.where style callback - **/ - max( - collection: List, - whereValue: W): T; - - /** - * @see _.max - * @param whereValue _.where style callback - **/ - max( - collection: Dictionary, - whereValue: W): T; - } - - interface LoDashArrayWrapper { - /** - * @see _.max - **/ - max( - callback?: ListIterator, - thisArg?: any): LoDashWrapper; - - /** - * @see _.max - * @param pluckValue _.pluck style callback - **/ - max( - pluckValue: string): LoDashWrapper; - - /** - * @see _.max - * @param whereValue _.where style callback - **/ - max( - whereValue: W): LoDashWrapper; - } - - //_.min - interface LoDashStatic { - /** - * Retrieves the minimum value of a collection. If the collection is empty or falsey - * Infinity is returned. If a callback is provided it will be executed for each value - * in the collection to generate the criterion by which the value is ranked. The callback - * is bound to thisArg and invoked with three arguments; (value, index, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback - * will return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will - * return true for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return Returns the maximum value. - **/ - min( - collection: Array, - callback?: ListIterator, - thisArg?: any): T; - - /** - * @see _.min - **/ - min( - collection: List, - callback?: ListIterator, - thisArg?: any): T; - - /** - * @see _.min - **/ - min( - collection: Dictionary, - callback?: ListIterator, - thisArg?: any): T; - - /** - * @see _.min - * @param pluckValue _.pluck style callback - **/ - min( - collection: Array, - pluckValue: string): T; - - /** - * @see _.min - * @param pluckValue _.pluck style callback - **/ - min( - collection: List, - pluckValue: string): T; - - /** - * @see _.min - * @param pluckValue _.pluck style callback - **/ - min( - collection: Dictionary, - pluckValue: string): T; - - /** - * @see _.min - * @param whereValue _.where style callback - **/ - min( - collection: Array, - whereValue: W): T; - - /** - * @see _.min - * @param whereValue _.where style callback - **/ - min( - collection: List, - whereValue: W): T; - - /** - * @see _.min - * @param whereValue _.where style callback - **/ - min( - collection: Dictionary, - whereValue: W): T; - } - - interface LoDashArrayWrapper { - /** - * @see _.min - **/ - min( - callback?: ListIterator, - thisArg?: any): LoDashWrapper; - - /** - * @see _.min - * @param pluckValue _.pluck style callback - **/ - min( - pluckValue: string): LoDashWrapper; - - /** - * @see _.min - * @param whereValue _.where style callback - **/ - min( - whereValue: W): LoDashWrapper; - } - - //_.sum - interface LoDashStatic { - /** - * Gets the sum of the values in collection. - * - * @param collection The collection to iterate over. - * @param iteratee The function invoked per iteration. - * @param thisArg The this binding of iteratee. - * @return Returns the sum. - **/ - sum( - collection: Array): number; - - /** - * @see _.sum - **/ - sum( - collection: List): number; - - /** - * @see _.sum - **/ - sum( - collection: Dictionary): number; - - /** - * @see _.sum - **/ - sum( - collection: Array, - iteratee: ListIterator, - thisArg?: any): number; - - /** - * @see _.sum - **/ - sum( - collection: List, - iteratee: ListIterator, - thisArg?: any): number; - - /** - * @see _.sum - **/ - sum( - collection: Dictionary, - iteratee: ObjectIterator, - thisArg?: any): number; - - /** - * @see _.sum - * @param property _.property callback shorthand. - **/ - sum( - collection: Array, - property: string): number; - - /** - * @see _.sum - * @param property _.property callback shorthand. - **/ - sum( - collection: List, - property: string): number; - - /** - * @see _.sum - * @param property _.property callback shorthand. - **/ - sum( - collection: Dictionary, - property: string): number; - } - - interface LoDashNumberArrayWrapper { - /** - * @see _.sum - **/ - sum(): number - - /** - * @see _.sum - **/ - sum( - iteratee: ListIterator, - thisArg?: any): number; - } - - interface LoDashArrayWrapper { - /** - * @see _.sum - **/ - sum( - iteratee: ListIterator, - thisArg?: any): number; - - /** - * @see _.sum - * @param property _.property callback shorthand. - **/ - sum( - property: string): number; - } - - interface LoDashObjectWrapper { - /** - * @see _.sum - **/ - sum(): number - - /** - * @see _.sum - **/ - sum( - iteratee: ObjectIterator, - thisArg?: any): number; - - /** - * @see _.sum - * @param property _.property callback shorthand. - **/ - sum( - property: string): number; - } - - //_.pluck - interface LoDashStatic { - /** - * Retrieves the value of a specified property from all elements in the collection. - * @param collection The collection to iterate over. - * @param property The property to pluck. - * @return A new array of property values. - **/ - pluck( - collection: Array, - property: string): any[]; - - /** - * @see _.pluck - **/ - pluck( - collection: List, - property: string): any[]; - - /** - * @see _.pluck - **/ - pluck( - collection: Dictionary, - property: string): any[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.pluck - **/ - pluck( - property: string): LoDashArrayWrapper; - } - - interface LoDashObjectWrapper { - /** - * @see _.pluck - **/ - pluck( - property: string): LoDashArrayWrapper; - } - - //_.reduce - interface LoDashStatic { - /** - * Reduces a collection to a value which is the accumulated result of running each - * element in the collection through the callback, where each successive callback execution - * consumes the return value of the previous execution. If accumulator is not provided the - * first element of the collection will be used as the initial accumulator value. The callback - * is bound to thisArg and invoked with four arguments; (accumulator, value, index|key, collection). - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param accumulator Initial value of the accumulator. - * @param thisArg The this binding of callback. - * @return Returns the accumulated value. - **/ - reduce( - collection: Array, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - reduce( - collection: List, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - reduce( - collection: Dictionary, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - reduce( - collection: Array, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - reduce( - collection: List, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - reduce( - collection: Dictionary, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - collection: Array, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - collection: List, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - collection: Dictionary, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - collection: Array, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - collection: List, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - collection: Dictionary, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - collection: Array, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - collection: List, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - collection: Dictionary, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - collection: Array, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - collection: List, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - collection: Dictionary, - callback: MemoIterator, - thisArg?: any): TResult; - } - - interface LoDashArrayWrapper { - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - callback: MemoIterator, - thisArg?: any): TResult; - } - - interface LoDashObjectWrapper { - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - callback: MemoIterator, - thisArg?: any): TResult; - } - - //_.reduceRight - interface LoDashStatic { - /** - * This method is like _.reduce except that it iterates over elements of a collection from - * right to left. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param accumulator Initial value of the accumulator. - * @param thisArg The this binding of callback. - * @return The accumulated value. - **/ - reduceRight( - collection: Array, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - reduceRight( - collection: List, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - reduceRight( - collection: Dictionary, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - reduceRight( - collection: Array, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - reduceRight( - collection: List, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - reduceRight( - collection: Dictionary, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr( - collection: Array, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr( - collection: List, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr( - collection: Dictionary, - callback: MemoIterator, - accumulator: TResult, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr( - collection: Array, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr( - collection: List, - callback: MemoIterator, - thisArg?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr( - collection: Dictionary, - callback: MemoIterator, - thisArg?: any): TResult; - } - - //_.reject - interface LoDashStatic { - /** - * The opposite of _.filter this method returns the elements of a collection that - * the callback does not return truey for. - * - * If a property name is provided for callback the created "_.pluck" style callback - * will return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will - * return true for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return A new array of elements that failed the callback check. - **/ - reject( - collection: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.reject - **/ - reject( - collection: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.reject - **/ - reject( - collection: Dictionary, - callback: DictionaryIterator, - thisArg?: any): T[]; - - /** - * @see _.reject - * @param pluckValue _.pluck style callback - **/ - reject( - collection: Array, - pluckValue: string): T[]; - - /** - * @see _.reject - * @param pluckValue _.pluck style callback - **/ - reject( - collection: List, - pluckValue: string): T[]; - - /** - * @see _.reject - * @param pluckValue _.pluck style callback - **/ - reject( - collection: Dictionary, - pluckValue: string): T[]; - - /** - * @see _.reject - * @param whereValue _.where style callback - **/ - reject( - collection: Array, - whereValue: W): T[]; - - /** - * @see _.reject - * @param whereValue _.where style callback - **/ - reject( - collection: List, - whereValue: W): T[]; - - /** - * @see _.reject - * @param whereValue _.where style callback - **/ - reject( - collection: Dictionary, - whereValue: W): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.reject - **/ - reject( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.reject - * @param pluckValue _.pluck style callback - **/ - reject(pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.reject - * @param whereValue _.where style callback - **/ - reject(whereValue: W): LoDashArrayWrapper; - } - - //_.sample - interface LoDashStatic { - /** - * Retrieves a random element or n random elements from a collection. - * @param collection The collection to sample. - * @return Returns the random sample(s) of collection. - **/ - sample(collection: Array): T; - - /** - * @see _.sample - **/ - sample(collection: List): T; - - /** - * @see _.sample - **/ - sample(collection: Dictionary): T; - - /** - * @see _.sample - * @param n The number of elements to sample. - **/ - sample(collection: Array, n: number): T[]; - - /** - * @see _.sample - * @param n The number of elements to sample. - **/ - sample(collection: List, n: number): T[]; - - /** - * @see _.sample - * @param n The number of elements to sample. - **/ - sample(collection: Dictionary, n: number): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.sample - **/ - sample(n: number): LoDashArrayWrapper; - - /** - * @see _.sample - **/ - sample(): LoDashArrayWrapper; - } - - //_.shuffle - interface LoDashStatic { - /** - * Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. - * See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. - * @param collection The collection to shuffle. - * @return Returns a new shuffled collection. - **/ - shuffle(collection: Array): T[]; - - /** - * @see _.shuffle - **/ - shuffle(collection: List): T[]; - - /** - * @see _.shuffle - **/ - shuffle(collection: Dictionary): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.shuffle - **/ - shuffle(): LoDashArrayWrapper; - } - - interface LoDashObjectWrapper { - /** - * @see _.shuffle - **/ - shuffle(): LoDashArrayWrapper; - } - - //_.size - interface LoDashStatic { - /** - * Gets the size of the collection by returning collection.length for arrays and array-like - * objects or the number of own enumerable properties for objects. - * @param collection The collection to inspect. - * @return collection.length - **/ - size(collection: Array): number; - - /** - * @see _.size - **/ - size(collection: List): number; - - /** - * @see _.size - * @param object The object to inspect - * @return The number of own enumerable properties. - **/ - size(object: T): number; - - /** - * @see _.size - * @param aString The string to inspect - * @return The length of aString - **/ - size(aString: string): number; - } - - //_.some - interface LoDashStatic { - /** - * Checks if the callback returns a truey value for any element of a collection. The function - * returns as soon as it finds a passing value and does not iterate over the entire collection. - * The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will return - * the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return true for - * elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return True if any element passed the callback check, else false. - **/ - some( - collection: Array, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.some - **/ - some( - collection: List, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.some - **/ - some( - collection: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): boolean; - - /** - * @see _.some - **/ - some( - collection: {}, - callback?: ListIterator<{}, boolean>, - thisArg?: any): boolean; - - /** - * @see _.some - * @param pluckValue _.pluck style callback - **/ - some( - collection: Array, - pluckValue: string): boolean; - - /** - * @see _.some - * @param pluckValue _.pluck style callback - **/ - some( - collection: List, - pluckValue: string): boolean; - - /** - * @see _.some - * @param pluckValue _.pluck style callback - **/ - some( - collection: Dictionary, - pluckValue: string): boolean; - - /** - * @see _.some - * @param whereValue _.where style callback - **/ - some( - collection: Array, - whereValue: W): boolean; - - /** - * @see _.some - * @param whereValue _.where style callback - **/ - some( - collection: List, - whereValue: W): boolean; - - /** - * @see _.some - * @param whereValue _.where style callback - **/ - some( - collection: Dictionary, - whereValue: W): boolean; - - /** - * @see _.some - **/ - any( - collection: Array, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.some - **/ - any( - collection: List, - callback?: ListIterator, - thisArg?: any): boolean; - - /** - * @see _.some - **/ - any( - collection: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): boolean; - - /** - * @see _.some - **/ - any( - collection: {}, - callback?: ListIterator<{}, boolean>, - thisArg?: any): boolean; - - /** - * @see _.some - * @param pluckValue _.pluck style callback - **/ - any( - collection: Array, - pluckValue: string): boolean; - - /** - * @see _.some - * @param pluckValue _.pluck style callback - **/ - any( - collection: List, - pluckValue: string): boolean; - - /** - * @see _.some - * @param pluckValue _.pluck style callback - **/ - any( - collection: Dictionary, - pluckValue: string): boolean; - - /** - * @see _.some - * @param whereValue _.where style callback - **/ - any( - collection: Array, - whereValue: W): boolean; - - /** - * @see _.some - * @param whereValue _.where style callback - **/ - any( - collection: List, - whereValue: W): boolean; - - /** - * @see _.some - * @param whereValue _.where style callback - **/ - any( - collection: Dictionary, - whereValue: W): boolean; - } - - //_.sortBy - interface LoDashStatic { - /** - * Creates an array of elements, sorted in ascending order by the results of running each - * element in a collection through the callback. This method performs a stable sort, that - * is, it will preserve the original sort order of equal elements. The callback is bound - * to thisArg and invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return A new array of sorted elements. - **/ - sortBy( - collection: Array, - callback?: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.sortBy - **/ - sortBy( - collection: List, - callback?: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.sortBy - * @param pluckValue _.pluck style callback - **/ - sortBy( - collection: Array, - pluckValue: string): T[]; - - /** - * @see _.sortBy - * @param pluckValue _.pluck style callback - **/ - sortBy( - collection: List, - pluckValue: string): T[]; - - /** - * @see _.sortBy - * @param whereValue _.where style callback - **/ - sortBy( - collection: Array, - whereValue: W): T[]; - - /** - * @see _.sortBy - * @param whereValue _.where style callback - **/ - sortBy( - collection: List, - whereValue: W): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.sortBy - **/ - sortBy( - callback?: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.sortBy - * @param pluckValue _.pluck style callback - **/ - sortBy(pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.sortBy - * @param whereValue _.where style callback - **/ - sortBy(whereValue: W): LoDashArrayWrapper; - } - - //_.toArray - interface LoDashStatic { - /** - * Converts the collection to an array. - * @param collection The collection to convert. - * @return The new converted array. - **/ - toArray(collection: Array): T[]; - - /** - * @see _.toArray - **/ - toArray(collection: List): T[]; - - /** - * @see _.toArray - **/ - toArray(collection: Dictionary): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.toArray - **/ - toArray(): LoDashArrayWrapper; - } - - interface LoDashObjectWrapper { - /** - * @see _.toArray - **/ - toArray(): LoDashArrayWrapper; - } - - //_.where - interface LoDashStatic { - /** - * Performs a deep comparison of each element in a collection to the given properties - * object, returning an array of all elements that have equivalent property values. - * @param collection The collection to iterate over. - * @param properties The object of property values to filter by. - * @return A new array of elements that have the given properties. - **/ - where( - list: Array, - properties: U): T[]; - - /** - * @see _.where - **/ - where( - list: List, - properties: U): T[]; - - /** - * @see _.where - **/ - where( - list: Dictionary, - properties: U): T[]; - } - - interface LoDashArrayWrapper { - /** - * @see _.where - **/ - where(properties: U): LoDashArrayWrapper; - } - - /******** - * Date * - ********/ - - //_.now - interface LoDashStatic { - /** - * Gets the number of milliseconds that have elapsed since the Unix epoch - * (1 January 1970 00:00:00 UTC). - * @return The number of milliseconds. - **/ - now(): number; - } - - /************* - * Functions * - *************/ - - //_.after - interface LoDashStatic { - /** - * Creates a function that executes func, with the this binding and arguments of the - * created function, only after being called n times. - * @param n The number of times the function must be called before func is executed. - * @param func The function to restrict. - * @return The new restricted function. - **/ - after( - n: number, - func: Function): Function; - } - - interface LoDashWrapper { - /** - * @see _.after - **/ - after(func: Function): LoDashObjectWrapper; - } - - //_.bind - interface LoDashStatic { - /** - * Creates a function that, when called, invokes func with the this binding of thisArg - * and prepends any additional bind arguments to those provided to the bound function. - * @param func The function to bind. - * @param thisArg The this binding of func. - * @param args Arguments to be partially applied. - * @return The new bound function. - **/ - bind( - func: Function, - thisArg: any, - ...args: any[]): (...args: any[]) => any; - } - - interface LoDashObjectWrapper { - /** - * @see _.bind - **/ - bind( - thisArg: any, - ...args: any[]): LoDashObjectWrapper<(...args: any[]) => any>; - } - - //_.bindAll - interface LoDashStatic { - /** - * Binds methods of an object to the object itself, overwriting the existing method. Method - * names may be specified as individual arguments or as arrays of method names. If no method - * names are provided all the function properties of object will be bound. - * @param object The object to bind and assign the bound methods to. - * @param methodNames The object method names to bind, specified as individual method names - * or arrays of method names. - * @return object - **/ - bindAll( - object: T, - ...methodNames: string[]): T; - } - - interface LoDashObjectWrapper { - /** - * @see _.bindAll - **/ - bindAll(...methodNames: string[]): LoDashWrapper; - } - - //_.bindKey - interface LoDashStatic { - /** - * Creates a function that, when called, invokes the method at object[key] and prepends any - * additional bindKey arguments to those provided to the bound function. This method differs - * from _.bind by allowing bound functions to reference methods that will be redefined or don't - * yet exist. See http://michaux.ca/articles/lazy-function-definition-pattern. - * @param object The object the method belongs to. - * @param key The key of the method. - * @param args Arguments to be partially applied. - * @return The new bound function. - **/ - bindKey( - object: T, - key: string, - ...args: any[]): Function; - } - - interface LoDashObjectWrapper { - /** - * @see _.bindKey - **/ - bindKey( - key: string, - ...args: any[]): LoDashObjectWrapper; - } - - //_.compose - interface LoDashStatic { - /** - * Creates a function that is the composition of the provided functions, where each function - * consumes the return value of the function that follows. For example, composing the functions - * f(), g(), and h() produces f(g(h())). Each function is executed with the this binding of the - * composed function. - * @param funcs Functions to compose. - * @return The new composed function. - **/ - compose(...funcs: Function[]): Function; - } - - interface LoDashObjectWrapper { - /** - * @see _.compose - **/ - compose(...funcs: Function[]): LoDashObjectWrapper; - } - - //_.createCallback - interface LoDashStatic { - /** - * Produces a callback bound to an optional thisArg. If func is a property name the created - * callback will return the property value for a given element. If func is an object the created - * callback will return true for elements that contain the equivalent object properties, - * otherwise it will return false. - * @param func The value to convert to a callback. - * @param thisArg The this binding of the created callback. - * @param argCount The number of arguments the callback accepts. - * @return A callback function. - **/ - createCallback( - func: string, - thisArg?: any, - argCount?: number): () => any; - - /** - * @see _.createCallback - **/ - createCallback( - func: Dictionary, - thisArg?: any, - argCount?: number): () => boolean; - } - - interface LoDashWrapper { - /** - * @see _.createCallback - **/ - createCallback( - thisArg?: any, - argCount?: number): LoDashObjectWrapper<() => any>; - } - - interface LoDashObjectWrapper { - /** - * @see _.createCallback - **/ - createCallback( - thisArg?: any, - argCount?: number): LoDashObjectWrapper<() => any>; - } - - //_.curry - interface LoDashStatic { - /** - * Creates a function which accepts one or more arguments of func that when invoked either - * executes func returning its result, if all func arguments have been provided, or returns - * a function that accepts one or more of the remaining func arguments, and so on. The arity - * of func can be specified if func.length is not sufficient. - * @param func The function to curry. - * @param arity The arity of func. - * @return The new curried function. - **/ - curry( - func: Function, - arity?: number): Function; - } - - interface LoDashObjectWrapper { - /** - * @see _.curry - **/ - curry(arity?: number): LoDashObjectWrapper; - } - - //_.debounce - interface LoDashStatic { - /** - * Creates a function that will delay the execution of func until after wait milliseconds have - * elapsed since the last time it was invoked. Provide an options object to indicate that func - * should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls - * to the debounced function will return the result of the last func call. - * - * Note: If leading and trailing options are true func will be called on the trailing edge of - * the timeout only if the the debounced function is invoked more than once during the wait - * timeout. - * @param func The function to debounce. - * @param wait The number of milliseconds to delay. - * @param options The options object. - * @param options.leading Specify execution on the leading edge of the timeout. - * @param options.maxWait The maximum time func is allowed to be delayed before it's called. - * @param options.trailing Specify execution on the trailing edge of the timeout. - * @return The new debounced function. - **/ - debounce( - func: T, - wait: number, - options?: DebounceSettings): T; - } - - interface LoDashObjectWrapper { - /** - * @see _.debounce - **/ - debounce( - wait: number, - options?: DebounceSettings): LoDashObjectWrapper; - } - - interface DebounceSettings { - /** - * Specify execution on the leading edge of the timeout. - **/ - leading?: boolean; - - /** - * The maximum time func is allowed to be delayed before it's called. - **/ - maxWait?: number; - - /** - * Specify execution on the trailing edge of the timeout. - **/ - trailing?: boolean; - } - - //_.defer - interface LoDashStatic { - /** - * Defers executing the func function until the current call stack has cleared. Additional - * arguments will be provided to func when it is invoked. - * @param func The function to defer. - * @param args Arguments to invoke the function with. - * @return The timer id. - **/ - defer( - func: Function, - ...args: any[]): number; - } - - interface LoDashObjectWrapper { - /** - * @see _.defer - **/ - defer(...args: any[]): LoDashWrapper; - } - - //_.delay - interface LoDashStatic { - /** - * Executes the func function after wait milliseconds. Additional arguments will be provided - * to func when it is invoked. - * @param func The function to delay. - * @param wait The number of milliseconds to delay execution. - * @param args Arguments to invoke the function with. - * @return The timer id. - **/ - delay( - func: Function, - wait: number, - ...args: any[]): number; - } - - interface LoDashObjectWrapper { - /** - * @see _.delay - **/ - delay( - wait: number, - ...args: any[]): LoDashWrapper; - } - - //_.memoize - interface LoDashStatic { - /** - * Creates a function that memoizes the result of func. If resolver is provided it will be - * used to determine the cache key for storing the result based on the arguments provided to - * the memoized function. By default, the first argument provided to the memoized function is - * used as the cache key. The func is executed with the this binding of the memoized function. - * The result cache is exposed as the cache property on the memoized function. - * @param func Computationally expensive function that will now memoized results. - * @param resolver Hash function for storing the result of `fn`. - * @return Returns the new memoizing function. - **/ - memoize( - func: T, - resolver?: Function): T; - } - - //_.once - interface LoDashStatic { - /** - * Creates a function that is restricted to execute func once. Repeat calls to the function - * will return the value of the first call. The func is executed with the this binding of the - * created function. - * @param func Function to only execute once. - * @return The new restricted function. - **/ - once(func: T): T; - } - - //_.partial - interface LoDashStatic { - /** - * Creates a function that, when called, invokes func with any additional partial arguments - * prepended to those provided to the new function. This method is similar to _.bind except - * it does not alter the this binding. - * @param func The function to partially apply arguments to. - * @param args Arguments to be partially applied. - * @return The new partially applied function. - **/ - partial( - func: Function, - ...args: any[]): Function; - } - - //_.partialRight - interface LoDashStatic { - /** - * This method is like _.partial except that partial arguments are appended to those provided - * to the new function. - * @param func The function to partially apply arguments to. - * @param args Arguments to be partially applied. - * @return The new partially applied function. - **/ - partialRight( - func: Function, - ...args: any[]): Function; - } - - //_.throttle - interface LoDashStatic { - /** - * Creates a function that, when executed, will only call the func function at most once per - * every wait milliseconds. Provide an options object to indicate that func should be invoked - * on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled - * function will return the result of the last func call. - * - * Note: If leading and trailing options are true func will be called on the trailing edge of - * the timeout only if the the throttled function is invoked more than once during the wait timeout. - * @param func The function to throttle. - * @param wait The number of milliseconds to throttle executions to. - * @param options The options object. - * @param options.leading Specify execution on the leading edge of the timeout. - * @param options.trailing Specify execution on the trailing edge of the timeout. - * @return The new throttled function. - **/ - throttle( - func: T, - wait: number, - options?: ThrottleSettings): T; - } - - interface ThrottleSettings { - - /** - * If you'd like to disable the leading-edge call, pass this as false. - **/ - leading?: boolean; - - /** - * If you'd like to disable the execution on the trailing-edge, pass false. - **/ - trailing?: boolean; - } - - //_.wrap - interface LoDashStatic { - /** - * Creates a function that provides value to the wrapper function as its first argument. - * Additional arguments provided to the function are appended to those provided to the - * wrapper function. The wrapper is executed with the this binding of the created function. - * @param value The value to wrap. - * @param wrapper The wrapper function. - * @return The new function. - **/ - wrap( - value: any, - wrapper: (func: Function, ...args: any[]) => any): Function; - } - - /************* - * Objects * - *************/ - - //_.assign - interface LoDashStatic { - /** - * Assigns own enumerable properties of source object(s) to the destination object. Subsequent - * sources will overwrite property assignments of previous sources. If a callback is provided - * it will be executed to produce the assigned values. The callback is bound to thisArg and - * invoked with two arguments; (objectValue, sourceValue). - * @param object The destination object. - * @param s1-8 The source object(s) - * @param callback The function to customize merging properties. - * @param thisArg The this binding of callback. - * @return The destination object. - **/ - assign( - object: T, - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - assign( - object: T, - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - assign( - object: T, - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - assign( - object: T, - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - } - - interface LoDashObjectWrapper { - /** - * @see _.assign - **/ - assign( - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - - /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - s5: S5, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - - /** - * @see _.assign - **/ - extend( - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - - /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - s5: S5, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - - } - - //_.clone - interface LoDashStatic { - /** - * Creates a clone of value. If deep is true nested objects will also be cloned, otherwise - * they will be assigned by reference. If a callback is provided it will be executed to produce - * the cloned values. If the callback returns undefined cloning will be handled by the method - * instead. The callback is bound to thisArg and invoked with one argument; (value). - * @param value The value to clone. - * @param deep Specify a deep clone. - * @param callback The function to customize cloning values. - * @param thisArg The this binding of callback. - * @return The cloned value. - **/ - clone( - value: T, - deep?: boolean, - callback?: (value: any) => any, - thisArg?: any): T; - } - - //_.cloneDeep - interface LoDashStatic { - /** - * Creates a deep clone of value. If a callback is provided it will be executed to produce the - * cloned values. If the callback returns undefined cloning will be handled by the method instead. - * The callback is bound to thisArg and invoked with one argument; (value). - * - * Note: This method is loosely based on the structured clone algorithm. Functions and DOM nodes - * are not cloned. The enumerable properties of arguments objects and objects created by constructors - * other than Object are cloned to plain Object objects. - * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. - * @param value The value to clone. - * @param callback The function to customize cloning values. - * @param thisArg The this binding of callback. - * @return The cloned value. - **/ - cloneDeep( - value: T, - callback?: (value: any) => any, - thisArg?: any): T; - } - - //_.defaults - interface LoDashStatic { - /** - * Assigns own enumerable properties of source object(s) to the destination object for all - * destination properties that resolve to undefined. Once a property is set, additional defaults - * of the same property will be ignored. - * @param object The destination object. - * @param sources The source objects. - * @return The destination object. - **/ - defaults( - object: T, - ...sources: any[]): TResult; - - - //@xiphiaz added defaultsDeep here for lodash 3.10.1 - defaultsDeep( - object: T, - ...sources: any[]): TResult; - } - - interface LoDashObjectWrapper { - /** - * @see _.defaults - **/ - defaults(...sources: any[]): LoDashObjectWrapper - } - - //_.findKey - interface LoDashStatic { - /** - * This method is like _.findIndex except that it returns the key of the first element that - * passes the callback check, instead of the element itself. - * @param object The object to search. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return The key of the found element, else undefined. - **/ - findKey( - object: any, - callback: (value: any) => boolean, - thisArg?: any): string; - - /** - * @see _.findKey - * @param pluckValue _.pluck style callback - **/ - findKey( - object: any, - pluckValue: string): string; - - /** - * @see _.findKey - * @param whereValue _.where style callback - **/ - findKey, T>( - object: T, - whereValue: W): string; - } - - //_.findLastKey - interface LoDashStatic { - /** - * This method is like _.findKey except that it iterates over elements of a collection in the opposite order. - * @param object The object to search. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return The key of the found element, else undefined. - **/ - findLastKey( - object: any, - callback: (value: any) => boolean, - thisArg?: any): string; - - /** - * @see _.findLastKey - * @param pluckValue _.pluck style callback - **/ - findLastKey( - object: any, - pluckValue: string): string; - - /** - * @see _.findLastKey - * @param whereValue _.where style callback - **/ - findLastKey, T>( - object: T, - whereValue: W): string; - } - - //_.forIn - interface LoDashStatic { - /** - * Iterates over own and inherited enumerable properties of an object, executing the callback for - * each property. The callback is bound to thisArg and invoked with three arguments; (value, key, - * object). Callbacks may exit iteration early by explicitly returning false. - * @param object The object to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return object - **/ - forIn( - object: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.forIn - **/ - forIn( - object: T, - callback?: ObjectIterator, - thisArg?: any): T; - } - - interface LoDashObjectWrapper { - /** - * @see _.forIn - **/ - forIn( - callback: ObjectIterator, - thisArg?: any): _.LoDashObjectWrapper; - } - - //_.forInRight - interface LoDashStatic { - /** - * This method is like _.forIn except that it iterates over elements of a collection in the - * opposite order. - * @param object The object to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return object - **/ - forInRight( - object: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.forInRight - **/ - forInRight( - object: T, - callback?: ObjectIterator, - thisArg?: any): T; - } - - interface LoDashObjectWrapper { - /** - * @see _.forInRight - **/ - forInRight( - callback: ObjectIterator, - thisArg?: any): _.LoDashObjectWrapper; - } - - //_.forOwn - interface LoDashStatic { - /** - * Iterates over own enumerable properties of an object, executing the callback for each - * property. The callback is bound to thisArg and invoked with three arguments; (value, key, - * object). Callbacks may exit iteration early by explicitly returning false. - * @param object The object to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return object - **/ - forOwn( - object: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): Dictionary; - - /** - * @see _.forOwn - **/ - forOwn( - object: T, - callback?: ObjectIterator, - thisArg?: any): T; - } - - interface LoDashObjectWrapper { - /** - * @see _.forOwn - **/ - forOwn( - callback: ObjectIterator, - thisArg?: any): _.LoDashObjectWrapper; - } - - //_.forOwnRight - interface LoDashStatic { - /** - * This method is like _.forOwn except that it iterates over elements of a collection in the - * opposite order. - * @param object The object to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - * @return object - **/ - forOwnRight( - object: Dictionary, - callback?: DictionaryIterator, - thisArg?: any): Dictionary; - /** - * @see _.forOwnRight - **/ - forOwnRight( - object: T, - callback?: ObjectIterator, - thisArg?: any): T; - } - - interface LoDashObjectWrapper { - /** - * @see _.forOwnRight - **/ - forOwnRight( - callback: ObjectIterator, - thisArg?: any): _.LoDashObjectWrapper; - } - - //_.functions - interface LoDashStatic { - /** - * Creates a sorted array of property names of all enumerable properties, own and inherited, of - * object that have function values. - * @param object The object to inspect. - * @return An array of property names that have function values. - **/ - functions(object: any): string[]; - - /** - * @see _functions - **/ - methods(object: any): string[]; - } - - interface LoDashObjectWrapper { - /** - * @see _.functions - **/ - functions(): _.LoDashArrayWrapper; - - /** - * @see _.functions - **/ - methods(): _.LoDashArrayWrapper; - } - - //_.get - interface LoDashStatic { - /** - * Gets the property value at path of object. If the resolved - * value is undefined the defaultValue is used in its place. - * @param object The object to query. - * @param path The path of the property to get. - * @param defaultValue The value returned if the resolved value is undefined. - * @return Returns the resolved value. - **/ - get(object : Object, - path:string|string[], - defaultValue?:T - ): T; - } - - //_.has - interface LoDashStatic { - /** - * Checks if the specified object property exists and is a direct property, instead of an - * inherited property. - * @param object The object to check. - * @param property The property to check for. - * @return True if key is a direct property, else false. - **/ - has(object: any, property: string): boolean; - } - - //_.invert - interface LoDashStatic { - /** - * Creates an object composed of the inverted keys and values of the given object. - * @param object The object to invert. - * @return The created inverted object. - **/ - invert(object: any): any; - } - - //_.isArguments - interface LoDashStatic { - /** - * Checks if value is an arguments object. - * @param value The value to check. - * @return True if the value is an arguments object, else false. - **/ - isArguments(value?: any): boolean; - } - - //_.isArray - interface LoDashStatic { - /** - * Checks if value is an array. - * @param value The value to check. - * @return True if the value is an array, else false. - **/ - isArray(value?: any): boolean; - } - - //_.isBoolean - interface LoDashStatic { - /** - * Checks if value is a boolean value. - * @param value The value to check. - * @return True if the value is a boolean value, else false. - **/ - isBoolean(value?: any): boolean; - } - - //_.isDate - interface LoDashStatic { - /** - * Checks if value is a date. - * @param value The value to check. - * @return True if the value is a date, else false. - **/ - isDate(value?: any): boolean; - } - - //_.isElement - interface LoDashStatic { - /** - * Checks if value is a DOM element. - * @param value The value to check. - * @return True if the value is a DOM element, else false. - **/ - isElement(value?: any): boolean; - } - - //_.isEmpty - interface LoDashStatic { - /** - * Checks if value is empty. Arrays, strings, or arguments objects with a length of 0 and objects - * with no own enumerable properties are considered "empty". - * @param value The value to inspect. - * @return True if the value is empty, else false. - **/ - isEmpty(value?: any[]|Dictionary|string|any): boolean; - } - - //_.isError - interface LoDashStatic { - /** - * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, - * or URIError object. - * @param value The value to check. - * @return True if value is an error object, else false. - */ - isError(value: any): boolean; - } - - - //_.isEqual - interface LoDashStatic { - /** - * Performs a deep comparison between two values to determine if they are equivalent to each - * other. If a callback is provided it will be executed to compare values. If the callback - * returns undefined comparisons will be handled by the method instead. The callback is bound to - * thisArg and invoked with two arguments; (a, b). - * @param a The value to compare. - * @param b The other value to compare. - * @param callback The function to customize comparing values. - * @param thisArg The this binding of callback. - * @return True if the values are equivalent, else false. - **/ - isEqual( - a?: any, - b?: any, - callback?: (a: any, b: any) => boolean, - thisArg?: any): boolean; - } - - //_.isFinite - interface LoDashStatic { - /** - * Checks if value is, or can be coerced to, a finite number. - * - * Note: This is not the same as native isFinite which will return true for booleans and empty - * strings. See http://es5.github.io/#x15.1.2.5. - * @param value The value to check. - * @return True if the value is finite, else false. - **/ - isFinite(value?: any): boolean; - } - - //_.isFunction - interface LoDashStatic { - /** - * Checks if value is a function. - * @param value The value to check. - * @return True if the value is a function, else false. - **/ - isFunction(value?: any): boolean; - } - - //_.isNaN - interface LoDashStatic { - /** - * Checks if value is NaN. - * - * Note: This is not the same as native isNaN which will return true for undefined and other - * non-numeric values. See http://es5.github.io/#x15.1.2.4. - * @param value The value to check. - * @return True if the value is NaN, else false. - **/ - isNaN(value?: any): boolean; - } - - //_.isNull - interface LoDashStatic { - /** - * Checks if value is null. - * @param value The value to check. - * @return True if the value is null, else false. - **/ - isNull(value?: any): boolean; - } - - //_.isNumber - interface LoDashStatic { - /** - * Checks if value is a number. - * - * Note: NaN is considered a number. See http://es5.github.io/#x8.5. - * @param value The value to check. - * @return True if the value is a number, else false. - **/ - isNumber(value?: any): boolean; - } - - //_.isObject - interface LoDashStatic { - /** - * Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, - * new Number(0), and new String('')) - * @param value The value to check. - * @return True if the value is an object, else false. - **/ - isObject(value?: any): boolean; - } - - //_.isPlainObject - interface LoDashStatic { - /** - * Checks if value is an object created by the Object constructor. - * @param value The value to check. - * @return True if value is a plain object, else false. - **/ - isPlainObject(value?: any): boolean; - } - - //_.isRegExp - interface LoDashStatic { - /** - * Checks if value is a regular expression. - * @param value The value to check. - * @return True if the value is a regular expression, else false. - **/ - isRegExp(value?: any): boolean; - } - - //_.isString - interface LoDashStatic { - /** - * Checks if value is a string. - * @param value The value to check. - * @return True if the value is a string, else false. - **/ - isString(value?: any): boolean; - } - - //_.isUndefined - interface LoDashStatic { - /** - * Checks if value is undefined. - * @param value The value to check. - * @return True if the value is undefined, else false. - **/ - isUndefined(value?: any): boolean; - } - - //_.keys - interface LoDashStatic { - /** - * Creates an array composed of the own enumerable property names of an object. - * @param object The object to inspect. - * @return An array of property names. - **/ - keys(object?: any): string[]; - } - - interface LoDashObjectWrapper { - /** - * @see _.keys - **/ - keys(): LoDashArrayWrapper - } - - //_.mapValues - interface LoDashStatic { - /** - * Creates an object with the same keys as object and values generated by running each own - * enumerable property of object through iteratee. The iteratee function is bound to thisArg - * and invoked with three arguments: (value, key, object). - * - * If a property name is provided iteratee the created "_.property" style callback returns - * the property value of the given element. - * - * If a value is also provided for thisArg the creted "_.matchesProperty" style callback returns - * true for elements that have a matching property value, else false;. - * - * If an object is provided for iteratee the created "_.matches" style callback returns true - * for elements that have the properties of the given object, else false. - * - * @param {Object} object The object to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration. - * @param {Object} [thisArg] The `this` binding of `iteratee`. - * @return {Object} Returns the new mapped object. - */ - mapValues(obj: Dictionary, callback: ObjectIterator, thisArg?: any): Dictionary; - mapValues(obj: Dictionary, where: Dictionary): Dictionary; - mapValues(obj: T, pluck: string): TMapped; - mapValues(obj: T, callback: ObjectIterator, thisArg?: any): T; - } - - interface LoDashObjectWrapper { - /** - * @see _.mapValues - * TValue is the type of the property values of T. - * TResult is the type output by the ObjectIterator function - */ - mapValues(callback: ObjectIterator, thisArg?: any): LoDashObjectWrapper>; - - /** - * @see _.mapValues - * TResult is the type of the property specified by pluck. - * T should be a Dictionary> - */ - mapValues(pluck: string): LoDashObjectWrapper>; - - /** - * @see _.mapValues - * TResult is the type of the properties on the object specified by pluck. - * T should be a Dictionary>> - */ - mapValues(pluck: string, where: Dictionary): LoDashArrayWrapper>; - - /** - * @see _.mapValues - * TResult is the type of the properties of each object in the values of T - * T should be a Dictionary> - */ - mapValues(where: Dictionary): LoDashArrayWrapper; - } - - //_.merge - interface LoDashStatic { - /** - * Recursively merges own enumerable properties of the source object(s), that don't resolve - * to undefined into the destination object. Subsequent sources will overwrite property - * assignments of previous sources. If a callback is provided it will be executed to produce - * the merged values of the destination and source properties. If the callback returns undefined - * merging will be handled by the method instead. The callback is bound to thisArg and invoked - * with two arguments; (objectValue, sourceValue). - * @param object The destination object. - * @param s1-8 The source object(s) - * @param callback The function to customize merging properties. - * @param thisArg The this binding of callback. - * @return The destination object. - **/ - merge( - object: T, - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.merge - **/ - merge( - object: T, - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.merge - **/ - merge( - object: T, - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.merge - **/ - merge( - object: T, - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - } - - //_.omit - interface LoDashStatic { - /** - * Creates a shallow clone of object excluding the specified properties. Property names may be - * specified as individual arguments or as arrays of property names. If a callback is provided - * it will be executed for each property of object omitting the properties the callback returns - * truey for. The callback is bound to thisArg and invoked with three arguments; (value, key, - * object). - * @param object The source object. - * @param keys The properties to omit. - * @return An object without the omitted properties. - **/ - omit( - object: T, - ...keys: string[]): Omitted; - - /** - * @see _.omit - **/ - omit( - object: T, - keys: string[]): Omitted; - - /** - * @see _.omit - **/ - omit( - object: T, - callback: ObjectIterator, - thisArg?: any): Omitted; - } - - interface LoDashObjectWrapper { - /** - * @see _.omit - **/ - omit( - ...keys: string[]): LoDashObjectWrapper; - - /** - * @see _.omit - **/ - omit( - keys: string[]): LoDashObjectWrapper; - - /** - * @see _.omit - **/ - omit( - callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper; - } - - //_.pairs - interface LoDashStatic { - /** - * Creates a two dimensional array of an object's key-value pairs, - * i.e. [[key1, value1], [key2, value2]]. - * @param object The object to inspect. - * @return Aew array of key-value pairs. - **/ - pairs(object?: any): any[][]; - } - - interface LoDashObjectWrapper { - /** - * @see _.pairs - **/ - pairs(): LoDashArrayWrapper; - } - - //_.picks - interface LoDashStatic { - /** - * Creates a shallow clone of object composed of the specified properties. Property names may be - * specified as individual arguments or as arrays of property names. If a callback is provided - * it will be executed for each property of object picking the properties the callback returns - * truey for. The callback is bound to thisArg and invoked with three arguments; (value, key, - * object). - * @param object Object to strip unwanted key/value pairs. - * @param keys Property names to pick - * @return An object composed of the picked properties. - **/ - pick( - object: T, - ...keys: string[]): Picked; - - /** - * @see _.pick - **/ - pick( - object: T, - keys: string[]): Picked; - - /** - * @see _.pick - **/ - pick( - object: T, - callback: ObjectIterator, - thisArg?: any): Picked; - } - - //_.transform - interface LoDashStatic { - /** - * An alternative to _.reduce this method transforms object to a new accumulator object which is - * the result of running each of its elements through a callback, with each callback execution - * potentially mutating the accumulator object. The callback is bound to thisArg and invoked with - * four arguments; (accumulator, value, key, object). Callbacks may exit iteration early by - * explicitly returning false. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param accumulator The custom accumulator value. - * @param thisArg The this binding of callback. - * @return The accumulated value. - **/ - transform( - collection: Array, - callback: MemoVoidIterator, - accumulator: Acc, - thisArg?: any): Acc; - - /** - * @see _.transform - **/ - transform( - collection: List, - callback: MemoVoidIterator, - accumulator: Acc, - thisArg?: any): Acc; - - /** - * @see _.transform - **/ - transform( - collection: Dictionary, - callback: MemoVoidIterator, - accumulator: Acc, - thisArg?: any): Acc; - - /** - * @see _.transform - **/ - transform( - collection: Array, - callback?: MemoVoidIterator, - thisArg?: any): Acc; - - /** - * @see _.transform - **/ - transform( - collection: List, - callback?: MemoVoidIterator, - thisArg?: any): Acc; - - /** - * @see _.transform - **/ - transform( - collection: Dictionary, - callback?: MemoVoidIterator, - thisArg?: any): Acc; - } - - //_.values - interface LoDashStatic { - /** - * Creates an array composed of the own enumerable property values of object. - * @param object The object to inspect. - * @return Returns an array of property values. - **/ - values(object?: any): any[]; - } - - /********** - * String * - **********/ - - interface LoDashStatic { - camelCase(str?: string): string; - capitalize(str?: string): string; - deburr(str?: string): string; - endsWith(str?: string, target?: string, position?: number): boolean; - escape(str?: string): string; - escapeRegExp(str?: string): string; - kebabCase(str?: string): string; - pad(str?: string, length?: number, chars?: string): string; - padLeft(str?: string, length?: number, chars?: string): string; - padRight(str?: string, length?: number, chars?: string): string; - repeat(str?: string, n?: number): string; - snakeCase(str?: string): string; - startCase(str?: string): string; - startsWith(str?: string, target?: string, position?: number): boolean; - trim(str?: string, chars?: string): string; - trimLeft(str?: string, chars?: string): string; - trimRight(str?: string, chars?: string): string; - trunc(str?: string, len?: number): string; - trunc(str?: string, options?: { length?: number; omission?: string; separator?: string|RegExp }): string; - words(str?: string, pattern?: string|RegExp): string[]; - } - - //_.parseInt - interface LoDashStatic { - /** - * Converts the given value into an integer of the specified radix. If radix is undefined or 0 a - * radix of 10 is used unless the value is a hexadecimal, in which case a radix of 16 is used. - * - * Note: This method avoids differences in native ES3 and ES5 parseInt implementations. See - * http://es5.github.io/#E. - * @param value The value to parse. - * @param radix The radix used to interpret the value to parse. - * @return The new integer value. - **/ - parseInt(value?: string, radix?: number): number; - } - - /************* - * Utilities * - *************/ - //_.escape - interface LoDashStatic { - /** - * Converts the characters &, <, >, ", and ' in string to their corresponding HTML entities. - * @param string The string to escape. - * @return The escaped string. - **/ - escape(str?: string): string; - } - - //_.identity - interface LoDashStatic { - /** - * This method returns the first argument provided to it. - * @param value Any value. - * @return value. - **/ - identity(value?: T): T; - } - - //_.mixin - interface LoDashStatic { - /** - * Adds function properties of a source object to the lodash function and chainable wrapper. - * @param object The object of function properties to add to lodash. - **/ - mixin(object?: Dictionary<(value: any) => any>): void; - } - - //_.noConflict - interface LoDashStatic { - /** - * Reverts the '_' variable to its previous value and returns a reference to the lodash function. - * @return The lodash function. - **/ - noConflict(): typeof _; - } - - //_.property - interface LoDashStatic { - /** - * # S - * Creates a "_.pluck" style function, which returns the key value of a given object. - * @param key (string) - * @return the value of that key on the object - **/ - property(key: string): (obj: T) => RT; - } - - //_.random - interface LoDashStatic { - /** - * Produces a random number between min and max (inclusive). If only one argument is provided a - * number between 0 and the given number will be returned. If floating is truey or either min or - * max are floats a floating-point number will be returned instead of an integer. - * @param max The maximum possible value. - * @param floating Specify returning a floating-point number. - * @return A random number. - **/ - random(max: number, floating?: boolean): number; - - /** - * @see _.random - * @param min The minimum possible value. - * @return A random number between `min` and `max`. - **/ - random(min: number, max: number, floating?: boolean): number; - } - - //_.result - interface LoDashStatic { - /** - * Resolves the value of property on object. If property is a function it will be invoked with - * the this binding of object and its result returned, else the property value is returned. If - * object is falsey then undefined is returned. - * @param object The object to inspect. - * @param property The property to get the value of. - * @return The resolved value. - **/ - result(object: any, property: string): any; - } - - //_.runInContext - interface LoDashStatic { - /** - * Create a new lodash function using the given context object. - * @param context The context object - * @returns The lodash function. - **/ - runInContext(context: any): typeof _; - } - - //_.template - interface LoDashStatic { - /** - * A micro-templating method that handles arbitrary delimiters, preserves whitespace, and - * correctly escapes quotes within interpolated code. - * - * Note: In the development build, _.template utilizes sourceURLs for easier debugging. See - * http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl - * - * For more information on precompiling templates see: - * http://lodash.com/#custom-builds - * - * For more information on Chrome extension sandboxes see: - * http://developer.chrome.com/stable/extensions/sandboxingEval.html - * @param text The template text. - * @param data The data object used to populate the text. - * @param options The options object. - * @param options.escape The "escape" delimiter. - * @param options.evaluate The "evaluate" delimiter. - * @param options.import An object to import into the template as local variables. - * @param options.interpolate The "interpolate" delimiter. - * @param sourceURL The sourceURL of the template's compiled source. - * @param variable The data object variable name. - * @return Returns the compiled Lo-Dash HTML template or a TemplateExecutor if no data is passed. - **/ - template( - text: string): TemplateExecutor; - - /** - * @see _.template - **/ - template( - text: string, - data: any, - options?: TemplateSettings, - sourceURL?: string, - variable?: string): any /* string or TemplateExecutor*/; - } - - interface TemplateExecutor { - (...data: any[]): string; - source: string; - } - - //_.times - interface LoDashStatic { - /** - * Executes the callback n times, returning an array of the results of each callback execution. - * The callback is bound to thisArg and invoked with one argument; (index). - * @param n The number of times to execute the callback. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - times( - n: number, - callback: (num: number) => TResult, - context?: any): TResult[]; - } - - //_.unescape - interface LoDashStatic { - /** - * The inverse of _.escape this method converts the HTML entities &, <, >, ", and - * ' in string to their corresponding characters. - * @param string The string to unescape. - * @return The unescaped string. - **/ - unescape( - string: string): string; - } - - //_.uniqueId - interface LoDashStatic { - /** - * Generates a unique ID. If prefix is provided the ID will be appended to it. - * @param prefix The value to prefix the ID with. - * @return Returns the unique ID. - **/ - uniqueId(prefix?: string): string; - } - - //_.noop - interface LoDashStatic { - /** - * A no-operation function. - **/ - noop(): void; - } - - //_.constant - interface LoDashStatic { - /** - * Creates a function that returns value.. - **/ - constant(value: T): () => T; - } - - //_.create - interface LoDashStatic { - /** - * Creates an object that inherits from the given prototype object. If a properties object is provided its own enumerable properties are assigned to the created object. - * @param prototype The object to inherit from. - * @param properties The properties to assign to the object. - */ - create(prototype: Object, properties?: Object): Object; - } - - interface ListIterator { - (value: T, index: number, collection: T[]): TResult; - } - - interface DictionaryIterator { - (value: T, key: string, collection: Dictionary): TResult; - } - - interface ObjectIterator { - (element: T, key: string, collection: any): TResult; - } - - interface MemoVoidIterator { - (prev: TResult, curr: T, indexOrKey: any, list?: T[]): void; - } - interface MemoIterator { - (prev: TResult, curr: T, indexOrKey: any, list?: T[]): TResult; - } - /* - interface MemoListIterator { - (prev: TResult, curr: T, index: number, list?: T[]): TResult; - } - interface MemoObjectIterator { - (prev: TResult, curr: T, index: string, object?: Dictionary): TResult; - } - */ - - //interface Collection {} - - // Common interface between Arrays and jQuery objects - interface List { - [index: number]: T; - length: number; - } - - interface Dictionary { - [index: string]: T; - } -} - -declare module "lodash" { - export = _; -} diff --git a/typings/mocha/mocha.d.ts b/typings/mocha/mocha.d.ts deleted file mode 100644 index 88dc359..0000000 --- a/typings/mocha/mocha.d.ts +++ /dev/null @@ -1,214 +0,0 @@ -// Type definitions for mocha 2.2.5 -// Project: http://mochajs.org/ -// Definitions by: Kazi Manzur Rashid , otiai10 , jt000 , Vadim Macagon -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface MochaSetupOptions { - //milliseconds to wait before considering a test slow - slow?: number; - - // timeout in milliseconds - timeout?: number; - - // ui name "bdd", "tdd", "exports" etc - ui?: string; - - //array of accepted globals - globals?: any[]; - - // reporter instance (function or string), defaults to `mocha.reporters.Spec` - reporter?: any; - - // bail on the first test failure - bail?: boolean; - - // ignore global leaks - ignoreLeaks?: boolean; - - // grep string or regexp to filter tests with - grep?: any; -} - -interface MochaDone { - (error?: Error): void; -} - -declare var mocha: Mocha; -declare var describe: Mocha.IContextDefinition; -declare var xdescribe: Mocha.IContextDefinition; -// alias for `describe` -declare var context: Mocha.IContextDefinition; -// alias for `describe` -declare var suite: Mocha.IContextDefinition; -declare var it: Mocha.ITestDefinition; -declare var xit: Mocha.ITestDefinition; -// alias for `it` -declare var test: Mocha.ITestDefinition; - -declare function before(action: () => void): void; - -declare function before(action: (done: MochaDone) => void): void; - -declare function setup(action: () => void): void; - -declare function setup(action: (done: MochaDone) => void): void; - -declare function after(action: () => void): void; - -declare function after(action: (done: MochaDone) => void): void; - -declare function teardown(action: () => void): void; - -declare function teardown(action: (done: MochaDone) => void): void; - -declare function beforeEach(action: () => void): void; - -declare function beforeEach(action: (done: MochaDone) => void): void; - -declare function suiteSetup(action: () => void): void; - -declare function suiteSetup(action: (done: MochaDone) => void): void; - -declare function afterEach(action: () => void): void; - -declare function afterEach(action: (done: MochaDone) => void): void; - -declare function suiteTeardown(action: () => void): void; - -declare function suiteTeardown(action: (done: MochaDone) => void): void; - -declare class Mocha { - constructor(options?: { - grep?: RegExp; - ui?: string; - reporter?: string; - timeout?: number; - bail?: boolean; - }); - - /** Setup mocha with the given options. */ - setup(options: MochaSetupOptions): Mocha; - bail(value?: boolean): Mocha; - addFile(file: string): Mocha; - /** Sets reporter by name, defaults to "spec". */ - reporter(name: string): Mocha; - /** Sets reporter constructor, defaults to mocha.reporters.Spec. */ - reporter(reporter: (runner: Mocha.IRunner, options: any) => any): Mocha; - ui(value: string): Mocha; - grep(value: string): Mocha; - grep(value: RegExp): Mocha; - invert(): Mocha; - ignoreLeaks(value: boolean): Mocha; - checkLeaks(): Mocha; - /** Enables growl support. */ - growl(): Mocha; - globals(value: string): Mocha; - globals(values: string[]): Mocha; - useColors(value: boolean): Mocha; - useInlineDiffs(value: boolean): Mocha; - timeout(value: number): Mocha; - slow(value: number): Mocha; - enableTimeouts(value: boolean): Mocha; - asyncOnly(value: boolean): Mocha; - noHighlighting(value: boolean): Mocha; - /** Runs tests and invokes `onComplete()` when finished. */ - run(onComplete?: (failures: number) => void): Mocha.IRunner; -} - -// merge the Mocha class declaration with a module -declare module Mocha { - /** Partial interface for Mocha's `Runnable` class. */ - interface IRunnable { - title: string; - fn: Function; - async: boolean; - sync: boolean; - timedOut: boolean; - } - - /** Partial interface for Mocha's `Suite` class. */ - interface ISuite { - parent: ISuite; - title: string; - - fullTitle(): string; - } - - /** Partial interface for Mocha's `Test` class. */ - interface ITest extends IRunnable { - parent: ISuite; - pending: boolean; - - fullTitle(): string; - } - - /** Partial interface for Mocha's `Runner` class. */ - interface IRunner {} - - interface IContextDefinition { - (description: string, spec: () => void): ISuite; - only(description: string, spec: () => void): ISuite; - skip(description: string, spec: () => void): void; - timeout(ms: number): void; - } - - interface ITestDefinition { - (expectation: string, assertion?: () => void): ITest; - (expectation: string, assertion?: (done: MochaDone) => void): ITest; - only(expectation: string, assertion?: () => void): ITest; - only(expectation: string, assertion?: (done: MochaDone) => void): ITest; - skip(expectation: string, assertion?: () => void): void; - skip(expectation: string, assertion?: (done: MochaDone) => void): void; - timeout(ms: number): void; - } - - export module reporters { - export class Base { - stats: { - suites: number; - tests: number; - passes: number; - pending: number; - failures: number; - }; - - constructor(runner: IRunner); - } - - export class Doc extends Base {} - export class Dot extends Base {} - export class HTML extends Base {} - export class HTMLCov extends Base {} - export class JSON extends Base {} - export class JSONCov extends Base {} - export class JSONStream extends Base {} - export class Landing extends Base {} - export class List extends Base {} - export class Markdown extends Base {} - export class Min extends Base {} - export class Nyan extends Base {} - export class Progress extends Base { - /** - * @param options.open String used to indicate the start of the progress bar. - * @param options.complete String used to indicate a complete test on the progress bar. - * @param options.incomplete String used to indicate an incomplete test on the progress bar. - * @param options.close String used to indicate the end of the progress bar. - */ - constructor(runner: IRunner, options?: { - open?: string; - complete?: string; - incomplete?: string; - close?: string; - }); - } - export class Spec extends Base {} - export class TAP extends Base {} - export class XUnit extends Base { - constructor(runner: IRunner, options?: any); - } - } -} - -declare module "mocha" { - export = Mocha; -} diff --git a/typings/moment/moment-node.d.ts b/typings/moment/moment-node.d.ts deleted file mode 100644 index ba5fe85..0000000 --- a/typings/moment/moment-node.d.ts +++ /dev/null @@ -1,483 +0,0 @@ -// Type definitions for Moment.js 2.8.0 -// Project: https://github.com/timrwood/moment -// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink , Adi Dahiya -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module moment { - - interface MomentInput { - - years?: number; - y?: number; - - months?: number; - M?: number; - - weeks?: number; - w?: number; - - days?: number; - d?: number; - - hours?: number; - h?: number; - - minutes?: number; - m?: number; - - seconds?: number; - s?: number; - - milliseconds?: number; - ms?: number; - - } - - interface Duration { - - humanize(withSuffix?: boolean): string; - - as(units: string): number; - - milliseconds(): number; - asMilliseconds(): number; - - seconds(): number; - asSeconds(): number; - - minutes(): number; - asMinutes(): number; - - hours(): number; - asHours(): number; - - days(): number; - asDays(): number; - - months(): number; - asMonths(): number; - - years(): number; - asYears(): number; - - add(n: number, p: string): Duration; - add(n: number): Duration; - add(d: Duration): Duration; - - subtract(n: number, p: string): Duration; - subtract(n: number): Duration; - subtract(d: Duration): Duration; - - toISOString(): string; - - } - - interface Moment { - - format(format: string): string; - format(): string; - - fromNow(withoutSuffix?: boolean): string; - - startOf(unitOfTime: string): Moment; - endOf(unitOfTime: string): Moment; - - /** - * Mutates the original moment by adding time. (deprecated in 2.8.0) - * - * @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc) - * @param amount the amount you want to add - */ - add(unitOfTime: string, amount: number): Moment; - /** - * Mutates the original moment by adding time. - * - * @param amount the amount you want to add - * @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc) - */ - add(amount: number, unitOfTime: string): Moment; - /** - * Mutates the original moment by adding time. Note that the order of arguments can be flipped. - * - * @param amount the amount you want to add - * @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc) - */ - add(amount: string, unitOfTime: string): Moment; - /** - * Mutates the original moment by adding time. - * - * @param objectLiteral an object literal that describes multiple time units {days:7,months:1} - */ - add(objectLiteral: MomentInput): Moment; - /** - * Mutates the original moment by adding time. - * - * @param duration a length of time - */ - add(duration: Duration): Moment; - - /** - * Mutates the original moment by subtracting time. (deprecated in 2.8.0) - * - * @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc) - * @param amount the amount you want to subtract - */ - subtract(unitOfTime: string, amount: number): Moment; - /** - * Mutates the original moment by subtracting time. - * - * @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc) - * @param amount the amount you want to subtract - */ - subtract(amount: number, unitOfTime: string): Moment; - /** - * Mutates the original moment by subtracting time. Note that the order of arguments can be flipped. - * - * @param amount the amount you want to add - * @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc) - */ - subtract(amount: string, unitOfTime: string): Moment; - /** - * Mutates the original moment by subtracting time. - * - * @param objectLiteral an object literal that describes multiple time units {days:7,months:1} - */ - subtract(objectLiteral: MomentInput): Moment; - /** - * Mutates the original moment by subtracting time. - * - * @param duration a length of time - */ - subtract(duration: Duration): Moment; - - calendar(): string; - calendar(start: Moment): string; - - clone(): Moment; - - /** - * @return Unix timestamp, or milliseconds since the epoch. - */ - valueOf(): number; - - local(): Moment; // current date/time in local mode - - utc(): Moment; // current date/time in UTC mode - - isValid(): boolean; - - year(y: number): Moment; - year(): number; - quarter(): number; - quarter(q: number): Moment; - month(M: number): Moment; - month(M: string): Moment; - month(): number; - day(d: number): Moment; - day(d: string): Moment; - day(): number; - date(d: number): Moment; - date(): number; - hour(h: number): Moment; - hour(): number; - hours(h: number): Moment; - hours(): number; - minute(m: number): Moment; - minute(): number; - minutes(m: number): Moment; - minutes(): number; - second(s: number): Moment; - second(): number; - seconds(s: number): Moment; - seconds(): number; - millisecond(ms: number): Moment; - millisecond(): number; - milliseconds(ms: number): Moment; - milliseconds(): number; - weekday(): number; - weekday(d: number): Moment; - isoWeekday(): number; - isoWeekday(d: number): Moment; - weekYear(): number; - weekYear(d: number): Moment; - isoWeekYear(): number; - isoWeekYear(d: number): Moment; - week(): number; - week(d: number): Moment; - weeks(): number; - weeks(d: number): Moment; - isoWeek(): number; - isoWeek(d: number): Moment; - isoWeeks(): number; - isoWeeks(d: number): Moment; - weeksInYear(): number; - isoWeeksInYear(): number; - dayOfYear(): number; - dayOfYear(d: number): Moment; - - from(f: Moment): string; - from(f: Moment, suffix: boolean): string; - from(d: Date): string; - from(s: string): string; - from(date: number[]): string; - - diff(b: Moment): number; - diff(b: Moment, unitOfTime: string): number; - diff(b: Moment, unitOfTime: string, round: boolean): number; - - toArray(): number[]; - toDate(): Date; - toISOString(): string; - toJSON(): string; - unix(): number; - - isLeapYear(): boolean; - zone(): number; - zone(b: number): Moment; - zone(b: string): Moment; - utcOffset(): number; - utcOffset(b: number): Moment; - utcOffset(b: string): Moment; - daysInMonth(): number; - isDST(): boolean; - - isBefore(): boolean; - isBefore(b: Moment): boolean; - isBefore(b: string): boolean; - isBefore(b: Number): boolean; - isBefore(b: Date): boolean; - isBefore(b: number[]): boolean; - isBefore(b: Moment, granularity: string): boolean; - isBefore(b: String, granularity: string): boolean; - isBefore(b: Number, granularity: string): boolean; - isBefore(b: Date, granularity: string): boolean; - isBefore(b: number[], granularity: string): boolean; - - isAfter(): boolean; - isAfter(b: Moment): boolean; - isAfter(b: string): boolean; - isAfter(b: Number): boolean; - isAfter(b: Date): boolean; - isAfter(b: number[]): boolean; - isAfter(b: Moment, granularity: string): boolean; - isAfter(b: String, granularity: string): boolean; - isAfter(b: Number, granularity: string): boolean; - isAfter(b: Date, granularity: string): boolean; - isAfter(b: number[], granularity: string): boolean; - - isSame(b: Moment): boolean; - isSame(b: string): boolean; - isSame(b: Number): boolean; - isSame(b: Date): boolean; - isSame(b: number[]): boolean; - isSame(b: Moment, granularity: string): boolean; - isSame(b: String, granularity: string): boolean; - isSame(b: Number, granularity: string): boolean; - isSame(b: Date, granularity: string): boolean; - isSame(b: number[], granularity: string): boolean; - - // Deprecated as of 2.8.0. - lang(language: string): Moment; - lang(reset: boolean): Moment; - lang(): MomentLanguage; - - locale(language: string): Moment; - locale(reset: boolean): Moment; - locale(): string; - - localeData(language: string): Moment; - localeData(reset: boolean): Moment; - localeData(): MomentLanguage; - - // Deprecated as of 2.7.0. - max(date: Date): Moment; - max(date: number): Moment; - max(date: any[]): Moment; - max(date: string): Moment; - max(date: string, format: string): Moment; - max(clone: Moment): Moment; - - // Deprecated as of 2.7.0. - min(date: Date): Moment; - min(date: number): Moment; - min(date: any[]): Moment; - min(date: string): Moment; - min(date: string, format: string): Moment; - min(clone: Moment): Moment; - - get(unit: string): number; - set(unit: string, value: number): Moment; - - } - - interface MomentCalendar { - - lastDay: any; - sameDay: any; - nextDay: any; - lastWeek: any; - nextWeek: any; - sameElse: any; - - } - - interface BaseMomentLanguage { - months ?: any; - monthsShort ?: any; - weekdays ?: any; - weekdaysShort ?: any; - weekdaysMin ?: any; - relativeTime ?: MomentRelativeTime; - meridiem ?: (hour: number, minute: number, isLowercase: boolean) => string; - calendar ?: MomentCalendar; - ordinal ?: (num: number) => string; - } - - interface MomentLanguage extends BaseMomentLanguage { - longDateFormat?: MomentLongDateFormat; - } - - interface MomentLanguageData extends BaseMomentLanguage { - /** - * @param formatType should be L, LL, LLL, LLLL. - */ - longDateFormat(formatType: string): string; - } - - interface MomentLongDateFormat { - - L: string; - LL: string; - LLL: string; - LLLL: string; - LT: string; - l?: string; - ll?: string; - lll?: string; - llll?: string; - lt?: string; - - } - - interface MomentRelativeTime { - - future: any; - past: any; - s: any; - m: any; - mm: any; - h: any; - hh: any; - d: any; - dd: any; - M: any; - MM: any; - y: any; - yy: any; - - } - - interface MomentStatic { - - version: string; - - (): Moment; - (date: number): Moment; - (date: number[]): Moment; - (date: string, format?: string, strict?: boolean): Moment; - (date: string, format?: string, language?: string, strict?: boolean): Moment; - (date: string, formats: string[], strict?: boolean): Moment; - (date: string, formats: string[], language?: string, strict?: boolean): Moment; - (date: string, specialFormat: () => void, strict?: boolean): Moment; - (date: string, specialFormat: () => void, language?: string, strict?: boolean): Moment; - (date: string, formatsIncludingSpecial: any[], strict?: boolean): Moment; - (date: string, formatsIncludingSpecial: any[], language?: string, strict?: boolean): Moment; - (date: Date): Moment; - (date: Moment): Moment; - (date: Object): Moment; - - utc(): Moment; - utc(date: number): Moment; - utc(date: number[]): Moment; - utc(date: string, format?: string, strict?: boolean): Moment; - utc(date: string, format?: string, language?: string, strict?: boolean): Moment; - utc(date: string, formats: string[], strict?: boolean): Moment; - utc(date: string, formats: string[], language?: string, strict?: boolean): Moment; - utc(date: Date): Moment; - utc(date: Moment): Moment; - utc(date: Object): Moment; - - unix(timestamp: number): Moment; - - invalid(parsingFlags?: Object): Moment; - isMoment(): boolean; - isMoment(m: any): boolean; - isDuration(): boolean; - isDuration(d: any): boolean; - - // Deprecated in 2.8.0. - lang(language?: string): string; - lang(language?: string, definition?: MomentLanguage): string; - - locale(language?: string): string; - locale(language?: string[]): string; - locale(language?: string, definition?: MomentLanguage): string; - - localeData(language?: string): MomentLanguageData; - - longDateFormat: any; - relativeTime: any; - meridiem: (hour: number, minute: number, isLowercase: boolean) => string; - calendar: any; - ordinal: (num: number) => string; - - duration(milliseconds: Number): Duration; - duration(num: Number, unitOfTime: string): Duration; - duration(input: MomentInput): Duration; - duration(object: any): Duration; - duration(): Duration; - - parseZone(date: string): Moment; - - months(): string[]; - months(index: number): string; - months(format: string): string[]; - months(format: string, index: number): string; - monthsShort(): string[]; - monthsShort(index: number): string; - monthsShort(format: string): string[]; - monthsShort(format: string, index: number): string; - - weekdays(): string[]; - weekdays(index: number): string; - weekdays(format: string): string[]; - weekdays(format: string, index: number): string; - weekdaysShort(): string[]; - weekdaysShort(index: number): string; - weekdaysShort(format: string): string[]; - weekdaysShort(format: string, index: number): string; - weekdaysMin(): string[]; - weekdaysMin(index: number): string; - weekdaysMin(format: string): string[]; - weekdaysMin(format: string, index: number): string; - - min(moments: Moment[]): Moment; - max(moments: Moment[]): Moment; - - normalizeUnits(unit: string): string; - relativeTimeThreshold(threshold: string): number|boolean; - relativeTimeThreshold(threshold: string, limit:number): boolean; - - /** - * Constant used to enable explicit ISO_8601 format parsing. - */ - ISO_8601(): void; - - } - -} - -declare module 'moment' { - var moment: moment.MomentStatic; - export = moment; -} diff --git a/typings/moment/moment.d.ts b/typings/moment/moment.d.ts deleted file mode 100644 index 736956e..0000000 --- a/typings/moment/moment.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for Moment.js 2.8.0 -// Project: https://github.com/timrwood/moment -// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink , Adi Dahiya -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare var moment: moment.MomentStatic; diff --git a/typings/sinon-chai/sinon-chai.d.ts b/typings/sinon-chai/sinon-chai.d.ts deleted file mode 100644 index 03bd0e8..0000000 --- a/typings/sinon-chai/sinon-chai.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -// Type definitions for sinon-chai 2.7.0 -// Project: https://github.com/domenic/sinon-chai -// Definitions by: Kazi Manzur Rashid , Jed Mao -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module Chai { - - interface LanguageChains { - always: Assertion; - } - - interface Assertion { - /** - * true if the spy was called at least once. - */ - called: Assertion; - /** - * @param count The number of recorded calls. - */ - callCount(count: number): Assertion; - /** - * true if the spy was called exactly once. - */ - calledOnce: Assertion; - /** - * true if the spy was called exactly twice. - */ - calledTwice: Assertion; - /** - * true if the spy was called exactly thrice. - */ - calledThrice: Assertion; - /** - * Returns true if the spy was called before anotherSpy. - */ - calledBefore(anotherSpy: Sinon.SinonSpy): Assertion; - /** - * Returns true if the spy was called after anotherSpy. - */ - calledAfter(anotherSpy: Sinon.SinonSpy): Assertion; - /** - * Returns true if spy/stub was called with the new operator. Beware that - * this is inferred based on the value of the this object and the spy - * function's prototype, so it may give false positives if you actively - * return the right kind of object. - */ - calledWithNew: Assertion; - /** - * Returns true if context was this for this call. - */ - calledOn(context: any): Assertion; - /** - * Returns true if call received provided arguments (and possibly others). - */ - calledWith(...args: any[]): Assertion; - /** - * Returns true if call received provided arguments and no others. - */ - calledWithExactly(...args: any[]): Assertion; - /** - * Returns true if call received matching arguments (and possibly others). - * This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...). - */ - calledWithMatch(...args: any[]): Assertion; - /** - * Returns true if spy returned the provided value at least once. Uses - * deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) - * for strict comparison (see matchers). - */ - returned(obj: any): Assertion; - /** - * Returns true if spy threw the provided exception object at least once. - */ - thrown(obj?: Error|typeof Error|string): Assertion; - } -} - -declare module "sinon-chai" { - function sinonChai(chai: any, utils: any): void; - export = sinonChai; -} diff --git a/typings/sinon/sinon.d.ts b/typings/sinon/sinon.d.ts deleted file mode 100644 index 6440dda..0000000 --- a/typings/sinon/sinon.d.ts +++ /dev/null @@ -1,420 +0,0 @@ -// Type definitions for Sinon 1.8.1 -// Project: http://sinonjs.org/ -// Definitions by: William Sears -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module Sinon { - interface SinonSpyCallApi { - // Properties - thisValue: any; - args: any[]; - exception: any; - returnValue: any; - - // Methods - calledOn(obj: any): boolean; - calledWith(...args: any[]): boolean; - calledWithExactly(...args: any[]): boolean; - calledWithMatch(...args: any[]): boolean; - notCalledWith(...args: any[]): boolean; - notCalledWithMatch(...args: any[]): boolean; - returned(value: any): boolean; - threw(): boolean; - threw(type: string): boolean; - threw(obj: any): boolean; - callArg(pos: number): void; - callArgOn(pos: number, obj: any, ...args: any[]): void; - callArgWith(pos: number, ...args: any[]): void; - callArgOnWith(pos: number, obj: any, ...args: any[]): void; - yield(...args: any[]): void; - yieldOn(obj: any, ...args: any[]): void; - yieldTo(property: string, ...args: any[]): void; - yieldToOn(property: string, obj: any, ...args: any[]): void; - } - - interface SinonSpyCall extends SinonSpyCallApi { - calledBefore(call: SinonSpyCall): boolean; - calledAfter(call: SinonSpyCall): boolean; - calledWithNew(call: SinonSpyCall): boolean; - } - - interface SinonSpy extends SinonSpyCallApi { - // Properties - callCount: number; - called: boolean; - notCalled: boolean; - calledOnce: boolean; - calledTwice: boolean; - calledThrice: boolean; - firstCall: SinonSpyCall; - secondCall: SinonSpyCall; - thirdCall: SinonSpyCall; - lastCall: SinonSpyCall; - thisValues: any[]; - args: any[][]; - exceptions: any[]; - returnValues: any[]; - - // Methods - (...args: any[]): any; - calledBefore(anotherSpy: SinonSpy): boolean; - calledAfter(anotherSpy: SinonSpy): boolean; - calledWithNew(spy: SinonSpy): boolean; - withArgs(...args: any[]): SinonSpy; - alwaysCalledOn(obj: any): boolean; - alwaysCalledWith(...args: any[]): boolean; - alwaysCalledWithExactly(...args: any[]): boolean; - alwaysCalledWithMatch(...args: any[]): boolean; - neverCalledWith(...args: any[]): boolean; - neverCalledWithMatch(...args: any[]): boolean; - alwaysThrew(): boolean; - alwaysThrew(type: string): boolean; - alwaysThrew(obj: any): boolean; - alwaysReturned(): boolean; - invokeCallback(...args: any[]): void; - getCall(n: number): SinonSpyCall; - reset(): void; - printf(format: string, ...args: any[]): string; - restore(): void; - } - - interface SinonSpyStatic { - (): SinonSpy; - (func: any): SinonSpy; - (obj: any, method: string): SinonSpy; - } - - interface SinonStatic { - spy: SinonSpyStatic; - } - - interface SinonStub extends SinonSpy { - resetBehavior(): void; - returns(obj: any): SinonStub; - returnsArg(index: number): SinonStub; - throws(type?: string): SinonStub; - throws(obj: any): SinonStub; - callsArg(index: number): SinonStub; - callsArgOn(index: number, context: any): SinonStub; - callsArgWith(index: number, ...args: any[]): SinonStub; - callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; - callsArgAsync(index: number): SinonStub; - callsArgOnAsync(index: number, context: any): SinonStub; - callsArgWithAsync(index: number, ...args: any[]): SinonStub; - callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; - onCall(n: number): SinonStub; - onFirstCall(): SinonStub; - onSecondCall(): SinonStub; - onThirdCall(): SinonStub; - yields(...args: any[]): SinonStub; - yieldsOn(context: any, ...args: any[]): SinonStub; - yieldsTo(property: string, ...args: any[]): SinonStub; - yieldsToOn(property: string, context: any, ...args: any[]): SinonStub; - yieldsAsync(...args: any[]): SinonStub; - yieldsOnAsync(context: any, ...args: any[]): SinonStub; - yieldsToAsync(property: string, ...args: any[]): SinonStub; - yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; - withArgs(...args: any[]): SinonStub; - } - - interface SinonStubStatic { - (): SinonStub; - (obj: any): SinonStub; - (obj: any, method: string): SinonStub; - (obj: any, method: string, func: any): SinonStub; - } - - interface SinonStatic { - stub: SinonStubStatic; - } - - interface SinonExpectation extends SinonStub { - atLeast(n: number): SinonExpectation; - atMost(n: number): SinonExpectation; - never(): SinonExpectation; - once(): SinonExpectation; - twice(): SinonExpectation; - thrice(): SinonExpectation; - exactly(n: number): SinonExpectation; - withArgs(...args: any[]): SinonExpectation; - withExactArgs(...args: any[]): SinonExpectation; - on(obj: any): SinonExpectation; - verify(): SinonExpectation; - restore(): void; - } - - interface SinonExpectationStatic { - create(methodName?: string): SinonExpectation; - } - - interface SinonMock { - expects(method: string): SinonExpectation; - restore(): void; - verify(): void; - } - - interface SinonMockStatic { - (): SinonExpectation; - (obj: any): SinonMock; - } - - interface SinonStatic { - expectation: SinonExpectationStatic; - mock: SinonMockStatic; - } - - interface SinonFakeTimers { - now: number; - create(now: number): SinonFakeTimers; - setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; - clearTimeout(id: number): void; - setInterval(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; - clearInterval(id: number): void; - tick(ms: number): number; - reset(): void; - Date(): Date; - Date(year: number): Date; - Date(year: number, month: number): Date; - Date(year: number, month: number, day: number): Date; - Date(year: number, month: number, day: number, hour: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; - restore(): void; - } - - interface SinonFakeTimersStatic { - (): SinonFakeTimers; - (...timers: string[]): SinonFakeTimers; - (now: number, ...timers: string[]): SinonFakeTimers; - } - - interface SinonStatic { - useFakeTimers: SinonFakeTimersStatic; - clock: SinonFakeTimers; - } - - interface SinonFakeUploadProgress { - eventListeners: { - progress: any[]; - load: any[]; - abort: any[]; - error: any[]; - }; - - addEventListener(event: string, listener: (e: Event) => any): void; - removeEventListener(event: string, listener: (e: Event) => any): void; - dispatchEvent(event: Event): void; - } - - interface SinonFakeXMLHttpRequest { - // Properties - onCreate: (xhr: SinonFakeXMLHttpRequest) => void; - url: string; - method: string; - requestHeaders: any; - requestBody: string; - status: number; - statusText: string; - async: boolean; - username: string; - password: string; - withCredentials: boolean; - upload: SinonFakeUploadProgress; - responseXML: Document; - getResponseHeader(header: string): string; - getAllResponseHeaders(): any; - - // Methods - restore(): void; - useFilters: boolean; - addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; - setResponseHeaders(headers: any): void; - setResponseBody(body: string): void; - respond(status: number, headers: any, body: string): void; - autoRespond(ms: number): void; - } - - interface SinonFakeXMLHttpRequestStatic { - (): SinonFakeXMLHttpRequest; - } - - interface SinonStatic { - useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; - FakeXMLHttpRequest: SinonFakeXMLHttpRequest; - } - - interface SinonFakeServer { - // Properties - autoRespond: boolean; - autoRespondAfter: number; - fakeHTTPMethods: boolean; - getHTTPMethod: (request: SinonFakeXMLHttpRequest) => string; - requests: SinonFakeXMLHttpRequest[]; - - // Methods - respondWith(body: string): void; - respondWith(response: any[]): void; - respondWith(fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(url: string, body: string): void; - respondWith(url: string, response: any[]): void; - respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(method: string, url: string, body: string): void; - respondWith(method: string, url: string, response: any[]): void; - respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(url: RegExp, body: string): void; - respondWith(url: RegExp, response: any[]): void; - respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(method: string, url: RegExp, body: string): void; - respondWith(method: string, url: RegExp, response: any[]): void; - respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respond(): void; - restore(): void; - } - - interface SinonFakeServerStatic { - create(): SinonFakeServer; - } - - interface SinonStatic { - fakeServer: SinonFakeServerStatic; - fakeServerWithClock: SinonFakeServerStatic; - } - - interface SinonExposeOptions { - prefix?: string; - includeFail?: boolean; - } - - interface SinonAssert { - // Properties - failException: string; - fail: (message?: string) => void; // Overridable - pass: (assertion: any) => void; // Overridable - - // Methods - notCalled(spy: SinonSpy): void; - called(spy: SinonSpy): void; - calledOnce(spy: SinonSpy): void; - calledTwice(spy: SinonSpy): void; - calledThrice(spy: SinonSpy): void; - callCount(spy: SinonSpy, count: number): void; - callOrder(...spies: SinonSpy[]): void; - calledOn(spy: SinonSpy, obj: any): void; - alwaysCalledOn(spy: SinonSpy, obj: any): void; - calledWith(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; - neverCalledWith(spy: SinonSpy, ...args: any[]): void; - calledWithExactly(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; - calledWithMatch(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWithMatch(spy: SinonSpy, ...args: any[]): void; - neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; - threw(spy: SinonSpy): void; - threw(spy: SinonSpy, exception: string): void; - threw(spy: SinonSpy, exception: any): void; - alwaysThrew(spy: SinonSpy): void; - alwaysThrew(spy: SinonSpy, exception: string): void; - alwaysThrew(spy: SinonSpy, exception: any): void; - expose(obj: any, options?: SinonExposeOptions): void; - } - - interface SinonStatic { - assert: SinonAssert; - } - - interface SinonMatcher { - and(expr: SinonMatcher): SinonMatcher; - or(expr: SinonMatcher): SinonMatcher; - } - - interface SinonMatch { - (value: number): SinonMatcher; - (value: string): SinonMatcher; - (expr: RegExp): SinonMatcher; - (obj: any): SinonMatcher; - (callback: (value: any) => boolean): SinonMatcher; - any: SinonMatcher; - defined: SinonMatcher; - truthy: SinonMatcher; - falsy: SinonMatcher; - bool: SinonMatcher; - number: SinonMatcher; - string: SinonMatcher; - object: SinonMatcher; - func: SinonMatcher; - array: SinonMatcher; - regexp: SinonMatcher; - date: SinonMatcher; - same(obj: any): SinonMatcher; - typeOf(type: string): SinonMatcher; - instanceOf(type: any): SinonMatcher; - has(property: string, expect?: any): SinonMatcher; - hasOwn(property: string, expect?: any): SinonMatcher; - } - - interface SinonStatic { - match: SinonMatch; - } - - interface SinonSandboxConfig { - injectInto?: any; - properties?: string[]; - useFakeTimers?: any; - useFakeServer?: any; - } - - interface SinonSandbox { - clock: SinonFakeTimers; - requests: SinonFakeXMLHttpRequest; - server: SinonFakeServer; - spy: SinonSpyStatic; - stub: SinonStubStatic; - mock: SinonMockStatic; - useFakeTimers: SinonFakeTimersStatic; - useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; - useFakeServer(): SinonFakeServer; - restore(): void; - } - - interface SinonSandboxStatic { - create(): SinonSandbox; - create(config: SinonSandboxConfig): SinonSandbox; - } - - interface SinonStatic { - sandbox: SinonSandboxStatic; - } - - interface SinonTestConfig { - injectIntoThis?: boolean; - injectInto?: any; - properties?: string[]; - useFakeTimers?: boolean; - useFakeServer?: boolean; - } - - interface SinonTestWrapper extends SinonSandbox { - (...args: any[]): any; - } - - interface SinonStatic { - config: SinonTestConfig; - test(fn: (...args: any[]) => any): SinonTestWrapper; - testCase(tests: any): any; - } - - // Utility overridables - interface SinonStatic { - createStubInstance(constructor: any): SinonStub; - format(obj: any): string; - log(message: string): void; - restore(object: any): void; - } -} - -declare var sinon: Sinon.SinonStatic; - -declare module "sinon" { - export = sinon; -} diff --git a/typings/tsd.d.ts b/typings/tsd.d.ts deleted file mode 100644 index f9e15c7..0000000 --- a/typings/tsd.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// From 6692938a8b9aa3ace778cec635a6848483ea8bda Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Tue, 5 Apr 2016 22:18:49 +0100 Subject: [PATCH 02/13] Refactoered to use webpack for unit testing, started working through fixing unit tests --- dist/index.d.ts | 1 - dist/index.js | 11 - dist/index.js.map | 1 - dist/ngJwtAuthInterceptor.d.ts | 16 - dist/ngJwtAuthInterceptor.js | 46 -- dist/ngJwtAuthInterceptor.js.map | 1 - dist/ngJwtAuthInterfaces.d.ts | 63 --- dist/ngJwtAuthInterfaces.js | 2 - dist/ngJwtAuthInterfaces.js.map | 1 - dist/ngJwtAuthService.d.ts | 257 ---------- dist/ngJwtAuthService.js | 549 --------------------- dist/ngJwtAuthService.js.map | 1 - dist/ngJwtAuthServiceProvider.d.ts | 31 -- dist/ngJwtAuthServiceProvider.js | 84 ---- dist/ngJwtAuthServiceProvider.js.map | 1 - karma.conf.js | 44 +- package.json | 37 +- src/index.ts | 6 +- test/test.spec.ts => src/ngJwtAuth.spec.ts | 12 +- src/test.ts | 7 + tsconfig.build.json => tsconfig.json | 3 +- tsconfig.test.json | 21 - webpack/loaders.js | 29 ++ webpack/webpack.test.js | 27 + 24 files changed, 133 insertions(+), 1118 deletions(-) delete mode 100644 dist/index.d.ts delete mode 100644 dist/index.js delete mode 100644 dist/index.js.map delete mode 100644 dist/ngJwtAuthInterceptor.d.ts delete mode 100644 dist/ngJwtAuthInterceptor.js delete mode 100644 dist/ngJwtAuthInterceptor.js.map delete mode 100644 dist/ngJwtAuthInterfaces.d.ts delete mode 100644 dist/ngJwtAuthInterfaces.js delete mode 100644 dist/ngJwtAuthInterfaces.js.map delete mode 100644 dist/ngJwtAuthService.d.ts delete mode 100644 dist/ngJwtAuthService.js delete mode 100644 dist/ngJwtAuthService.js.map delete mode 100644 dist/ngJwtAuthServiceProvider.d.ts delete mode 100644 dist/ngJwtAuthServiceProvider.js delete mode 100644 dist/ngJwtAuthServiceProvider.js.map rename test/test.spec.ts => src/ngJwtAuth.spec.ts (99%) create mode 100644 src/test.ts rename tsconfig.build.json => tsconfig.json (92%) delete mode 100644 tsconfig.test.json create mode 100644 webpack/loaders.js create mode 100644 webpack/webpack.test.js diff --git a/dist/index.d.ts b/dist/index.d.ts deleted file mode 100644 index 51cabd3..0000000 --- a/dist/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -import "angular"; diff --git a/dist/index.js b/dist/index.js deleted file mode 100644 index 0cbd007..0000000 --- a/dist/index.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -require("angular"); -var ngJwtAuthServiceProvider_1 = require("./ngJwtAuthServiceProvider"); -var ngJwtAuthInterceptor_1 = require("./ngJwtAuthInterceptor"); -angular.module('ngJwtAuth', ['ab-base64', 'ngCookies']) - .provider('ngJwtAuthService', ngJwtAuthServiceProvider_1.NgJwtAuthServiceProvider) - .service('ngJwtAuthInterceptor', ngJwtAuthInterceptor_1.NgJwtAuthInterceptor) - .config(['$httpProvider', '$injector', function ($httpProvider) { - $httpProvider.interceptors.push('ngJwtAuthInterceptor'); - }]); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map deleted file mode 100644 index b13e715..0000000 --- a/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,QAAO,SAAS,CAAC,CAAA;AACjB,yCAAuC,4BAA4B,CAAC,CAAA;AACpE,qCAAmC,wBAAwB,CAAC,CAAA;AAG5D,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;KAClD,QAAQ,CAAC,kBAAkB,EAAE,mDAAwB,CAAC;KACtD,OAAO,CAAC,sBAAsB,EAAE,2CAAoB,CAAC;KACrD,MAAM,CAAC,CAAC,eAAe,EAAE,WAAW,EAAE,UAAC,aAA8B;QAElE,aAAa,CAAC,YAAY,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC,CACN"} \ No newline at end of file diff --git a/dist/ngJwtAuthInterceptor.d.ts b/dist/ngJwtAuthInterceptor.d.ts deleted file mode 100644 index 6723681..0000000 --- a/dist/ngJwtAuthInterceptor.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -export declare class NgJwtAuthInterceptor { - private $http; - private $q; - private $injector; - private ngJwtAuthService; - /** - * Construct the service with dependencies injected - * @param _$q - * @param _$injector - */ - static $inject: string[]; - constructor(_$q: ng.IQService, _$injector: ng.auto.IInjectorService); - private getNgJwtAuthService; - response: (response: ng.IHttpPromiseCallbackArg) => ng.IHttpPromiseCallbackArg; - responseError: (rejection: any) => any; -} diff --git a/dist/ngJwtAuthInterceptor.js b/dist/ngJwtAuthInterceptor.js deleted file mode 100644 index 5a49385..0000000 --- a/dist/ngJwtAuthInterceptor.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -var NgJwtAuthInterceptor = (function () { - function NgJwtAuthInterceptor(_$q, _$injector) { - var _this = this; - this.getNgJwtAuthService = function () { - if (_this.ngJwtAuthService == null) { - _this.ngJwtAuthService = _this.$injector.get('ngJwtAuthService'); - } - return _this.ngJwtAuthService; - }; - this.response = function (response) { - var updateHeader = response.headers('Authorization-Update'); - if (updateHeader) { - var newToken = updateHeader.replace('Bearer ', ''); - var ngJwtAuthService = _this.getNgJwtAuthService(); - if (!ngJwtAuthService.validateToken(newToken)) { - return response; //if it is not a valid JWT, just return the response as it might be some other kind of token that is being updated. - } - ngJwtAuthService.processNewToken(newToken); - } - return response; - }; - this.responseError = function (rejection) { - var ngJwtAuthService = _this.getNgJwtAuthService(); - //if the response is on a login method, reject immediately - if (ngJwtAuthService.isLoginMethod(rejection.config.url)) { - return _this.$q.reject(rejection); - } - if (401 === rejection.status) { - return ngJwtAuthService.handleInterceptedUnauthorisedResponse(rejection); - } - return _this.$q.reject(rejection); - }; - this.$q = _$q; - this.$injector = _$injector; - } - /** - * Construct the service with dependencies injected - * @param _$q - * @param _$injector - */ - NgJwtAuthInterceptor.$inject = ['$q', '$injector']; - return NgJwtAuthInterceptor; -}()); -exports.NgJwtAuthInterceptor = NgJwtAuthInterceptor; -//# sourceMappingURL=ngJwtAuthInterceptor.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthInterceptor.js.map b/dist/ngJwtAuthInterceptor.js.map deleted file mode 100644 index 7d1d774..0000000 --- a/dist/ngJwtAuthInterceptor.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ngJwtAuthInterceptor.js","sourceRoot":"","sources":["../src/ngJwtAuthInterceptor.ts"],"names":[],"mappings":";AAIA;IAeI,8BAAY,GAAgB,EAAE,UAAmC;QAfrE,iBAkEC;QA7CW,wBAAmB,GAAG;YAC1B,EAAE,CAAC,CAAC,KAAI,CAAC,gBAAgB,IAAI,IAAI,CAAC,CAAC,CAAC;gBAChC,KAAI,CAAC,gBAAgB,GAAqB,KAAI,CAAC,SAAS,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;YACrF,CAAC;YACD,MAAM,CAAC,KAAI,CAAC,gBAAgB,CAAC;QACjC,CAAC,CAAC;QAEK,aAAQ,GAAG,UAAC,QAAwC;YAEvD,IAAI,YAAY,GAAG,QAAQ,CAAC,OAAO,CAAC,sBAAsB,CAAC,CAAC;YAE5D,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;gBAEf,IAAI,QAAQ,GAAG,YAAY,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;gBAEnD,IAAI,gBAAgB,GAAG,KAAI,CAAC,mBAAmB,EAAE,CAAC;gBAElD,EAAE,CAAC,CAAC,CAAC,gBAAgB,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;oBAC5C,MAAM,CAAC,QAAQ,CAAC,CAAC,mHAAmH;gBACxI,CAAC;gBAED,gBAAgB,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;YAC/C,CAAC;YAED,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC,CAAC;QAEK,kBAAa,GAAG,UAAC,SAAS;YAE7B,IAAI,gBAAgB,GAAG,KAAI,CAAC,mBAAmB,EAAE,CAAC;YAElD,0DAA0D;YAC1D,EAAE,CAAC,CAAC,gBAAgB,CAAC,aAAa,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gBAEvD,MAAM,CAAC,KAAI,CAAC,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;YACrC,CAAC;YAED,EAAE,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;gBAE3B,MAAM,CAAC,gBAAgB,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC;YAC7E,CAAC;YAED,MAAM,CAAC,KAAI,CAAC,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACrC,CAAC,CAAA;QA/CG,IAAI,CAAC,EAAE,GAAG,GAAG,CAAC;QACd,IAAI,CAAC,SAAS,GAAG,UAAU,CAAC;IAChC,CAAC;IAXD;;;;OAIG;IACI,4BAAO,GAAG,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAqDzC,2BAAC;AAAD,CAAC,AAlED,IAkEC;AAlEY,4BAAoB,uBAkEhC,CAAA"} \ No newline at end of file diff --git a/dist/ngJwtAuthInterfaces.d.ts b/dist/ngJwtAuthInterfaces.d.ts deleted file mode 100644 index e71e939..0000000 --- a/dist/ngJwtAuthInterfaces.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -export interface IEndpointDefinition { - base?: string; - login?: string; - loginAsUser?: string; - tokenExchange?: string; - refresh?: string; -} -export interface ICookieConfig { - enabled: boolean; - name?: string; - topLevelDomain?: boolean; -} -export interface INgJwtAuthServiceConfig { - tokenLocation?: string; - tokenUser?: string; - apiEndpoints?: IEndpointDefinition; - storageKeyName?: string; - refreshBeforeSeconds?: number; - checkExpiryEverySeconds?: number; - cookie?: ICookieConfig; -} -export interface IJwtClaims { - iss: string; - aud: string; - sub: string; - nbf?: number; - iat: number; - exp: number; - jti: string; -} -export interface IJwtToken { - header: { - alg: string; - typ: string; - }; - data: IJwtClaims; - signature: string; -} -export interface IUser { - userId: any; - email: string; - firstName?: string; - lastName?: string; -} -export interface ICredentials { - username: string; - password: string; -} -export interface ILoginPromptFactory { - (deferredCredentials: ng.IDeferred, loginSuccessPromise: ng.IPromise, currentUser: IUser): ng.IPromise; -} -export interface IUserFactory { - (subClaim: string, tokenData: IJwtClaims): ng.IPromise; -} -export interface IUserEventListener { - (user: IUser): void; -} -export interface IBase64Service { - encode(string: string): string; - decode(string: string): string; - urldecode(string: string): string; - urldecode(string: string): string; -} diff --git a/dist/ngJwtAuthInterfaces.js b/dist/ngJwtAuthInterfaces.js deleted file mode 100644 index d8b9c48..0000000 --- a/dist/ngJwtAuthInterfaces.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=ngJwtAuthInterfaces.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthInterfaces.js.map b/dist/ngJwtAuthInterfaces.js.map deleted file mode 100644 index 82a8ada..0000000 --- a/dist/ngJwtAuthInterfaces.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ngJwtAuthInterfaces.js","sourceRoot":"","sources":["../src/ngJwtAuthInterfaces.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/ngJwtAuthService.d.ts b/dist/ngJwtAuthService.d.ts deleted file mode 100644 index 087aff8..0000000 --- a/dist/ngJwtAuthService.d.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { IUserFactory, ILoginPromptFactory, IUserEventListener, IUser, INgJwtAuthServiceConfig, IBase64Service } from "./ngJwtAuthInterfaces"; -export declare class NgJwtAuthService { - private config; - private $http; - private $q; - private $window; - private $interval; - private base64Service; - private $cookies; - private $location; - private userFactory; - private loginPromptFactory; - private loginListeners; - private logoutListeners; - private userLoggedInPromise; - private refreshTimerPromise; - private tokenData; - user: IUser; - loggedIn: boolean; - rawToken: string; - /** - * Construct the service with dependencies injected - * @param config - * @param $http - * @param $q - * @param $window - * @param $interval - * @param base64Service - * @param $cookies - * @param $location - */ - constructor(config: INgJwtAuthServiceConfig, $http: ng.IHttpService, $q: ng.IQService, $window: ng.IWindowService, $interval: ng.IIntervalService, base64Service: IBase64Service, $cookies: ng.cookies.ICookiesService, $location: ng.ILocationService); - /** - * Get the current configuration - * @returns {INgJwtAuthServiceConfig} - */ - getConfig(): INgJwtAuthServiceConfig; - /** - * A default implementation of the user factory if the client does not provide one - */ - private defaultUserFactory(subClaim, tokenData); - /** - * Service needs an init function so runtime configuration can occur before - * bootstrapping the service. This allows the user supplied LoginPromptFactory - * to be registered - */ - init(): ng.IPromise; - /** - * Register the refresh timer - */ - private startRefreshTimer(); - /** - * Cancel the refresh timer - */ - private cancelRefreshTimer(); - /** - * Handle token refresh timer - */ - private tickRefreshTime; - /** - * Check if the token needs to refresh now - * @returns {boolean} - */ - private tokenNeedsToRefreshNow(); - /** - * Get the endpoint for login - * @returns {string} - */ - private getLoginEndpoint(); - /** - * Get the endpoint for exchanging a token - * @returns {string} - */ - private getTokenExchangeEndpoint(); - /** - * Get the endpoint for getting a user's token (impersonation) - * @returns {string} - */ - private getLoginAsUserEndpoint(userIdentifier); - /** - * Get the endpoint for refreshing a token - * @returns {string} - */ - private getRefreshEndpoint(); - /** - * Build a authentication basic header string - * @param username - * @param password - * @returns {string} - */ - private static getAuthHeader(username, password); - /** - * Build a token header string - * @returns {string} - */ - private static getTokenHeader(token); - /** - * Get the standard header for a jwt token request - * @returns {string} - */ - private getBearerHeader(); - /** - * Build a refresh header string - * @returns {string} - */ - private getRefreshHeader(); - /** - * Retrieve the token from the remote API - * @param endpoint - * @param authHeader - * @returns {IPromise} - */ - private retrieveAndProcessToken(endpoint, authHeader); - /** - * Parse the raw token - * @param rawToken - * @returns {IJwtToken} - */ - private readToken(rawToken); - /** - * Validate JWT Token - * @param rawToken - * @returns {any} - */ - validateToken(rawToken: string): boolean; - /** - * Prompt user for their login credentials, and attempt to login - * @returns {ng.IPromise} - */ - promptLogin(): angular.IPromise; - /** - * Read and save the raw token to storage, kick off timer to attempt refresh - * @param rawToken - * @returns {IUser} - */ - processNewToken(rawToken: string): ng.IPromise; - private loadTokenFromStorage(); - /** - * Check if the endpoint is a login method (used for skipping the authentication error interceptor) - * @param url - * @returns {boolean} - */ - isLoginMethod(url: string): boolean; - getUser(): IUser; - /** - * - * @returns {IHttpPromise} - */ - getPromisedUser(): ng.IPromise; - /** - * Clear the token - */ - private clearJWTToken(); - /** - * Attempt to log in with username and password - * @param username - * @param password - * @returns {IPromise} - */ - authenticateCredentials(username: string, password: string): ng.IPromise; - /** - * Exchange an arbitrary token with a jwt token - * @param token - * @returns {ng.IPromise} - */ - exchangeToken(token: string): ng.IPromise; - /** - * Refresh an existing token - * @returns {ng.IPromise} - */ - refreshToken(): ng.IPromise; - /** - * Require that the user logs in again for a request - * 1. Check if there is already credentials promised - * 2. If not, execute the credential promise factory - * 3. Wait until the credentials are resolved - * 4. Then try to authenticateCredentials - * @returns {IPromise} - */ - requireCredentialsAndAuthenticate(): ng.IPromise; - /** - * Handle the login event - * @param user - */ - private handleLogin(user); - /** - * Find the user object within the path - * @param tokenData - * @returns {T} - */ - private getUserFromTokenData(tokenData); - /** - * Save the token - * @param rawToken - * @param tokenData - */ - private saveTokenToStorage(rawToken, tokenData); - /** - * Save to cookie - * @param rawToken - * @param tokenData - */ - private saveCookie(rawToken, tokenData); - /** - * Set the authentication token for all new requests - * @param rawToken - */ - private setJWTHeader(rawToken); - /** - * Remove the default http authorization header - */ - private unsetJWTHeader(); - /** - * Handle a request that was rejected due to unauthorised response - * 1. Require authentication - * 2. Retry the rejected $http request - * - * @param rejection - */ - handleInterceptedUnauthorisedResponse(rejection: ng.IHttpPromiseCallbackArg): ng.IPromise>; - /** - * Register the login prompt factory - * @param loginPromptFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - registerLoginPromptFactory(loginPromptFactory: ILoginPromptFactory): NgJwtAuthService; - /** - * Register the user factory for extracting a user from data - * @param userFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - registerUserFactory(userFactory: IUserFactory): NgJwtAuthService; - /** - * Clear the token and service properties - */ - logout(): void; - /** - * Register a login listener function - * @param loginListener - */ - registerLoginListener(loginListener: IUserEventListener): void; - /** - * Register a logout listener function - * @param logoutListener - */ - registerLogoutListener(logoutListener: IUserEventListener): void; - /** - * Get a user's token given their identifier - * @param userIdentifier - * @returns {ng.IPromise} - * - * Note this feature should be implemented very carefully as it is a security risk as it means users - * can log in as other users (impersonation). The responsibility is on the implementing app to strongly - * control permissions to access this endpoint to avoid security risks - */ - loginAsUser(userIdentifier: string | number): ng.IPromise; -} diff --git a/dist/ngJwtAuthService.js b/dist/ngJwtAuthService.js deleted file mode 100644 index 24c56c6..0000000 --- a/dist/ngJwtAuthService.js +++ /dev/null @@ -1,549 +0,0 @@ -"use strict"; -var moment = require("moment"); -var _ = require("lodash"); -var ngJwtAuthServiceProvider_1 = require("./ngJwtAuthServiceProvider"); -var NgJwtAuthService = (function () { - /** - * Construct the service with dependencies injected - * @param config - * @param $http - * @param $q - * @param $window - * @param $interval - * @param base64Service - * @param $cookies - * @param $location - */ - function NgJwtAuthService(config, $http, $q, $window, $interval, base64Service, $cookies, $location) { - var _this = this; - this.config = config; - this.$http = $http; - this.$q = $q; - this.$window = $window; - this.$interval = $interval; - this.base64Service = base64Service; - this.$cookies = $cookies; - this.$location = $location; - this.loginListeners = []; - this.logoutListeners = []; - this.loggedIn = false; - /** - * Handle token refresh timer - */ - this.tickRefreshTime = function () { - if (!_this.userLoggedInPromise && _this.tokenNeedsToRefreshNow()) { - _this.refreshToken(); - } - }; - this.userFactory = this.defaultUserFactory; - } - /** - * Get the current configuration - * @returns {INgJwtAuthServiceConfig} - */ - NgJwtAuthService.prototype.getConfig = function () { - return this.config; - }; - /** - * A default implementation of the user factory if the client does not provide one - */ - NgJwtAuthService.prototype.defaultUserFactory = function (subClaim, tokenData) { - return this.$q.when(_.get(tokenData, this.config.tokenUser)); - }; - /** - * Service needs an init function so runtime configuration can occur before - * bootstrapping the service. This allows the user supplied LoginPromptFactory - * to be registered - */ - NgJwtAuthService.prototype.init = function () { - var _this = this; - //attempt to load the token from storage - return this.loadTokenFromStorage() - .then(function () { - _this.startRefreshTimer(); - return true; - }); - }; - /** - * Register the refresh timer - */ - NgJwtAuthService.prototype.startRefreshTimer = function () { - //if the timer is already set, clear it so the timing is reset - if (!!this.refreshTimerPromise) { - this.cancelRefreshTimer(); - } - this.refreshTimerPromise = this.$interval(this.tickRefreshTime, this.config.checkExpiryEverySeconds * 1000, null, false); - }; - /** - * Cancel the refresh timer - */ - NgJwtAuthService.prototype.cancelRefreshTimer = function () { - this.$interval.cancel(this.refreshTimerPromise); - this.refreshTimerPromise = null; - }; - /** - * Check if the token needs to refresh now - * @returns {boolean} - */ - NgJwtAuthService.prototype.tokenNeedsToRefreshNow = function () { - if (!this.rawToken) { - return false; //cant refresh if there isn't a token - } - var latestRefresh = moment(this.tokenData.data.exp * 1000).subtract(this.config.refreshBeforeSeconds, 'seconds'), nextRefreshOpportunity = moment().add(this.config.checkExpiryEverySeconds); - //needs to refresh if the the next time we could refresh is after the configured refresh before date - return (latestRefresh <= nextRefreshOpportunity); - }; - /** - * Get the endpoint for login - * @returns {string} - */ - NgJwtAuthService.prototype.getLoginEndpoint = function () { - return this.config.apiEndpoints.base + this.config.apiEndpoints.login; - }; - /** - * Get the endpoint for exchanging a token - * @returns {string} - */ - NgJwtAuthService.prototype.getTokenExchangeEndpoint = function () { - return this.config.apiEndpoints.base + this.config.apiEndpoints.tokenExchange; - }; - /** - * Get the endpoint for getting a user's token (impersonation) - * @returns {string} - */ - NgJwtAuthService.prototype.getLoginAsUserEndpoint = function (userIdentifier) { - return this.config.apiEndpoints.base + this.config.apiEndpoints.loginAsUser + '/' + userIdentifier; - }; - /** - * Get the endpoint for refreshing a token - * @returns {string} - */ - NgJwtAuthService.prototype.getRefreshEndpoint = function () { - return this.config.apiEndpoints.base + this.config.apiEndpoints.refresh; - }; - /** - * Build a authentication basic header string - * @param username - * @param password - * @returns {string} - */ - NgJwtAuthService.getAuthHeader = function (username, password) { - return 'Basic ' + btoa(username + ':' + password); //note btoa is NOT supported <= IE9 - }; - /** - * Build a token header string - * @returns {string} - */ - NgJwtAuthService.getTokenHeader = function (token) { - return 'Token ' + token; - }; - /** - * Get the standard header for a jwt token request - * @returns {string} - */ - NgJwtAuthService.prototype.getBearerHeader = function () { - if (!this.rawToken) { - throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token is not set"); - } - return 'Bearer ' + this.rawToken; - }; - /** - * Build a refresh header string - * @returns {string} - */ - NgJwtAuthService.prototype.getRefreshHeader = function () { - if (!this.rawToken) { - throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token is not set, it cannot be refreshed"); - } - return 'Bearer ' + this.rawToken; - }; - /** - * Retrieve the token from the remote API - * @param endpoint - * @param authHeader - * @returns {IPromise} - */ - NgJwtAuthService.prototype.retrieveAndProcessToken = function (endpoint, authHeader) { - var _this = this; - var requestConfig = { - method: 'GET', - url: endpoint, - headers: { - Authorization: authHeader - }, - responseType: 'json' - }; - return this.$http(requestConfig).then(function (result) { - if (result && result.data) { - var token = _.get(result.data, _this.config.tokenLocation); - if (_.isString(token)) { - return token; - } - } - return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token could not be found in response body")); - }) - .then(function (token) { - try { - return _this.processNewToken(token); - } - catch (error) { - return _this.$q.reject(error); - } - }) - .catch(function (e) { - if (_.isError(e) || e instanceof _this.$window.Error) { - return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException(e.message)); - } - if (e.status === 401) { - return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthCredentialsFailedException("Login attempt received unauthorised response")); - } - return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException("The API reported an error - " + e.status + " " + e.statusText)); - }); - }; - /** - * Parse the raw token - * @param rawToken - * @returns {IJwtToken} - */ - NgJwtAuthService.prototype.readToken = function (rawToken) { - if ((rawToken.match(/\./g) || []).length !== 2) { - throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Raw token is has incorrect format. Format must be of form \"[header].[data].[signature]\""); - } - var pieces = rawToken.split('.'); - var jwt = { - header: angular.fromJson(this.base64Service.urldecode(pieces[0])), - data: angular.fromJson(this.base64Service.urldecode(pieces[1])), - signature: pieces[2], - }; - return jwt; - }; - /** - * Validate JWT Token - * @param rawToken - * @returns {any} - */ - NgJwtAuthService.prototype.validateToken = function (rawToken) { - try { - var tokenData = this.readToken(rawToken); - return _.isObject(tokenData); - } - catch (e) { - return false; - } - }; - /** - * Prompt user for their login credentials, and attempt to login - * @returns {ng.IPromise} - */ - NgJwtAuthService.prototype.promptLogin = function () { - return this.requireCredentialsAndAuthenticate(); - }; - /** - * Read and save the raw token to storage, kick off timer to attempt refresh - * @param rawToken - * @returns {IUser} - */ - NgJwtAuthService.prototype.processNewToken = function (rawToken) { - var _this = this; - this.rawToken = rawToken; - this.tokenData = this.readToken(rawToken); - var expiryDate = moment(this.tokenData.data.exp * 1000); - if (expiryDate < moment()) { - throw new ngJwtAuthServiceProvider_1.NgJwtAuthTokenExpiredException("Token has expired"); - } - this.saveTokenToStorage(rawToken, this.tokenData); - this.setJWTHeader(rawToken); - this.loggedIn = true; - this.startRefreshTimer(); - var userFromToken = this.getUserFromTokenData(this.tokenData); - userFromToken.then(function (user) { return _this.handleLogin(user); }); - return userFromToken; - }; - NgJwtAuthService.prototype.loadTokenFromStorage = function () { - var rawToken = this.$window.localStorage.getItem(this.config.storageKeyName); - if (!rawToken) { - return this.$q.when("No token in storage"); - } - try { - return this.processNewToken(rawToken); - } - catch (e) { - if (e instanceof ngJwtAuthServiceProvider_1.NgJwtAuthTokenExpiredException) { - return this.requireCredentialsAndAuthenticate(); - } - return this.$q.reject(e); - } - }; - /** - * Check if the endpoint is a login method (used for skipping the authentication error interceptor) - * @param url - * @returns {boolean} - */ - NgJwtAuthService.prototype.isLoginMethod = function (url) { - var loginMethods = [ - this.getLoginEndpoint(), - this.getTokenExchangeEndpoint(), - ]; - return _.contains(loginMethods, url); - }; - NgJwtAuthService.prototype.getUser = function () { - return this.user; - }; - /** - * - * @returns {IHttpPromise} - */ - NgJwtAuthService.prototype.getPromisedUser = function () { - if (this.loggedIn) { - return this.$q.when(this.user); - } - else { - return this.requireCredentialsAndAuthenticate(); - } - }; - /** - * Clear the token - */ - NgJwtAuthService.prototype.clearJWTToken = function () { - this.rawToken = null; - this.$window.localStorage.removeItem(this.config.storageKeyName); - if (this.config.cookie.enabled) { - this.$cookies.remove(this.config.cookie.name); - } - this.unsetJWTHeader(); - }; - /** - * Attempt to log in with username and password - * @param username - * @param password - * @returns {IPromise} - */ - NgJwtAuthService.prototype.authenticateCredentials = function (username, password) { - var authHeader = NgJwtAuthService.getAuthHeader(username, password); - var endpoint = this.getLoginEndpoint(); - return this.retrieveAndProcessToken(endpoint, authHeader); - }; - /** - * Exchange an arbitrary token with a jwt token - * @param token - * @returns {ng.IPromise} - */ - NgJwtAuthService.prototype.exchangeToken = function (token) { - var authHeader = NgJwtAuthService.getTokenHeader(token); - var endpoint = this.getTokenExchangeEndpoint(); - return this.retrieveAndProcessToken(endpoint, authHeader); - }; - /** - * Refresh an existing token - * @returns {ng.IPromise} - */ - NgJwtAuthService.prototype.refreshToken = function () { - var _this = this; - var authHeader = this.getRefreshHeader(); - var endpoint = this.getRefreshEndpoint(); - return this.retrieveAndProcessToken(endpoint, authHeader) - .catch(function (err) { - _this.cancelRefreshTimer(); //if token refreshing fails, stop the refresh timer - return _this.$q.reject(err); - }); - }; - /** - * Require that the user logs in again for a request - * 1. Check if there is already credentials promised - * 2. If not, execute the credential promise factory - * 3. Wait until the credentials are resolved - * 4. Then try to authenticateCredentials - * @returns {IPromise} - */ - NgJwtAuthService.prototype.requireCredentialsAndAuthenticate = function () { - var _this = this; - if (!_.isFunction(this.loginPromptFactory)) { - throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You must set a loginPromptFactory with `ngJwtAuthService.registerLoginPromptFactory()` so the user can be prompted for their credentials"); - } - if (!this.userLoggedInPromise) { - var deferredCredentials_1 = this.$q.defer(); - var loginSuccess_1 = this.$q.defer(); - deferredCredentials_1.promise - .then(null, null, function (credentials) { - return _this.authenticateCredentials(credentials.username, credentials.password).then(function (user) { - //credentials were successful; resolve the promises - deferredCredentials_1.resolve(user); - loginSuccess_1.resolve(user); - }, function (err) { - loginSuccess_1.notify(err); - }); - }); - this.userLoggedInPromise = this.loginPromptFactory(deferredCredentials_1, loginSuccess_1.promise, this.user) - .then(function () { return loginSuccess_1.promise; }, //when the user has completed the login, chain on the login success promise - function (err) { - deferredCredentials_1.reject(); //if the user aborted login, reject the credentials promise - loginSuccess_1.reject(); - return _this.$q.reject(err); //and reject the login promise - }); - } - return this.userLoggedInPromise - .then(function () { - return _this.getUser(); - }) - .finally(function () { - if (!!_this.userLoggedInPromise) { - _this.userLoggedInPromise = null; - } - }); - }; - /** - * Handle the login event - * @param user - */ - NgJwtAuthService.prototype.handleLogin = function (user) { - _.invoke(this.loginListeners, _.call, null, user); - }; - /** - * Find the user object within the path - * @param tokenData - * @returns {T} - */ - NgJwtAuthService.prototype.getUserFromTokenData = function (tokenData) { - var _this = this; - return this.userFactory(tokenData.data.sub, tokenData.data) - .then(function (user) { - _this.user = user; - return user; - }); - }; - /** - * Save the token - * @param rawToken - * @param tokenData - */ - NgJwtAuthService.prototype.saveTokenToStorage = function (rawToken, tokenData) { - this.$window.localStorage.setItem(this.config.storageKeyName, rawToken); - if (this.config.cookie.enabled) { - this.saveCookie(rawToken, tokenData); - } - }; - /** - * Save to cookie - * @param rawToken - * @param tokenData - */ - NgJwtAuthService.prototype.saveCookie = function (rawToken, tokenData) { - var cookieKey = this.config.cookie.name, expires = new Date(tokenData.data.exp * 1000); //set the cookie expiry to the same as the jwt - if (this.config.cookie.topLevelDomain) { - var hostnameParts = this.$location.host().split('.'); - var segmentCount = 1; - var testHostname = ''; - do { - testHostname = _.takeRight(hostnameParts, segmentCount).join('.'); - segmentCount++; - this.$cookies.put(cookieKey, rawToken, { - domain: testHostname, - expires: expires, - }); - if (this.$cookies.get(cookieKey)) { - return; //so exit here - } - } while (segmentCount < hostnameParts.length + 1); //try all the segment combinations, exit when all attempted - throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Could not set cookie for domain " + testHostname); - } - else { - this.$cookies.put(cookieKey, rawToken, { - expires: expires, - }); - } - }; - /** - * Set the authentication token for all new requests - * @param rawToken - */ - NgJwtAuthService.prototype.setJWTHeader = function (rawToken) { - this.$http.defaults.headers.common.Authorization = 'Bearer ' + rawToken; - }; - /** - * Remove the default http authorization header - */ - NgJwtAuthService.prototype.unsetJWTHeader = function () { - delete this.$http.defaults.headers.common.Authorization; - }; - /** - * Handle a request that was rejected due to unauthorised response - * 1. Require authentication - * 2. Retry the rejected $http request - * - * @param rejection - */ - NgJwtAuthService.prototype.handleInterceptedUnauthorisedResponse = function (rejection) { - var _this = this; - return this.requireCredentialsAndAuthenticate() - .then(function () { - //update with the new header - rejection.config.headers['Authorization'] = _this.getBearerHeader(); - return _this.$http(rejection.config); - }); - }; - /** - * Register the login prompt factory - * @param loginPromptFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - NgJwtAuthService.prototype.registerLoginPromptFactory = function (loginPromptFactory) { - if (_.isFunction(this.loginPromptFactory)) { - throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You cannot redeclare the login prompt factory"); - } - this.loginPromptFactory = loginPromptFactory; - return this; - }; - /** - * Register the user factory for extracting a user from data - * @param userFactory - * @returns {NgJwtAuth.NgJwtAuthService} - */ - NgJwtAuthService.prototype.registerUserFactory = function (userFactory) { - this.userFactory = userFactory; - return this; - }; - /** - * Clear the token and service properties - */ - NgJwtAuthService.prototype.logout = function () { - this.clearJWTToken(); - this.loggedIn = false; - //call all logout listeners with user that is logged out - _.invoke(this.logoutListeners, _.call, null, this.user); - this.user = null; - }; - /** - * Register a login listener function - * @param loginListener - */ - NgJwtAuthService.prototype.registerLoginListener = function (loginListener) { - this.loginListeners.push(loginListener); - }; - /** - * Register a logout listener function - * @param logoutListener - */ - NgJwtAuthService.prototype.registerLogoutListener = function (logoutListener) { - this.logoutListeners.push(logoutListener); - }; - /** - * Get a user's token given their identifier - * @param userIdentifier - * @returns {ng.IPromise} - * - * Note this feature should be implemented very carefully as it is a security risk as it means users - * can log in as other users (impersonation). The responsibility is on the implementing app to strongly - * control permissions to access this endpoint to avoid security risks - */ - NgJwtAuthService.prototype.loginAsUser = function (userIdentifier) { - if (!this.loggedIn) { - throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You must be logged in to retrieve a user's token"); - } - var authHeader = this.getBearerHeader(); - var endpoint = this.getLoginAsUserEndpoint(userIdentifier); - return this.retrieveAndProcessToken(endpoint, authHeader); - }; - return NgJwtAuthService; -}()); -exports.NgJwtAuthService = NgJwtAuthService; -//# sourceMappingURL=ngJwtAuthService.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthService.js.map b/dist/ngJwtAuthService.js.map deleted file mode 100644 index d81f96f..0000000 --- a/dist/ngJwtAuthService.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ngJwtAuthService.js","sourceRoot":"","sources":["../src/ngJwtAuthService.ts"],"names":[],"mappings":";AAAA,IAAY,MAAM,WAAM,QAAQ,CAAC,CAAA;AACjC,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAa5B,yCAGO,4BAA4B,CAAC,CAAA;AAEpC;IAiBI;;;;;;;;;;OAUG;IACH,0BAAoB,MAA8B,EAC9B,KAAqB,EACrB,EAAe,EACf,OAAyB,EACzB,SAA6B,EAC7B,aAA4B,EAC5B,QAAmC,EACnC,SAA6B;QAnCrD,iBAyrBC;QA7pBuB,WAAM,GAAN,MAAM,CAAwB;QAC9B,UAAK,GAAL,KAAK,CAAgB;QACrB,OAAE,GAAF,EAAE,CAAa;QACf,YAAO,GAAP,OAAO,CAAkB;QACzB,cAAS,GAAT,SAAS,CAAoB;QAC7B,kBAAa,GAAb,aAAa,CAAe;QAC5B,aAAQ,GAAR,QAAQ,CAA2B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I,iDAAsB,GAA7B,UAA8B,cAAiC;QAC3D,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;;;;OAQG;IACI,sCAAW,GAAlB,UAAmB,cAA4B;QAE3C,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;YACjB,MAAM,IAAI,6CAAkB,CAAC,kDAAkD,CAAC,CAAC;QACrF,CAAC;QAED,IAAI,UAAU,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;QACxC,IAAI,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,cAAc,CAAC,CAAC;QAE3D,MAAM,CAAC,IAAI,CAAC,uBAAuB,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IAC9D,CAAC;IAEL,uBAAC;AAAD,CAAC,AAzrBD,IAyrBC;AAzrBY,wBAAgB,mBAyrB5B,CAAA"} \ No newline at end of file diff --git a/dist/ngJwtAuthServiceProvider.d.ts b/dist/ngJwtAuthServiceProvider.d.ts deleted file mode 100644 index 1cd1303..0000000 --- a/dist/ngJwtAuthServiceProvider.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { IEndpointDefinition } from "./ngJwtAuthInterfaces"; -import { NgJwtAuthService } from "./ngJwtAuthService"; -export declare class Error { - name: string; - message: string; - stack: string; - constructor(message?: string); -} -export declare class NgJwtAuthException extends Error { - message: string; - constructor(message: string); - toString(): string; -} -export declare class NgJwtAuthTokenExpiredException extends NgJwtAuthException { -} -export declare class NgJwtAuthCredentialsFailedException extends NgJwtAuthException { -} -export declare class NgJwtAuthServiceProvider implements ng.IServiceProvider { - private config; - /** - * Initialise the service provider - */ - constructor(); - /** - * Set the configuration - * @param config - * @returns {NgJwtAuth.NgJwtAuthServiceProvider} - */ - configure(config: IEndpointDefinition): NgJwtAuthServiceProvider; - $get: (string | (($http: any, $q: any, $window: any, $interval: any, base64: any, $cookies: any, $location: any) => NgJwtAuthService))[]; -} diff --git a/dist/ngJwtAuthServiceProvider.js b/dist/ngJwtAuthServiceProvider.js deleted file mode 100644 index 5e4810f..0000000 --- a/dist/ngJwtAuthServiceProvider.js +++ /dev/null @@ -1,84 +0,0 @@ -"use strict"; -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; -var ngJwtAuthService_1 = require("./ngJwtAuthService"); -var NgJwtAuthException = (function (_super) { - __extends(NgJwtAuthException, _super); - function NgJwtAuthException(message) { - _super.call(this, message); - this.message = message; - this.name = 'NgJwtAuthException'; - this.message = message; - this.stack = (new Error()).stack; - } - NgJwtAuthException.prototype.toString = function () { - return this.name + ': ' + this.message; - }; - return NgJwtAuthException; -}(Error)); -exports.NgJwtAuthException = NgJwtAuthException; -var NgJwtAuthTokenExpiredException = (function (_super) { - __extends(NgJwtAuthTokenExpiredException, _super); - function NgJwtAuthTokenExpiredException() { - _super.apply(this, arguments); - } - return NgJwtAuthTokenExpiredException; -}(NgJwtAuthException)); -exports.NgJwtAuthTokenExpiredException = NgJwtAuthTokenExpiredException; -var NgJwtAuthCredentialsFailedException = (function (_super) { - __extends(NgJwtAuthCredentialsFailedException, _super); - function NgJwtAuthCredentialsFailedException() { - _super.apply(this, arguments); - } - return NgJwtAuthCredentialsFailedException; -}(NgJwtAuthException)); -exports.NgJwtAuthCredentialsFailedException = NgJwtAuthCredentialsFailedException; -var NgJwtAuthServiceProvider = (function () { - /** - * Initialise the service provider - */ - function NgJwtAuthServiceProvider() { - this.$get = ['$http', '$q', '$window', '$interval', 'base64', '$cookies', '$location', function NgJwtAuthServiceFactory($http, $q, $window, $interval, base64, $cookies, $location) { - return new ngJwtAuthService_1.NgJwtAuthService(this.config, $http, $q, $window, $interval, base64, $cookies, $location); - }]; - //initialise service config - this.config = { - tokenLocation: 'token', - tokenUser: '#user', - apiEndpoints: { - base: '/api/auth', - login: '/login', - tokenExchange: '/token', - loginAsUser: '/user', - refresh: '/refresh', - }, - storageKeyName: 'NgJwtAuthToken', - refreshBeforeSeconds: 60 * 2, - checkExpiryEverySeconds: 60, - cookie: { - enabled: false, - name: 'ngJwtAuthToken', - topLevelDomain: false, - } - }; - } - /** - * Set the configuration - * @param config - * @returns {NgJwtAuth.NgJwtAuthServiceProvider} - */ - NgJwtAuthServiceProvider.prototype.configure = function (config) { - var mismatchedConfig = _.difference(_.keys(config), _.keys(this.config)); - if (mismatchedConfig.length > 0) { - throw new NgJwtAuthException("Invalid properties [" + mismatchedConfig.join(',') + "] passed to config)"); - } - this.config = _.defaultsDeep(config, this.config); - return this; - }; - return NgJwtAuthServiceProvider; -}()); -exports.NgJwtAuthServiceProvider = NgJwtAuthServiceProvider; -//# sourceMappingURL=ngJwtAuthServiceProvider.js.map \ No newline at end of file diff --git a/dist/ngJwtAuthServiceProvider.js.map b/dist/ngJwtAuthServiceProvider.js.map deleted file mode 100644 index 62bdaba..0000000 --- a/dist/ngJwtAuthServiceProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ngJwtAuthServiceProvider.js","sourceRoot":"","sources":["../src/ngJwtAuthServiceProvider.ts"],"names":[],"mappings":";;;;;;AAEA,iCAA+B,oBAAoB,CAAC,CAAA;AASpD;IAAwC,sCAAK;IAEzC,4BAAmB,OAAe;QAC9B,kBAAM,OAAO,CAAC,CAAC;QADA,YAAO,GAAP,OAAO,CAAQ;QAE9B,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,KAAK,GAAG,CAAM,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC;IAC1C,CAAC;IACD,qCAAQ,GAAR;QACI,MAAM,CAAC,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC;IAC3C,CAAC;IACL,yBAAC;AAAD,CAAC,AAX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AiB,MAA0B;QAEvC,IAAI,gBAAgB,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;QACzE,EAAE,CAAC,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA,CAAC;YAC7B,MAAM,IAAI,kBAAkB,CAAC,sBAAsB,GAAC,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAC,qBAAqB,CAAC,CAAC;QAC1G,CAAC;QAED,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAClD,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAML,+BAAC;AAAD,CAAC,AApDD,IAoDC;AApDY,gCAAwB,2BAoDpC,CAAA"} \ No newline at end of file diff --git a/karma.conf.js b/karma.conf.js index 9e2e875..b56a03a 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,30 +1,49 @@ +'use strict'; + +var webpackConfig = require('./webpack/webpack.test.js'); require('phantomjs-polyfill'); +webpackConfig.entry = {}; module.exports = function(config) { config.set({ - frameworks: ['chai-as-promised', 'mocha', 'sinon', 'sinon-chai'], - - preprocessors: { - 'dist/**/*.js': ['commonjs', 'coverage'] - }, + frameworks: ['mocha', 'chai', 'chai-as-promised', 'sinon-chai'], files: [ './node_modules/phantomjs-polyfill/bind-polyfill.js', - 'dist/**/*.js', - 'test/tmp/test/**/*.spec.js' + './src/test.ts' ], - reporters: ['mocha', 'coverage'], + + babelPreprocessor: { + options: { + presets: ['es2015'] + } + }, + + preprocessors: { + 'src/test.ts': ['webpack'], + 'src/**/!(*.spec)+(.js)': ['coverage'] + }, + + webpackMiddleware: { + stats: { + chunkModules: false, + colors: true + } + }, + webpack: webpackConfig, + port: 9018, runnerPort: 9100, urlRoot: '/', + singleRun: true, autoWatch: false, browsers: [ - // 'PhantomJS', - 'Chrome', + 'PhantomJS', + // 'Chrome', ], client: { @@ -34,7 +53,10 @@ module.exports = function(config) { } }, - logLevel: config.LOG_VERBOSE, + logLevel: config.LOG_INFO, + + + reporters: ['mocha', 'coverage'], coverageReporter: { // specify a common output directory diff --git a/package.json b/package.json index f53db2e..fe30c02 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,7 @@ "url": "https://github.com/spira/angular-jwt-auth" }, "scripts": { - "build": "tsc --project tsconfig.build.json --declaration --pretty --listFiles", - "pretest": "tsc --project tsconfig.test.json", + "build": "tsc --declaration --pretty --listFiles", "test": "karma start --NODE_ENV=test", "postinstall": "typings i" }, @@ -22,7 +21,20 @@ "moment": "^2.12.0" }, "devDependencies": { - "bower": "^1.4.1", + "angular-mocks": "1.5.0", + "babel-core": "6.4.5", + "babel-istanbul": "0.6.0", + "browser-sync": "2.11.1", + "browser-sync-webpack-plugin": "1.0.1", + "compression-webpack-plugin": "0.3.0", + "file-loader": "0.8.5", + "istanbul": "0.4.2", + "istanbul-instrumenter-loader": "0.1.3", + "karma-typescript-preprocessor": "0.0.21", + "phantomjs": "2.1.3", + "raw-loader": "0.5.1", + "url-loader": "0.5.7", + "wallaby-webpack": "0.0.11", "del": "^1.2.0", "event-stream": "^3.3.1", "globby": "^2.1.0", @@ -45,20 +57,16 @@ "gulp-typescript": "^2.7.6", "gulp-util": "^3.0.5", "inquirer": "^0.8.5", - "karma": "0.13.19", - "karma-chai": "^0.1.0", - "karma-chai-as-promised": "^0.1.2", - "karma-chai-plugins": "^0.6.0", - "karma-chrome-launcher": "^0.2.0", - "karma-commonjs": "0.0.13", + "karma": "0.13.22", + "karma-chai-plugins": "^0.7.0", + "karma-chrome-launcher": "^0.2.3", "karma-coverage": "0.5.3", - "karma-mocha": "^0.2.0", + "karma-mocha": "^0.2.2", "karma-mocha-reporter": "^1.0.2", "karma-phantomjs-launcher": "1.0.0", - "karma-sinon": "^1.0.4", - "karma-sinon-chai": "^1.2.0", "karma-sourcemap-loader": "0.3.7", "karma-spec-reporter": "0.0.23", + "karma-webpack": "^1.7.0", "lolex": "^1.4.0", "merge2": "^0.3.6", "minimatch": "^2.0.8", @@ -67,8 +75,9 @@ "phantomjs-prebuilt": "2.1.3", "requirejs": "^2.1.18", "run-sequence": "^1.1.1", - "sinon": "^1.17.3", + "ts-loader": "^0.8.1", "typescript": "^1.8.9", - "typings": "^0.7.12" + "typings": "^0.7.12", + "webpack": "^1.12.14" } } diff --git a/src/index.ts b/src/index.ts index 28908f0..9622851 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,11 @@ import "angular"; +import "angular-cookies"; +import "angular-utf8-base64"; + import {NgJwtAuthServiceProvider} from "./ngJwtAuthServiceProvider"; import {NgJwtAuthInterceptor} from "./ngJwtAuthInterceptor"; - -angular.module('ngJwtAuth', ['ab-base64', 'ngCookies']) +angular.module('ngJwtAuth', ['utf8-base64', 'ngCookies']) .provider('ngJwtAuthService', NgJwtAuthServiceProvider) .service('ngJwtAuthInterceptor', NgJwtAuthInterceptor) .config(['$httpProvider', '$injector', ($httpProvider:ng.IHttpProvider) => { diff --git a/test/test.spec.ts b/src/ngJwtAuth.spec.ts similarity index 99% rename from test/test.spec.ts rename to src/ngJwtAuth.spec.ts index 4514270..a539eec 100644 --- a/test/test.spec.ts +++ b/src/ngJwtAuth.spec.ts @@ -5,11 +5,17 @@ import { import {NgJwtAuthService} from "../src/ngJwtAuthService"; import {INgJwtAuthServiceConfig, IJwtToken, ICredentials, IJwtClaims, IUser} from "../src/ngJwtAuthInterfaces"; -import {expect} from "chai"; + import {Chance} from "chance"; import * as _ from "lodash"; +import * as moment from "moment"; +import "angular"; +import "angular-mocks"; +import "." //@todo double check this is right + +let expect:Chai.ExpectStatic = chai.expect; -let seededChance = new Chance(1); +let seededChance:Chance.Chance = new Chance(1); let fixtures = { user : { _self: '/users/1', @@ -232,7 +238,7 @@ describe('Service tests', () => { }); - angular.mock.module('ngCookies',[]); //register the angular.mock.module as being overriden + angular.module('ngCookies',[]); //register the angular.mock.module as being overriden angular.mock.module('ngJwtAuth'); diff --git a/src/test.ts b/src/test.ts new file mode 100644 index 0000000..0ebae77 --- /dev/null +++ b/src/test.ts @@ -0,0 +1,7 @@ +// this file is only being used by karma +require('phantomjs-polyfill') + +requireAll((require).context("./", true, /spec.ts$/)); +function requireAll(r: any): any { + r.keys().forEach(r); +} \ No newline at end of file diff --git a/tsconfig.build.json b/tsconfig.json similarity index 92% rename from tsconfig.build.json rename to tsconfig.json index 9ecc2b3..af7e937 100644 --- a/tsconfig.build.json +++ b/tsconfig.json @@ -15,8 +15,7 @@ "dev", "typings/main.d.ts", "typings/main", - "reports", - "test" + "reports" ], "version": "1.8.9" } \ No newline at end of file diff --git a/tsconfig.test.json b/tsconfig.test.json deleted file mode 100644 index bbddaf6..0000000 --- a/tsconfig.test.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "compilerOptions": { - "target": "es5", - "noImplicitAny": false, - "removeComments": true, - "sourceMap": true, - "module": "commonjs", - "experimentalDecorators": true, - "outDir": "test/tmp" - }, - "exclude": [ - "out", - "node_modules", - "dist", - "dev", - "typings/main.d.ts", - "typings/main", - "reports" - ], - "version": "1.8.9" -} \ No newline at end of file diff --git a/webpack/loaders.js b/webpack/loaders.js new file mode 100644 index 0000000..da9636b --- /dev/null +++ b/webpack/loaders.js @@ -0,0 +1,29 @@ +module.exports = [ + {test: /\.ts(x?)$/, loader: 'ts-loader'}, + { + test: /\.css$/, + loader: 'style-loader!css-loader' + }, + { + test: /\.scss$/, + loader: 'style!css!sass' + }, { + test: /\.html$/, + exclude: /node_modules/, + loader: 'raw' + }, { + test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, + loader: 'url-loader?limit=10000&mimetype=application/font-woff' + }, { + test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, + loader: 'file-loader' + }, { + test: '\.jpg$', + exclude: /node_modules/, + loader: 'file' + }, { + test: '\.png$', + exclude: /node_modules/, + loader: 'url' + } +]; diff --git a/webpack/webpack.test.js b/webpack/webpack.test.js new file mode 100644 index 0000000..620d0b2 --- /dev/null +++ b/webpack/webpack.test.js @@ -0,0 +1,27 @@ +var loaders = require("./loaders"); +var webpack = require('webpack'); +module.exports = { + entry: ['./src/index.ts'], + output: { + filename: 'build.js', + path: 'tmp' + }, + resolve: { + root: __dirname, + extensions: ['', '.ts', '.js', '.json'] + }, + resolveLoader: { + modulesDirectories: ["node_modules"] + }, + devtool: "source-map-inline", + module: { + loaders: loaders, + postLoaders: [ + { + test: /^((?!\.spec\.ts).)*.ts$/, + exclude: /(node_modules)/, + loader: 'istanbul-instrumenter' + } + ] + } +}; From 2a9209cfb6495c47871362b40acd67d5241b1328 Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Tue, 5 Apr 2016 22:44:28 +0100 Subject: [PATCH 03/13] Fixed renamed lodash functions --- karma.conf.js | 2 +- src/ngJwtAuth.spec.ts | 11 ++++++----- src/ngJwtAuthService.ts | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/karma.conf.js b/karma.conf.js index b56a03a..294a3e4 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -49,7 +49,7 @@ module.exports = function(config) { client: { captureConsole: true, mocha: { - bail: true + // bail: true } }, diff --git a/src/ngJwtAuth.spec.ts b/src/ngJwtAuth.spec.ts index a539eec..ba547a2 100644 --- a/src/ngJwtAuth.spec.ts +++ b/src/ngJwtAuth.spec.ts @@ -228,7 +228,7 @@ describe('Service tests', () => { let cookieDomain = 'example.com'; let hostDomain = 'sub.example.com'; - beforeEach(()=>{ + beforeEach(() => { angular.mock.module(function ($provide) { @@ -238,24 +238,24 @@ describe('Service tests', () => { }); - angular.module('ngCookies',[]); //register the angular.mock.module as being overriden + angular.module('ngCookies', []); //register the angular.mock.module as being overriden angular.mock.module('ngJwtAuth'); inject((_$httpBackend_, _ngJwtAuthService_, _$http_, _$rootScope_, _$cookies_, _$q_) => { - if (!ngJwtAuthService){ //dont rebind, so each test gets the singleton + if (!ngJwtAuthService) { //dont rebind, so each test gets the singleton $httpBackend = _$httpBackend_; $rootScope = _$rootScope_; ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider $http = _$http_; $q = _$q_; $cookies = _$cookies_; + } }); ngJwtAuthService.init(); - }); afterEach(() => { @@ -284,6 +284,7 @@ describe('Service tests', () => { describe('Authentication', () => { + //@todo resolve why http service is not mocked. Likely due to the one-time binding. it('should process a token and return a user', () => { $httpBackend.expectGET('/api/auth/login').respond({token: fixtures.token}); @@ -328,7 +329,7 @@ describe('Service tests', () => { expect(ngJwtAuthService.getUser()).to.be.null; $httpBackend.expectGET('/any', (headers) => { - return !_.contains(headers, 'Authorization'); //Authorization header has been unset + return !_.includes(headers, 'Authorization'); //Authorization header has been unset }).respond('foobar'); (ngJwtAuthService).$http.get('/any'); diff --git a/src/ngJwtAuthService.ts b/src/ngJwtAuthService.ts index e9683a1..9c486df 100644 --- a/src/ngJwtAuthService.ts +++ b/src/ngJwtAuthService.ts @@ -382,7 +382,7 @@ export class NgJwtAuthService { this.getTokenExchangeEndpoint(), ]; - return _.contains(loginMethods, url); + return _.includes(loginMethods, url); } public getUser():IUser { From 83978c5dff221a745d1129d69deab734c45796c9 Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 12:32:43 +0100 Subject: [PATCH 04/13] Split tests across files, various style fixes --- src/declarations.d.ts | 1 + src/fixtures.spec.ts | 106 ++++++++ src/index.ts | 4 +- src/{ => interceptor}/ngJwtAuthInterceptor.ts | 10 +- src/provider/ngJwtAuthServiceProvider.spec.ts | 105 ++++++++ .../ngJwtAuthServiceProvider.ts | 33 +-- .../ngJwtAuthService.spec.ts} | 243 ++---------------- src/{ => service}/ngJwtAuthService.ts | 24 +- src/test.ts | 2 +- 9 files changed, 271 insertions(+), 257 deletions(-) create mode 100644 src/declarations.d.ts create mode 100644 src/fixtures.spec.ts rename src/{ => interceptor}/ngJwtAuthInterceptor.ts (87%) create mode 100644 src/provider/ngJwtAuthServiceProvider.spec.ts rename src/{ => provider}/ngJwtAuthServiceProvider.ts (73%) rename src/{ngJwtAuth.spec.ts => service/ngJwtAuthService.spec.ts} (82%) rename src/{ => service}/ngJwtAuthService.ts (97%) diff --git a/src/declarations.d.ts b/src/declarations.d.ts new file mode 100644 index 0000000..4db9ef4 --- /dev/null +++ b/src/declarations.d.ts @@ -0,0 +1 @@ +declare function require(string: string): string; \ No newline at end of file diff --git a/src/fixtures.spec.ts b/src/fixtures.spec.ts new file mode 100644 index 0000000..7e06abc --- /dev/null +++ b/src/fixtures.spec.ts @@ -0,0 +1,106 @@ +import {Chance} from "chance"; +import * as _ from "lodash"; +import * as moment from "moment"; +import {IJwtToken, IUser} from "./ngJwtAuthInterfaces"; + +let seededChance:Chance.Chance = new Chance(1); +export const fixtures = { + user: { + _self: '/users/1', + userId: 1, + email: 'joe.bloggs@example.com', + firstName: seededChance.first(), + lastName: seededChance.last(), + password: 'password', + phone: seededChance.phone() + }, + + get userResponse():IUser{ + return _.omit(fixtures.user, 'password'); + }, + + get authBasic():string{ + return 'Basic '+btoa(fixtures.user.email+':'+fixtures.user.password) + }, + + buildToken: (overrides = {}) => { + let defaultConfig = { + header: { + alg: 'RS256', + typ: 'JWT' + }, + data: { + iss: 'api.spira.io', + aud: 'spira.io', + sub: fixtures.user.userId, + iat: Number(moment().format('X')), + exp: Number(moment().add(1, 'hours').format('X')), + jti: 'random-hash', + '#user': fixtures.userResponse, + }, + signature: 'this-is-the-signed-hash' + }; + + let token:IJwtToken = _.merge(defaultConfig, overrides); + + return btoa(JSON.stringify(token.data)) + + '.' + btoa(JSON.stringify(token.data)) + + '.' + token.signature + ; + }, + + get token(){ + + return fixtures.buildToken(); //no customisations + } +}; + + +export function locationFactoryMock(hostname:string) { + return () => { + + return { + host: function () { + return hostname; + } + }; + }; +} + +export function cookiesFactoryMock(allowDomain:string) { + + let cookieStore = {}; + + return () => { + + return { + /* If you need more then $location.host(), add more methods */ + put: (key, value, conf) => { + + if (conf.domain && conf.domain !== allowDomain || value.split('.')[2] == 'always-fail-domain'){ + return false; + } + + cookieStore[key] = { + value: value, + conf: conf + }; + }, + + get: (key) => { + if (!cookieStore[key]){ + return undefined; + } + return cookieStore[key].value; + }, + + getObject: (key) => { + return cookieStore[key]; + }, + + remove: (key) => { + delete cookieStore[key]; + } + }; + }; +}; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 9622851..4720eb4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,8 +2,8 @@ import "angular"; import "angular-cookies"; import "angular-utf8-base64"; -import {NgJwtAuthServiceProvider} from "./ngJwtAuthServiceProvider"; -import {NgJwtAuthInterceptor} from "./ngJwtAuthInterceptor"; +import {NgJwtAuthServiceProvider} from "./provider/ngJwtAuthServiceProvider"; +import {NgJwtAuthInterceptor} from "./interceptor/ngJwtAuthInterceptor"; angular.module('ngJwtAuth', ['utf8-base64', 'ngCookies']) .provider('ngJwtAuthService', NgJwtAuthServiceProvider) diff --git a/src/ngJwtAuthInterceptor.ts b/src/interceptor/ngJwtAuthInterceptor.ts similarity index 87% rename from src/ngJwtAuthInterceptor.ts rename to src/interceptor/ngJwtAuthInterceptor.ts index 05b17ca..eeedb2a 100644 --- a/src/ngJwtAuthInterceptor.ts +++ b/src/interceptor/ngJwtAuthInterceptor.ts @@ -1,11 +1,10 @@ +import {NgJwtAuthService} from "../service/ngJwtAuthService"; - -import {NgJwtAuthService} from "./ngJwtAuthService"; +export const authorizationUpdateHeader:string = 'Authorization-Update'; export class NgJwtAuthInterceptor { //list injected dependencies - private $http:ng.IHttpService; private $q:ng.IQService; private $injector:ng.auto.IInjectorService; private ngJwtAuthService:NgJwtAuthService; @@ -15,8 +14,7 @@ export class NgJwtAuthInterceptor { * @param _$q * @param _$injector */ - static $inject = ['$q', '$injector']; - + static $inject:string[] = ['$q', '$injector']; constructor(_$q:ng.IQService, _$injector:ng.auto.IInjectorService) { this.$q = _$q; @@ -32,7 +30,7 @@ export class NgJwtAuthInterceptor { public response = (response:ng.IHttpPromiseCallbackArg):ng.IHttpPromiseCallbackArg => { - let updateHeader = response.headers('Authorization-Update'); + let updateHeader = response.headers(authorizationUpdateHeader); if (updateHeader) { diff --git a/src/provider/ngJwtAuthServiceProvider.spec.ts b/src/provider/ngJwtAuthServiceProvider.spec.ts new file mode 100644 index 0000000..a24bd8d --- /dev/null +++ b/src/provider/ngJwtAuthServiceProvider.spec.ts @@ -0,0 +1,105 @@ +import {NgJwtAuthServiceProvider, NgJwtAuthException} from "./ngJwtAuthServiceProvider"; +import {NgJwtAuthService} from "../service/ngJwtAuthService"; +import {INgJwtAuthServiceConfig} from "../ngJwtAuthInterfaces"; + +import "angular"; +import "angular-mocks"; +import "../index" //@todo double check this is right + +let expect:Chai.ExpectStatic = chai.expect; + +let defaultAuthServiceProvider:NgJwtAuthServiceProvider; + +describe('Default configuration', function () { + + let defaultAuthService:NgJwtAuthService; + + beforeEach(() => { + + angular.mock.module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { + defaultAuthServiceProvider = _ngJwtAuthServiceProvider_; //register injection of service provider + }); + + }); + + it('should have the default endpoints', () => { + expect((defaultAuthServiceProvider).config.apiEndpoints.base).to.equal('/api/auth'); + expect((defaultAuthServiceProvider).config.apiEndpoints.login).to.equal('/login'); + expect((defaultAuthServiceProvider).config.apiEndpoints.refresh).to.equal('/refresh'); + }); + + beforeEach(()=>{ + inject(function(_ngJwtAuthService_){ + defaultAuthService = _ngJwtAuthService_; + }) + }); + + it('should have the default login endpoint', function() { + expect((defaultAuthService).getLoginEndpoint()).to.equal('/api/auth/login'); + }); + + it('should have the default token exchange endpoint', function() { + expect((defaultAuthService).getTokenExchangeEndpoint()).to.equal('/api/auth/token'); + }); + + it('should have the default refresh endpoint', function() { + expect((defaultAuthService).getRefreshEndpoint()).to.equal('/api/auth/refresh'); + }); + +}); + +describe('Custom configuration', function () { + + let authServiceProvider:NgJwtAuthServiceProvider; + let customAuthService:NgJwtAuthService; + let partialCustomConfig:INgJwtAuthServiceConfig = { + tokenLocation: 'token-custom', + tokenUser: '#user-custom', + apiEndpoints: { + base: '/api/auth-custom', + login: '/login-custom', + tokenExchange: '/token-custom', + refresh: '/refresh-custom', + }, + //storageKeyName: 'NgJwtAuthToken-custom', //intentionally commented out as this will be tested to be the default + }; + + beforeEach(() => { + + angular.mock.module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { + authServiceProvider = _ngJwtAuthServiceProvider_; //register injection of service provider + + authServiceProvider.configure(partialCustomConfig); + }); + + }); + + it('should throw an exception when invalid configuration is passed', () => { + + let testInvalidConfigurationFn = () => { + authServiceProvider.configure({invalid:'config'}); + }; + + expect(testInvalidConfigurationFn).to.throw(NgJwtAuthException); + + }); + + it('should be able to partially configure the service provider', () => { + + expect((authServiceProvider).config.apiEndpoints).to.deep.equal(partialCustomConfig.apiEndpoints); //assert that the custom value has come across + + expect((authServiceProvider).config.storageKeyName).to.deep.equal((authServiceProvider).config.storageKeyName); //assert that the default was not overridden + + }); + + beforeEach(()=>{ + inject((_ngJwtAuthService_) => { + customAuthService = _ngJwtAuthService_; + }) + }); + + it('should have the configured login endpoint', function() { + expect((customAuthService).getLoginEndpoint()).to.equal('/api/auth-custom/login-custom'); + }); + +}); \ No newline at end of file diff --git a/src/ngJwtAuthServiceProvider.ts b/src/provider/ngJwtAuthServiceProvider.ts similarity index 73% rename from src/ngJwtAuthServiceProvider.ts rename to src/provider/ngJwtAuthServiceProvider.ts index 24ba097..ae8e25c 100644 --- a/src/ngJwtAuthServiceProvider.ts +++ b/src/provider/ngJwtAuthServiceProvider.ts @@ -1,33 +1,36 @@ - -import {INgJwtAuthServiceConfig, IEndpointDefinition} from "./ngJwtAuthInterfaces"; -import {NgJwtAuthService} from "./ngJwtAuthService"; +import {INgJwtAuthServiceConfig, IEndpointDefinition} from "../ngJwtAuthInterfaces"; +import {NgJwtAuthService} from "../service/ngJwtAuthService"; export declare class Error { - public name: string; - public message: string; - public stack: string; - constructor(message?: string); + public name:string; + public message:string; + public stack:string; + + constructor(message?:string); } export class NgJwtAuthException extends Error { - constructor(public message: string) { + constructor(public message:string) { super(message); this.name = 'NgJwtAuthException'; this.message = message; this.stack = (new Error()).stack; } + toString() { return this.name + ': ' + this.message; } } -export class NgJwtAuthTokenExpiredException extends NgJwtAuthException{} -export class NgJwtAuthCredentialsFailedException extends NgJwtAuthException{} +export class NgJwtAuthTokenExpiredException extends NgJwtAuthException { +} +export class NgJwtAuthCredentialsFailedException extends NgJwtAuthException { +} export class NgJwtAuthServiceProvider implements ng.IServiceProvider { - private config: INgJwtAuthServiceConfig; + private config:INgJwtAuthServiceConfig; /** * Initialise the service provider @@ -60,13 +63,13 @@ export class NgJwtAuthServiceProvider implements ng.IServiceProvider { /** * Set the configuration * @param config - * @returns {NgJwtAuth.NgJwtAuthServiceProvider} + * @returns {NgJwtAuthServiceProvider} */ - public configure(config:IEndpointDefinition) : NgJwtAuthServiceProvider { + public configure(config:IEndpointDefinition):NgJwtAuthServiceProvider { let mismatchedConfig = _.difference(_.keys(config), _.keys(this.config)); - if (mismatchedConfig.length > 0){ - throw new NgJwtAuthException("Invalid properties ["+mismatchedConfig.join(',')+"] passed to config)"); + if (mismatchedConfig.length > 0) { + throw new NgJwtAuthException("Invalid properties [" + mismatchedConfig.join(',') + "] passed to config)"); } this.config = _.defaultsDeep(config, this.config); diff --git a/src/ngJwtAuth.spec.ts b/src/service/ngJwtAuthService.spec.ts similarity index 82% rename from src/ngJwtAuth.spec.ts rename to src/service/ngJwtAuthService.spec.ts index ba547a2..f8ffb1c 100644 --- a/src/ngJwtAuth.spec.ts +++ b/src/service/ngJwtAuthService.spec.ts @@ -1,218 +1,19 @@ import { NgJwtAuthServiceProvider, NgJwtAuthException, NgJwtAuthCredentialsFailedException -} from "../src/ngJwtAuthServiceProvider"; -import {NgJwtAuthService} from "../src/ngJwtAuthService"; -import {INgJwtAuthServiceConfig, IJwtToken, ICredentials, IJwtClaims, IUser} from "../src/ngJwtAuthInterfaces"; +} from "../provider/ngJwtAuthServiceProvider"; +import {NgJwtAuthService} from "./ngJwtAuthService"; +import {INgJwtAuthServiceConfig, ICredentials, IJwtClaims, IUser} from "../ngJwtAuthInterfaces"; - -import {Chance} from "chance"; import * as _ from "lodash"; import * as moment from "moment"; import "angular"; import "angular-mocks"; -import "." //@todo double check this is right - -let expect:Chai.ExpectStatic = chai.expect; - -let seededChance:Chance.Chance = new Chance(1); -let fixtures = { - user : { - _self: '/users/1', - userId: 1, - email: 'joe.bloggs@example.com', - firstName: seededChance.first(), - lastName: seededChance.last(), - password: 'password', - phone: seededChance.phone() - }, - - get userResponse(){ - return _.omit(fixtures.user, 'password'); - }, - - get authBasic(){ - return 'Basic '+btoa(fixtures.user.email+':'+fixtures.user.password) - }, - - buildToken: (overrides = {}) => { - let defaultConfig = { - header: { - alg: 'RS256', - typ: 'JWT' - }, - data: { - iss: 'api.spira.io', - aud: 'spira.io', - sub: fixtures.user.userId, - iat: Number(moment().format('X')), - exp: Number(moment().add(1, 'hours').format('X')), - jti: 'random-hash', - '#user': fixtures.userResponse, - }, - signature: 'this-is-the-signed-hash' - }; - - let token:IJwtToken = _.merge(defaultConfig, overrides); - - return btoa(JSON.stringify(token.data)) - + '.' + btoa(JSON.stringify(token.data)) - + '.' + token.signature - ; - }, - - get token(){ - - return fixtures.buildToken(); //no customisations - } -}; - - -let locationFactoryMock = (hostname) => { - return () => { - - return { - host: function () { - return hostname; - } - }; - }; -}; - -let cookiesFactoryMock = (allowDomain) => { - - let cookieStore = {}; - - return () => { - - return { - /* If you need more then $location.host(), add more methods */ - put: (key, value, conf) => { - - if (conf.domain && conf.domain !== allowDomain || value.split('.')[2] == 'always-fail-domain'){ - return false; - } - - cookieStore[key] = { - value: value, - conf: conf - }; - }, - - get: (key) => { - if (!cookieStore[key]){ - return undefined; - } - return cookieStore[key].value; - }, - - getObject: (key) => { - return cookieStore[key]; - }, - - remove: (key) => { - delete cookieStore[key]; - } - }; - }; -}; - -let defaultAuthServiceProvider:NgJwtAuthServiceProvider; - -describe('Default configuration', function () { - - let defaultAuthService:NgJwtAuthService; - - beforeEach(() => { - - angular.mock.module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { - defaultAuthServiceProvider = _ngJwtAuthServiceProvider_; //register injection of service provider - }); - - }); - - it('should have the default endpoints', () => { - expect((defaultAuthServiceProvider).config.apiEndpoints.base).to.equal('/api/auth'); - expect((defaultAuthServiceProvider).config.apiEndpoints.login).to.equal('/login'); - expect((defaultAuthServiceProvider).config.apiEndpoints.refresh).to.equal('/refresh'); - }); - - beforeEach(()=>{ - inject(function(_ngJwtAuthService_){ - defaultAuthService = _ngJwtAuthService_; - }) - }); - - it('should have the default login endpoint', function() { - expect((defaultAuthService).getLoginEndpoint()).to.equal('/api/auth/login'); - }); - - it('should have the default token exchange endpoint', function() { - expect((defaultAuthService).getTokenExchangeEndpoint()).to.equal('/api/auth/token'); - }); - - it('should have the default refresh endpoint', function() { - expect((defaultAuthService).getRefreshEndpoint()).to.equal('/api/auth/refresh'); - }); - -}); - -describe('Custom configuration', function () { - - let authServiceProvider:NgJwtAuthServiceProvider; - let customAuthService:NgJwtAuthService; - let partialCustomConfig:INgJwtAuthServiceConfig = { - tokenLocation: 'token-custom', - tokenUser: '#user-custom', - apiEndpoints: { - base: '/api/auth-custom', - login: '/login-custom', - tokenExchange: '/token-custom', - refresh: '/refresh-custom', - }, - //storageKeyName: 'NgJwtAuthToken-custom', //intentionally commented out as this will be tested to be the default - }; - - beforeEach(() => { - - angular.mock.module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { - authServiceProvider = _ngJwtAuthServiceProvider_; //register injection of service provider - - authServiceProvider.configure(partialCustomConfig); - }); - - }); - - it('should throw an exception when invalid configuration is passed', () => { - - let testInvalidConfigurationFn = () => { - authServiceProvider.configure({invalid:'config'}); - }; - - expect(testInvalidConfigurationFn).to.throw(NgJwtAuthException); - - }); +import "../index" //@todo double check this is right - it('should be able to partially configure the service provider', () => { - - expect((authServiceProvider).config.apiEndpoints).to.deep.equal(partialCustomConfig.apiEndpoints); //assert that the custom value has come across - - expect((authServiceProvider).config.storageKeyName).to.deep.equal((authServiceProvider).config.storageKeyName); //assert that the default was not overridden - - }); - - beforeEach(()=>{ - inject((_ngJwtAuthService_) => { - customAuthService = _ngJwtAuthService_; - }) - }); - - it('should have the configured login endpoint', function() { - expect((customAuthService).getLoginEndpoint()).to.equal('/api/auth-custom/login-custom'); - }); - -}); +import {cookiesFactoryMock, locationFactoryMock, fixtures} from "../fixtures.spec" +let expect:Chai.ExpectStatic = chai.expect; describe('Service tests', () => { @@ -230,21 +31,21 @@ describe('Service tests', () => { beforeEach(() => { - angular.mock.module(function ($provide) { + if (!ngJwtAuthService) { //dont rebind, so each test gets the same singleton + angular.mock.module(($provide:ng.auto.IProvideService) => { - $provide.factory('$cookies', cookiesFactoryMock(cookieDomain)); + $provide.factory('$cookies', cookiesFactoryMock(cookieDomain)); - $provide.factory('$location', locationFactoryMock(hostDomain)); + $provide.factory('$location', locationFactoryMock(hostDomain)); - }); + }); - angular.module('ngCookies', []); //register the angular.mock.module as being overriden + angular.module('ngCookies', []); //register the module as being overriden - angular.mock.module('ngJwtAuth'); + angular.mock.module('ngJwtAuth'); - inject((_$httpBackend_, _ngJwtAuthService_, _$http_, _$rootScope_, _$cookies_, _$q_) => { + inject((_$httpBackend_, _ngJwtAuthService_, _$http_, _$rootScope_, _$cookies_, _$q_) => { - if (!ngJwtAuthService) { //dont rebind, so each test gets the singleton $httpBackend = _$httpBackend_; $rootScope = _$rootScope_; ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider @@ -252,10 +53,11 @@ describe('Service tests', () => { $q = _$q_; $cookies = _$cookies_; - } - }); + }); + + ngJwtAuthService.init(); + } - ngJwtAuthService.init(); }); afterEach(() => { @@ -668,7 +470,7 @@ describe('Service tests', () => { expect(spy.loginPromptFactory).to.have.callCount(6); - var progressSpy = sinon.spy(); + let progressSpy = sinon.spy(); loginSuccess.then(null, null, progressSpy); userPromise.then(() => { @@ -824,7 +626,6 @@ describe('Service tests', () => { */ it('should be able to retrieve a token given a known user id', () => { - let userToImpersonate = fixtures.userResponse; userToImpersonate.userId = 2; @@ -1144,7 +945,7 @@ describe('Service Reloading', () => { it('should fail when the token in storage is malformed (vendor collision perhaps)', () => { - window.localStorage.setItem((defaultAuthServiceProvider).config.storageKeyName, 'this-is-not-a-jwt-token'); + window.localStorage.setItem((NgJwtAuthServiceProvider).config.storageKeyName, 'this-is-not-a-jwt-token'); let init = ngJwtAuthService.init(); @@ -1154,7 +955,7 @@ describe('Service Reloading', () => { it('should use the token from storage on init', () => { - window.localStorage.setItem((defaultAuthServiceProvider).config.storageKeyName, fixtures.token); + window.localStorage.setItem((NgJwtAuthServiceProvider).config.storageKeyName, fixtures.token); let userPromise = ngJwtAuthService.init().then(() => ngJwtAuthService.getPromisedUser()); @@ -1245,7 +1046,7 @@ describe('Service Reloading', () => { before(()=>{ ngJwtAuthService.logout(); //clear the authservice state - window.localStorage.setItem((defaultAuthServiceProvider).config.storageKeyName, expiredToken); + window.localStorage.setItem((NgJwtAuthServiceProvider).config.storageKeyName, expiredToken); }); it('should prompt the user to log in when the loaded token has expired on init', () => { diff --git a/src/ngJwtAuthService.ts b/src/service/ngJwtAuthService.ts similarity index 97% rename from src/ngJwtAuthService.ts rename to src/service/ngJwtAuthService.ts index 9c486df..b138cde 100644 --- a/src/ngJwtAuthService.ts +++ b/src/service/ngJwtAuthService.ts @@ -10,12 +10,12 @@ import { INgJwtAuthServiceConfig, IBase64Service, IJwtClaims, ICredentials, -} from "./ngJwtAuthInterfaces"; +} from "../ngJwtAuthInterfaces"; import { NgJwtAuthException, NgJwtAuthCredentialsFailedException, NgJwtAuthTokenExpiredException -} from "./ngJwtAuthServiceProvider"; +} from "../provider/ngJwtAuthServiceProvider"; export class NgJwtAuthService { @@ -216,11 +216,11 @@ export class NgJwtAuthService { * Retrieve the token from the remote API * @param endpoint * @param authHeader - * @returns {IPromise} + * @returns {IPromise} */ private retrieveAndProcessToken(endpoint:string, authHeader:string):ng.IPromise { - var requestConfig:ng.IRequestConfig = { + let requestConfig:ng.IRequestConfig = { method: 'GET', url: endpoint, headers: { @@ -279,9 +279,9 @@ export class NgJwtAuthService { throw new NgJwtAuthException("Raw token is has incorrect format. Format must be of form \"[header].[data].[signature]\""); } - var pieces = rawToken.split('.'); + let pieces = rawToken.split('.'); - var jwt:IJwtToken = { + let jwt:IJwtToken = { header: angular.fromJson(this.base64Service.urldecode(pieces[0])), data: angular.fromJson(this.base64Service.urldecode(pieces[1])), signature: pieces[2], @@ -328,7 +328,7 @@ export class NgJwtAuthService { this.tokenData = this.readToken(rawToken); - var expiryDate = moment(this.tokenData.data.exp * 1000); + let expiryDate = moment(this.tokenData.data.exp * 1000); if (expiryDate < moment()) { throw new NgJwtAuthTokenExpiredException("Token has expired"); @@ -391,7 +391,7 @@ export class NgJwtAuthService { /** * - * @returns {IHttpPromise} + * @returns {IHttpPromise} */ public getPromisedUser():ng.IPromise { @@ -469,7 +469,7 @@ export class NgJwtAuthService { * 2. If not, execute the credential promise factory * 3. Wait until the credentials are resolved * 4. Then try to authenticateCredentials - * @returns {IPromise} + * @returns {IPromise} */ public requireCredentialsAndAuthenticate():ng.IPromise { @@ -536,7 +536,7 @@ export class NgJwtAuthService { /** * Find the user object within the path * @param tokenData - * @returns {T} + * @returns {ng.IPromise} */ private getUserFromTokenData(tokenData:IJwtToken):ng.IPromise { @@ -640,7 +640,7 @@ export class NgJwtAuthService { /** * Register the login prompt factory * @param loginPromptFactory - * @returns {NgJwtAuth.NgJwtAuthService} + * @returns {NgJwtAuthService} */ public registerLoginPromptFactory(loginPromptFactory:ILoginPromptFactory):NgJwtAuthService { @@ -656,7 +656,7 @@ export class NgJwtAuthService { /** * Register the user factory for extracting a user from data * @param userFactory - * @returns {NgJwtAuth.NgJwtAuthService} + * @returns {NgJwtAuthService} */ public registerUserFactory(userFactory:IUserFactory):NgJwtAuthService { diff --git a/src/test.ts b/src/test.ts index 0ebae77..309f49f 100644 --- a/src/test.ts +++ b/src/test.ts @@ -1,5 +1,5 @@ // this file is only being used by karma -require('phantomjs-polyfill') +require('phantomjs-polyfill'); requireAll((require).context("./", true, /spec.ts$/)); function requireAll(r: any): any { From 5652ead43527d584c44e310e04ed279ae67d176c Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 15:32:51 +0100 Subject: [PATCH 05/13] Fixed all tests by changing the pattern to not use a single instances of the auth service for testing, fixed lodash typings to use v4, fixed instances of _.invoke that is now renamed to _.invokeMap. --- package.json | 1 + src/provider/ngJwtAuthServiceProvider.ts | 1 + src/service/ngJwtAuthService.spec.ts | 384 +++++++++++++---------- src/service/ngJwtAuthService.ts | 4 +- typings.json | 4 +- 5 files changed, 219 insertions(+), 175 deletions(-) diff --git a/package.json b/package.json index fe30c02..22ed508 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "4.0.0", "description": "Angular JSON Web Token Authentication Module", "main": "dist/ngJwtAuth.js", + "typings": "dist/ngJwtAuth.d.ts", "license": "MIT", "repository": { "type": "git", diff --git a/src/provider/ngJwtAuthServiceProvider.ts b/src/provider/ngJwtAuthServiceProvider.ts index ae8e25c..58c6a00 100644 --- a/src/provider/ngJwtAuthServiceProvider.ts +++ b/src/provider/ngJwtAuthServiceProvider.ts @@ -1,5 +1,6 @@ import {INgJwtAuthServiceConfig, IEndpointDefinition} from "../ngJwtAuthInterfaces"; import {NgJwtAuthService} from "../service/ngJwtAuthService"; +import * as _ from "lodash"; export declare class Error { public name:string; diff --git a/src/service/ngJwtAuthService.spec.ts b/src/service/ngJwtAuthService.spec.ts index f8ffb1c..0044cd1 100644 --- a/src/service/ngJwtAuthService.spec.ts +++ b/src/service/ngJwtAuthService.spec.ts @@ -31,31 +31,64 @@ describe('Service tests', () => { beforeEach(() => { - if (!ngJwtAuthService) { //dont rebind, so each test gets the same singleton - angular.mock.module(($provide:ng.auto.IProvideService) => { + angular.mock.module(($provide:ng.auto.IProvideService) => { - $provide.factory('$cookies', cookiesFactoryMock(cookieDomain)); + $provide.factory('$cookies', cookiesFactoryMock(cookieDomain)); - $provide.factory('$location', locationFactoryMock(hostDomain)); + $provide.factory('$location', locationFactoryMock(hostDomain)); - }); + }); - angular.module('ngCookies', []); //register the module as being overriden + angular.module('ngCookies', []); //register the module as being overriden - angular.mock.module('ngJwtAuth'); + angular.mock.module('ngJwtAuth'); - inject((_$httpBackend_, _ngJwtAuthService_, _$http_, _$rootScope_, _$cookies_, _$q_) => { + inject((_$httpBackend_, _ngJwtAuthService_, _$http_, _$rootScope_, _$cookies_, _$q_) => { - $httpBackend = _$httpBackend_; - $rootScope = _$rootScope_; - ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider - $http = _$http_; - $q = _$q_; - $cookies = _$cookies_; + $httpBackend = _$httpBackend_; + $rootScope = _$rootScope_; + $http = _$http_; + $q = _$q_; + $cookies = _$cookies_; - }); + ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider - ngJwtAuthService.init(); + }); + + ngJwtAuthService.init(); + + let reject = false; + let loginSuccess = null; + + fixtures.loginPrompt = { + getLoginSuccessPromise: ():ng.IPromise => { + return loginSuccess; + }, + shouldRejectPromise:(shouldRejectPromise:boolean = true) => { + reject = shouldRejectPromise; + }, + loginPromptFactory: (deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:IUser):ng.IPromise => { + + let credentials:ICredentials = { + username: fixtures.user.email, + password: fixtures.user.password, + }; + + if (reject) { + return $q.reject('rejected'); + } + + loginSuccess = loginSuccessPromise; //bind so the tests can attach a spy + + deferredCredentials.notify(credentials); + + loginSuccessPromise.then(() => { + }, null, (err) => { + deferredCredentials.notify(credentials); //retry resolving creds + }); + + return $q.when(true); //immediately resolve + }, } }); @@ -86,7 +119,6 @@ describe('Service tests', () => { describe('Authentication', () => { - //@todo resolve why http service is not mocked. Likely due to the one-time binding. it('should process a token and return a user', () => { $httpBackend.expectGET('/api/auth/login').respond({token: fixtures.token}); @@ -100,6 +132,8 @@ describe('Service tests', () => { it('should be able to get user info once authenticated', () => { + ngJwtAuthService.user = fixtures.userResponse; + let user = ngJwtAuthService.getUser(); let userPromise = ngJwtAuthService.getPromisedUser(); @@ -145,11 +179,18 @@ describe('Service tests', () => { describe('Login listening', () => { - let mockListener = sinon.stub(); - - it('should be able to register a login listener', () => { + let mockListener; + beforeEach(() => { + mockListener = sinon.stub(); ngJwtAuthService.registerLoginListener(mockListener); + }); + + afterEach(() => { + mockListener.reset(); + }); + + it('should be able to register a login listener', () => { expect(mockListener).not.to.have.been.called; @@ -174,11 +215,18 @@ describe('Service tests', () => { describe('Logout listening', () => { - let mockListener = sinon.stub(); - - it('should be able to register a logout listener', () => { + let mockListener; + beforeEach(() => { + mockListener = sinon.stub(); ngJwtAuthService.registerLogoutListener(mockListener); + }); + + afterEach(() => { + mockListener.reset(); + }); + + it('should be able to register a logout listener', () => { expect(mockListener).not.to.have.been.called; @@ -277,217 +325,204 @@ describe('Service tests', () => { describe('Login prompt', () => { - let $q; - let rejectPromise = false; - let loginSuccess:ng.IPromise = null; - let spy = { - loginPromptFactory: (deferredCredentials:ng.IDeferred, loginSuccessPromise:ng.IPromise, currentUser:IUser): ng.IPromise => { - let credentials:ICredentials = { - username: fixtures.user.email, - password: fixtures.user.password, - }; - if (rejectPromise){ - return $q.reject('rejected'); - } + beforeEach(() => { + sinon.spy(fixtures.loginPrompt, 'loginPromptFactory'); + $q = (ngJwtAuthService).$q; + }); - loginSuccess = loginSuccessPromise; //bind so the tests can attach a spy + afterEach(() => { + (fixtures.loginPrompt.loginPromptFactory).reset(); + }); - deferredCredentials.notify(credentials); + describe('login factory registration', () => { + it('should throw an exception when a login prompt factory is not set', () => { - loginSuccessPromise.then(() => { - }, null, (err) => { - deferredCredentials.notify(credentials); //retry resolving creds - }); + let testLoginPromptFactoryFn = () => { + ngJwtAuthService.promptLogin(); + }; - return $q.when(true); //immediately resolve - } - }; + expect(testLoginPromptFactoryFn).to.throw(NgJwtAuthException); - sinon.spy(spy, 'loginPromptFactory'); + }); - beforeEach(() => { - $q = (ngJwtAuthService).$q; + it('should be able to set a login prompt factory', () => { + + //set credential promise factory + ngJwtAuthService.registerLoginPromptFactory(fixtures.loginPrompt.loginPromptFactory); + + expect(fixtures.loginPrompt.loginPromptFactory).not.to.have.been.called; + + }); }); - it('should throw an exception when a login prompt factory is not set', () => { + describe('login factory tests', () => { - let testLoginPromptFactoryFn = () => { - ngJwtAuthService.promptLogin(); - }; + beforeEach(() => { - expect(testLoginPromptFactoryFn).to.throw(NgJwtAuthException); + //set credential promise factory + ngJwtAuthService.registerLoginPromptFactory(fixtures.loginPrompt.loginPromptFactory); + }); - }); + it('should not be able to re-set a login prompt factory', () => { - it('should be able to set a login prompt factory', () => { + //set credential promise factory + let setFactoryFn = () => { + ngJwtAuthService.registerLoginPromptFactory(fixtures.loginPrompt.loginPromptFactory); + }; - //set credential promise factory - ngJwtAuthService.registerLoginPromptFactory(spy.loginPromptFactory); + expect(setFactoryFn).to.throw(NgJwtAuthException); - expect(spy.loginPromptFactory).not.to.have.been.called; + }); - }); + it('should prompt a login promise to be resolved when a 401 occurs, then retry the method with updated headers', () => { + $httpBackend.expectGET('/any').respond(401); - it('should not be able to re-set a login prompt factory', () => { + let $http = (ngJwtAuthService).$http; //get the injected http method - //set credential promise factory - let setFactoryFn = () => { - ngJwtAuthService.registerLoginPromptFactory(() => $q.when(true)); - }; + //try to get a resource + $http.get('/any', { + headers: { + Authorization: "Bearer " + fixtures.buildToken({signature:'old-token'}), + } + }); + let newToken = fixtures.buildToken({signature:'new-token'}); - expect(setFactoryFn).to.throw(NgJwtAuthException); + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond({token: newToken}); - }); + $httpBackend.expectGET('/any', (headers) => { + return headers['Authorization'] == 'Bearer ' + newToken; + }).respond('ok'); - it('should prompt a login promise to be resolved when a 401 occurs, then retry the method with updated headers', () => { - $httpBackend.expectGET('/any').respond(401); + $httpBackend.flush(); - let $http = (ngJwtAuthService).$http; //get the injected http method + expect(fixtures.loginPrompt.loginPromptFactory).to.have.been.calledOnce; - //try to get a resource - $http.get('/any', { - headers: { - Authorization: "Bearer " + fixtures.buildToken({signature:'old-token'}), - } }); - let newToken = fixtures.buildToken({signature:'new-token'}); - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond({token: newToken}); + it('should be able to wait for a user to authenticate to get a user object', () => { - $httpBackend.expectGET('/any', (headers) => { - return headers['Authorization'] == 'Bearer ' + newToken; - }).respond('ok'); + ngJwtAuthService.logout(); //make sure that the service is not logged in. - $httpBackend.flush(); + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond({token: fixtures.token}); - expect(spy.loginPromptFactory).to.have.been.calledOnce; - }); + let userPromise = ngJwtAuthService.getPromisedUser(); + let loginStatusPromise = userPromise.then(() => { + return ngJwtAuthService.loggedIn; + }); - it('should be able to wait for a user to authenticate to get a user object', () => { + expect(loginStatusPromise).eventually.to.be.true; - ngJwtAuthService.logout(); //make sure that the service is not logged in. - - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond({token: fixtures.token}); + expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); + $httpBackend.flush(); - let userPromise = ngJwtAuthService.getPromisedUser(); + expect(fixtures.loginPrompt.loginPromptFactory).to.have.been.calledOnce; - let loginStatusPromise = userPromise.then(() => { - return ngJwtAuthService.loggedIn; }); - expect(loginStatusPromise).eventually.to.be.true; + it('should prompt the login prompt factory for credentials when requested and log out when request rejected', () => { - expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); + fixtures.loginPrompt.shouldRejectPromise(true); - $httpBackend.flush(); + let userPromise = ngJwtAuthService.promptLogin(); - expect(spy.loginPromptFactory).to.have.been.calledTwice; + let loginStatusPromise = userPromise.then(() => { + return ngJwtAuthService.loggedIn; + }); - }); + expect(userPromise).to.eventually.be.rejectedWith('rejected'); - it('should prompt the login prompt factory for credentials when requested and log out when request rejected', () => { + expect(fixtures.loginPrompt.loginPromptFactory).to.have.been.calledOnce; - rejectPromise = true; + expect(loginStatusPromise).eventually.to.be.false; - let userPromise = ngJwtAuthService.promptLogin(); + fixtures.loginPrompt.shouldRejectPromise(false); //reset - let loginStatusPromise = userPromise.then(() => { - return ngJwtAuthService.loggedIn; }); - expect(userPromise).to.eventually.be.rejectedWith('rejected'); - - expect(spy.loginPromptFactory).to.have.been.calledThrice; + it('should prompt the login prompt factory for credentials when requested', () => { - expect(loginStatusPromise).eventually.to.be.false; + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond({token: fixtures.token}); - }); + let userPromise = ngJwtAuthService.promptLogin(); - it('should prompt the login prompt factory for credentials when requested', () => { + expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); - rejectPromise = false; + $httpBackend.flush(); - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond({token: fixtures.token}); + expect(fixtures.loginPrompt.loginPromptFactory).to.have.calledOnce; - let userPromise = ngJwtAuthService.promptLogin(); + }); - expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); + it('should allow the user to retry their credentials when they get them wrong the first time', () => { - $httpBackend.flush(); + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond(401); //fail their login first time - expect(spy.loginPromptFactory).to.have.callCount(4); + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond({token: fixtures.token}); //pass it the second time - }); + let userPromise = ngJwtAuthService.promptLogin(); - it('should allow the user to retry their credentials when they get them wrong the first time', () => { + expect(fixtures.loginPrompt.loginPromptFactory).to.have.calledOnce; - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond(401); //fail their login first time + expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond({token: fixtures.token}); //pass it the second time - - let userPromise = ngJwtAuthService.promptLogin(); + $httpBackend.flush(); - expect(spy.loginPromptFactory).to.have.callCount(5); + }); - expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); + it('should have only one error notification emitted for each repeated credential failure', (done) => { - $httpBackend.flush(); + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond(401); //fail their login first time - }); + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond(401); //fail their login a second time - it('should have only one error notification emitted for each repeated credential failure', (done) => { + $httpBackend.expectGET('/api/auth/login', (headers) => { + return headers['Authorization'] == fixtures.authBasic; + }).respond({token: fixtures.token}); //pass it on the third go - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond(401); //fail their login first time + let userPromise = ngJwtAuthService.promptLogin(); - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond(401); //fail their login a second time + expect(fixtures.loginPrompt.loginPromptFactory).to.have.calledOnce; - $httpBackend.expectGET('/api/auth/login', (headers) => { - return headers['Authorization'] == fixtures.authBasic; - }).respond({token: fixtures.token}); //pass it on the third go + let progressSpy = sinon.spy(); + fixtures.loginPrompt.getLoginSuccessPromise().then(null, null, progressSpy); - let userPromise = ngJwtAuthService.promptLogin(); + userPromise.then(() => { + progressSpy.should.have.been.calledTwice; + progressSpy.should.have.been.calledWith(sinon.match.instanceOf(NgJwtAuthException)); + done(); + }); - expect(spy.loginPromptFactory).to.have.callCount(6); + expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); - let progressSpy = sinon.spy(); - loginSuccess.then(null, null, progressSpy); + $httpBackend.flush(); - userPromise.then(() => { - progressSpy.should.have.been.calledTwice; - progressSpy.should.have.been.calledWith(sinon.match.instanceOf(NgJwtAuthException)); - done(); }); - expect(userPromise).to.eventually.deep.equal(fixtures.userResponse); - - $httpBackend.flush(); - }); }); - describe('Authenticate with token', () => { beforeEach(() => { @@ -626,6 +661,9 @@ describe('Service tests', () => { */ it('should be able to retrieve a token given a known user id', () => { + //set credential promise factory + ngJwtAuthService.registerLoginPromptFactory(fixtures.loginPrompt.loginPromptFactory); + let userToImpersonate = fixtures.userResponse; userToImpersonate.userId = 2; @@ -669,9 +707,13 @@ describe('Service tests', () => { }); - describe('API Response Authorization update', () => { + beforeEach(() => { + + //set credential promise factory + ngJwtAuthService.registerLoginPromptFactory(fixtures.loginPrompt.loginPromptFactory); + }); it('should update the request header when an Authorization-Update header is received', () => { @@ -750,13 +792,16 @@ describe('Service tests', () => { config = ngJwtAuthService.getConfig(); + //set credential promise factory + ngJwtAuthService.registerLoginPromptFactory(fixtures.loginPrompt.loginPromptFactory); + }); afterEach(() => { (ngJwtAuthService).config = originalConfig; //restore }); - it('should save a cookie when configured', () => { + it('should save a cookie when configured, and remove it when logging out', () => { ngJwtAuthService.logout(); //logout @@ -774,32 +819,24 @@ describe('Service tests', () => { $httpBackend.flush(); - let cookie = $cookies.get(config.cookie.name); - - expect(cookie).to.equal(token); - - }); + let cookieExists = $cookies.get(config.cookie.name); - it('should have a valid expiry date', () => { + expect(cookieExists).to.equal(token); let expiry = $cookies.getObject(config.cookie.name).conf.expires; expect(expiry).to.be.instanceOf(Date); - }); - - - it('should delete the cookie when logged out', () => { - ngJwtAuthService.logout(); //logout - let cookie = $cookies.get(config.cookie.name); + let cookieMissing = $cookies.get(config.cookie.name); - expect(cookie).to.be.undefined; + expect(cookieMissing).to.be.undefined; }); + describe('Top level domain saving', () => { @@ -871,6 +908,7 @@ describe('Service Reloading', () => { let $httpBackend:ng.IHttpBackendService; let ngJwtAuthService:NgJwtAuthService; let $rootScope:ng.IRootScopeService; + let defaultAuthServiceProvider:NgJwtAuthServiceProvider; beforeEach(()=>{ @@ -882,7 +920,9 @@ describe('Service Reloading', () => { }); - angular.mock.module('ngJwtAuth'); + angular.mock.module('ngJwtAuth', (_ngJwtAuthServiceProvider_) => { + defaultAuthServiceProvider = _ngJwtAuthServiceProvider_; //register injection of service provider + }); inject((_$httpBackend_, _ngJwtAuthService_, _$rootScope_) => { @@ -945,7 +985,7 @@ describe('Service Reloading', () => { it('should fail when the token in storage is malformed (vendor collision perhaps)', () => { - window.localStorage.setItem((NgJwtAuthServiceProvider).config.storageKeyName, 'this-is-not-a-jwt-token'); + window.localStorage.setItem((defaultAuthServiceProvider).config.storageKeyName, 'this-is-not-a-jwt-token'); let init = ngJwtAuthService.init(); @@ -955,7 +995,7 @@ describe('Service Reloading', () => { it('should use the token from storage on init', () => { - window.localStorage.setItem((NgJwtAuthServiceProvider).config.storageKeyName, fixtures.token); + window.localStorage.setItem((defaultAuthServiceProvider).config.storageKeyName, fixtures.token); let userPromise = ngJwtAuthService.init().then(() => ngJwtAuthService.getPromisedUser()); @@ -1046,7 +1086,7 @@ describe('Service Reloading', () => { before(()=>{ ngJwtAuthService.logout(); //clear the authservice state - window.localStorage.setItem((NgJwtAuthServiceProvider).config.storageKeyName, expiredToken); + window.localStorage.setItem((defaultAuthServiceProvider).config.storageKeyName, expiredToken); }); it('should prompt the user to log in when the loaded token has expired on init', () => { diff --git a/src/service/ngJwtAuthService.ts b/src/service/ngJwtAuthService.ts index b138cde..ac66614 100644 --- a/src/service/ngJwtAuthService.ts +++ b/src/service/ngJwtAuthService.ts @@ -529,7 +529,7 @@ export class NgJwtAuthService { */ private handleLogin(user:IUser):void { - _.invoke(this.loginListeners, _.call, null, user); + _.invokeMap(this.loginListeners, _.call, null, user); } @@ -673,7 +673,7 @@ export class NgJwtAuthService { this.loggedIn = false; //call all logout listeners with user that is logged out - _.invoke(this.logoutListeners, _.call, null, this.user); + _.invokeMap(this.logoutListeners, _.call, null, this.user); this.user = null; } diff --git a/typings.json b/typings.json index e19aeeb..b60c85f 100644 --- a/typings.json +++ b/typings.json @@ -7,12 +7,14 @@ "chai-as-promised": "registry:dt/chai-as-promised#0.0.0+20160317120654", "chance": "registry:dt/chance#0.7.3+20160317120654", "jquery": "registry:dt/jquery#1.10.0+20160316155526", - "lodash": "registry:dt/lodash#3.10.0+20160330154726", "mocha": "registry:dt/mocha#2.2.5+20160317120654", "moment": "registry:dt/moment#2.8.0+20160316155526", "moment-node": "registry:dt/moment-node#2.11.1+20160329220348", "promises-a-plus": "registry:dt/promises-a-plus#0.0.0+20160317120654", "sinon": "registry:dt/sinon#1.16.0+20160317120654", "sinon-chai": "registry:dt/sinon-chai#2.7.0+20160317120654" + }, + "dependencies": { + "lodash": "registry:npm/lodash#4.0.0+20160305082308" } } From 900d55f8ee63b269b74f390c3f475e7b173fadce Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 15:36:01 +0100 Subject: [PATCH 06/13] Fixed travis setup --- .travis.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0c4b153..77f351f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ sudo: false #use container based infrastructure language: node_js node_js: - - "5.4.0" + - "5.4.1" addons: apt: @@ -11,14 +11,13 @@ addons: cache: directories: - node_modules - - bower_components install: - travis_retry npm install -g gulp - travis_retry npm install script: - - gulp test + - npm test after_script: - gulp coveralls From 475e000430bef33ec955541a697ed4bf765a89f5 Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 15:47:52 +0100 Subject: [PATCH 07/13] Added text reporter to console, fixed missing chance lib --- karma.conf.js | 1 + package.json | 17 +++++++++-------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/karma.conf.js b/karma.conf.js index 294a3e4..6d4993f 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -64,6 +64,7 @@ module.exports = function(config) { reporters: [ // reporters not supporting the `file` property //{type: 'html', subdir: 'report-html'}, + {type: 'text'}, {type: 'lcov', subdir: 'report-lcov'}, {type: 'clover', subdir: 'app'} ] diff --git a/package.json b/package.json index 22ed508..6798ef0 100644 --- a/package.json +++ b/package.json @@ -27,17 +27,11 @@ "babel-istanbul": "0.6.0", "browser-sync": "2.11.1", "browser-sync-webpack-plugin": "1.0.1", + "chance": "^1.0.1", "compression-webpack-plugin": "0.3.0", - "file-loader": "0.8.5", - "istanbul": "0.4.2", - "istanbul-instrumenter-loader": "0.1.3", - "karma-typescript-preprocessor": "0.0.21", - "phantomjs": "2.1.3", - "raw-loader": "0.5.1", - "url-loader": "0.5.7", - "wallaby-webpack": "0.0.11", "del": "^1.2.0", "event-stream": "^3.3.1", + "file-loader": "0.8.5", "globby": "^2.1.0", "gulp": "^3.9.0", "gulp-bump": "^0.3.1", @@ -58,6 +52,8 @@ "gulp-typescript": "^2.7.6", "gulp-util": "^3.0.5", "inquirer": "^0.8.5", + "istanbul": "0.4.2", + "istanbul-instrumenter-loader": "0.1.3", "karma": "0.13.22", "karma-chai-plugins": "^0.7.0", "karma-chrome-launcher": "^0.2.3", @@ -67,18 +63,23 @@ "karma-phantomjs-launcher": "1.0.0", "karma-sourcemap-loader": "0.3.7", "karma-spec-reporter": "0.0.23", + "karma-typescript-preprocessor": "0.0.21", "karma-webpack": "^1.7.0", "lolex": "^1.4.0", "merge2": "^0.3.6", "minimatch": "^2.0.8", "mocha": "^2.2.5", + "phantomjs": "2.1.3", "phantomjs-polyfill": "0.0.1", "phantomjs-prebuilt": "2.1.3", + "raw-loader": "0.5.1", "requirejs": "^2.1.18", "run-sequence": "^1.1.1", "ts-loader": "^0.8.1", "typescript": "^1.8.9", "typings": "^0.7.12", + "url-loader": "0.5.7", + "wallaby-webpack": "0.0.11", "webpack": "^1.12.14" } } From 69369a7148065d0cb10332f1f841c643a14d5dbc Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 16:17:00 +0100 Subject: [PATCH 08/13] Fixed case where slow tests would fail due to fixture changing over time --- package.json | 2 +- src/fixtures.spec.ts | 11 ++++++++--- src/service/ngJwtAuthService.spec.ts | 1 - 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 6798ef0..37b3f49 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "gulp-typescript": "^2.7.6", "gulp-util": "^3.0.5", "inquirer": "^0.8.5", - "istanbul": "0.4.2", + "istanbul": "^1.0.0-alpha.2", "istanbul-instrumenter-loader": "0.1.3", "karma": "0.13.22", "karma-chai-plugins": "^0.7.0", diff --git a/src/fixtures.spec.ts b/src/fixtures.spec.ts index 7e06abc..0083bda 100644 --- a/src/fixtures.spec.ts +++ b/src/fixtures.spec.ts @@ -4,9 +4,12 @@ import * as moment from "moment"; import {IJwtToken, IUser} from "./ngJwtAuthInterfaces"; let seededChance:Chance.Chance = new Chance(1); + +let loadedToken:string; + export const fixtures = { + loginPrompt:null, user: { - _self: '/users/1', userId: 1, email: 'joe.bloggs@example.com', firstName: seededChance.first(), @@ -50,8 +53,10 @@ export const fixtures = { }, get token(){ - - return fixtures.buildToken(); //no customisations + if (!loadedToken){ + loadedToken = fixtures.buildToken(); //no customisations + } + return loadedToken; //this "caching" ensures the token is unchanged between tests if they take too long (otherwise the timestamps may differ) } }; diff --git a/src/service/ngJwtAuthService.spec.ts b/src/service/ngJwtAuthService.spec.ts index 0044cd1..a8ac2ad 100644 --- a/src/service/ngJwtAuthService.spec.ts +++ b/src/service/ngJwtAuthService.spec.ts @@ -667,7 +667,6 @@ describe('Service tests', () => { let userToImpersonate = fixtures.userResponse; userToImpersonate.userId = 2; - userToImpersonate._self = '/users/2'; let expectedToken = fixtures.buildToken({ data: { From 4ef05c82b5f1ff3882822fd4c26f8d7d1b0a8c3c Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 16:37:53 +0100 Subject: [PATCH 09/13] Added build/dev webpack configs, updated package scripts to use webpack for compilation, removed gulpfile dependency on bower.json --- gulpfile.js | 3 +-- package.json | 3 ++- webpack/webpack.build.js | 30 ++++++++++++++++++++++++++++++ webpack/webpack.dev.js | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 webpack/webpack.build.js create mode 100644 webpack/webpack.dev.js diff --git a/gulpfile.js b/gulpfile.js index 3f3e455..cf61a02 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -22,7 +22,6 @@ var gulpCore = require('gulp'), gulp = plugins.help(gulpCore), _ = require('lodash'), path = require('path'), - bowerJson = require('./bower.json'), packageJson = require('./package.json') ; @@ -98,7 +97,7 @@ gulp.task('js:app', function () { target: "ES5", noExternalResolve: true, typescript: require('typescript'), - out: path.basename(bowerJson.main), + out: path.basename(packageJson.main), declarationFiles: true }, undefined, plugins.typescript.reporter.longReporter())); diff --git a/package.json b/package.json index 37b3f49..4df7cf1 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,9 @@ "url": "https://github.com/spira/angular-jwt-auth" }, "scripts": { - "build": "tsc --declaration --pretty --listFiles", + "start": "webpack --config webpack/webpack.dev.js --watch --NODE_ENV=dev", "test": "karma start --NODE_ENV=test", + "build": "webpack --config webpack/webpack.build.js --NODE_ENV=production", "postinstall": "typings i" }, "dependencies": { diff --git a/webpack/webpack.build.js b/webpack/webpack.build.js new file mode 100644 index 0000000..10f0f3b --- /dev/null +++ b/webpack/webpack.build.js @@ -0,0 +1,30 @@ +var loaders = require("./loaders"); +var webpack = require('webpack'); + +module.exports = { + entry: ['./src/index.ts'], + output: { + filename: 'ngJwtAuth.js', + path: 'dist' + }, + devtool: 'source-map', + resolve: { + root: __dirname, + extensions: ['', '.ts', '.js', '.json'] + }, + resolveLoader: { + modulesDirectories: ["node_modules"] + }, + plugins: [ + new webpack.optimize.UglifyJsPlugin( + { + warning: false, + mangle: true, + comments: false + } + ) + ], + module:{ + loaders: loaders + } +}; \ No newline at end of file diff --git a/webpack/webpack.dev.js b/webpack/webpack.dev.js new file mode 100644 index 0000000..dba6095 --- /dev/null +++ b/webpack/webpack.dev.js @@ -0,0 +1,34 @@ +var loaders = require("./loaders"); +var BrowserSyncPlugin = require('browser-sync-webpack-plugin'); +var HtmlWebpackPlugin = require('html-webpack-plugin'); +var webpack = require('webpack'); +module.exports = { + entry: ['./src/index.ts'], + output: { + filename: 'build.js', + path: 'dist' + }, + resolve: { + root: __dirname, + extensions: ['', '.ts', '.js', '.json'] + }, + resolveLoader: { + modulesDirectories: ["node_modules"] + }, + devtool: "source-map", + plugins: [ + new BrowserSyncPlugin({ + host: 'localhost', + port: 8080, + server: { + baseDir: 'dist' + }, + ui: false, + online: false, + notify: false + }) + ], + module:{ + loaders: loaders + } +}; \ No newline at end of file From 103cb1e62ce408340c5ecb347abcdd923f54e6c3 Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 17:59:21 +0100 Subject: [PATCH 10/13] Completed implementation of gulpfile to handle the new module pattern, ignored dist dir, implemented travis deployment with pr-bumper checker, reverted package name, removed redundant webpack configs, updated examples & readme --- .gitignore | 3 +- .travis.yml | 36 ++++++--- README.md | 112 ++++++++++++++-------------- examples/bower.json | 9 --- examples/example.ts | 105 ++++++++++++++++++++++++++ examples/index.html | 10 --- gulpfile.js | 88 ++++------------------ package.json | 19 ++--- src/index.ts | 5 ++ tsconfig.build.json | 12 +++ tsconfig.json => tsconfig.test.json | 0 webpack/webpack.build.js | 30 -------- webpack/webpack.dev.js | 34 --------- webpack/webpack.test.js | 3 + 14 files changed, 233 insertions(+), 233 deletions(-) delete mode 100644 examples/bower.json create mode 100644 examples/example.ts delete mode 100644 examples/index.html create mode 100644 tsconfig.build.json rename tsconfig.json => tsconfig.test.json (100%) delete mode 100644 webpack/webpack.build.js delete mode 100644 webpack/webpack.dev.js diff --git a/.gitignore b/.gitignore index 86f5796..1c9381c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ node_modules reports tmp .idea -typings \ No newline at end of file +typings +dist \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 77f351f..3c1487b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,23 +1,41 @@ -sudo: false #use container based infrastructure +sudo: false language: node_js node_js: - - "5.4.1" - +- 5.4.1 addons: apt: sources: - - libnotify-bin + - libnotify-bin cache: directories: - - node_modules + - node_modules + +branches: + except: + - /^v[0-9\.]+/ + +before_install: + - npm install -g pr-bumper + - pr-bumper check install: - - travis_retry npm install -g gulp - - travis_retry npm install +- travis_retry npm install -g gulp +- travis_retry npm install script: - - npm test +- npm test +- npm run build after_script: - - gulp coveralls +- gulp coveralls + +before_deploy: + - pr-bumper bump + +deploy: + provider: npm + on: + tags: true + api_key: + secure: aQCcMzb4VCbedVdkz75n7/hN+ovFz8iOKdApcA1VvyP2j/CudOyCbTr8BGB48K7YTs83ZYWeTSXSU/lC3/b8Z8C768nWW6gK9e15lx5+ENFBfMyRI5CY84z6AfW3dNB3vmUObKeEACSJGuchldKtPE1B2+Ysmw5h9qH9kEjoJpRxMalg2bSlbvA1ZMPjnLk4Mr0sOVPGtQaEtR7VZOmpQNxPfyTDEAFxZlMYjJOWFpH9987tkgyYmTI9n5J74zb8hQLwLEJ3D7GWOf/skJ37/IDOsqpncxOGGvqrvvC1uCJHAPm/Qx1vbrILv8bU5b08kfBP8Zbkf/4qfH/N7eeBu32CUU3yXCVh1WKW/eSeBwq7giP0YXPlEiFZrWVNdzJc2vmdR4ZihgTL2OOj+ThYIGhZWaJRhYUBOrJRYM5nhDkudOcDEylH3hLrLVZnzHJDrZ2yAtLyOfqRmHLTwITTEMO+RvzD5oPoYX69ZJ6EBn18Fr6LHlM1Xo3WlwuXugdC76fUM1UxtmW0OKNROCXF+zUHxc8lOBBHLhsI1pLR5R/khj1zuQwhYp5YL+ly2lxWhCR9DSySBWbbW4Yj7m8e0Sg7gKkcvx9JTzHSkcWfnvRJDXDk0FMZF9S71ldBwgPH2s9FjjU4lXMf0PglvTcJbQIxT/byMZCEnarFb3Fqe5s= diff --git a/README.md b/README.md index 7f89a77..3826f66 100644 --- a/README.md +++ b/README.md @@ -19,25 +19,30 @@ The module has the following features ## Installation -Install through bower: +Install through npm: ```sh -bower install angular-jwt-auth --save +npm install angular-jwt-auth --save ``` ## Usage * Require the `ngJwtAuth` module in your angular application -```js +```ts +import "angular" +import "angular-jwt-auth" angular.module('app', ['ngJwtAuth']) ``` * (Optionally) configure the service provider -```js +```ts + +import {NgJwtAuthServiceProvider} from "angular-jwt-auth" + angular.module('app', ['ngJwtAuth']) -.config(['ngJwtAuthServiceProvider', function(ngJwtAuthServiceProvider){ +.config(['ngJwtAuthServiceProvider', function(ngJwtAuthServiceProvider:NgJwtAuthServiceProvider){ ngJwtAuthServiceProvider .configure({ tokenLocation: 'token-custom', @@ -60,7 +65,7 @@ It is _highly_ recommended that you register a login prompt factory (See below), this will allow the interceptor to prompt your users for their login details when an api request that returns status code 401. -```js +```ts angular.module('app', ['ngJwtAuth']) .run(['ngJwtAuthService', function(ngJwtAuthService){ ngJwtAuthService.init(); @@ -96,77 +101,72 @@ Full typescript example from the [Spira](https://github.com/spira/spira) project Note this example is in typescript, but it is the same process in plain javascript. ```ts -namespace app.guest.login { + + namespace app.guest.login { export const namespace = 'app.guest.login'; class LoginConfig { - static $inject = ['ngJwtAuthServiceProvider']; - - constructor(private ngJwtAuthServiceProvider:NgJwtAuth.NgJwtAuthServiceProvider) { - - let config:NgJwtAuth.INgJwtAuthServiceConfig = { - refreshBeforeSeconds: 60 * 10, //10 mins - checkExpiryEverySeconds: 60, //1 min - apiEndpoints: { - base: '/api/auth/jwt', - login: '/login', - tokenExchange: '/token', - refresh: '/refresh', - }, - }; - - ngJwtAuthServiceProvider.configure(config); - + static $inject:string[] = ['ngJwtAuthServiceProvider',]; + constructor(private ngJwtAuthServiceProvider:NgJwtAuthServiceProvider) { + + ngJwtAuthServiceProvider + .configure({ + tokenLocation: 'token-custom', + apiEndpoints: { + base: '/api', + login: '/login-custom', + tokenExchange: '/token-custom', + refresh: '/refresh-custom', + } + }); + } } - export class LoginController { - - public socialLogin; - + class LoginController { + static $inject = ['$rootScope', '$mdDialog', '$mdToast', 'ngJwtAuthService', 'deferredCredentials', 'loginSuccess', 'userService']; - constructor(private $rootScope:global.IRootScope, private $mdDialog:ng.material.IDialogService, private $mdToast:ng.material.IToastService, - private ngJwtAuthService:NgJwtAuth.NgJwtAuthService, + private ngJwtAuthService:NgJwtAuthService, private deferredCredentials:ng.IDeferred, private loginSuccess:{promise:ng.IPromise}, private userService:common.services.user.UserService) { - + this.handleLoginSuccessPromise(); - + } - + /** * Register the login success promise handler */ private handleLoginSuccessPromise() { - + //register error handling and close on success this.loginSuccess.promise .then( - (user) => this.$mdDialog.hide(user), //on success hide the dialog, pass through the returned user object - null, - (err:Error) => { - if (err instanceof NgJwtAuth.NgJwtAuthCredentialsFailedException) { - this.$mdToast.show( - (this.$mdToast).simple() - .hideDelay(2000) - .position('top') - .content(err.message) - .parent('#loginDialog') - ); - } else { - console.error(err); + (user) => this.$mdDialog.hide(user), //on success hide the dialog, pass through the returned user object + null, + (err:Error) => { + if (err instanceof NgJwtAuthCredentialsFailedException) { + this.$mdToast.show( + (this.$mdToast).simple() + .hideDelay(2000) + .position('top') + .content(err.message) + .parent('#loginDialog') + ); + } else { + console.error(err); + } } - } - ); + ); } - + /** * allow the user to manually close the dialog */ @@ -174,23 +174,23 @@ namespace app.guest.login { this.ngJwtAuthService.logout(); //make sure the user is logged out this.$mdDialog.cancel('closed'); } - + /** * Attempt login * @param username * @param password */ public login(username, password) { - - let credentials:NgJwtAuth.ICredentials = { + + let credentials:ICredentials = { username: username, password: password, }; - + this.deferredCredentials.notify(credentials); //resolve the deferred credentials with the passed creds - + } - + } angular.module(namespace, []) diff --git a/examples/bower.json b/examples/bower.json deleted file mode 100644 index 8fd1e51..0000000 --- a/examples/bower.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "test", - "description": "testing our component", - "main": "index.html", - "private": true, - "dependencies": { - "angular-jwt-auth": "~0.0.0" - } -} diff --git a/examples/example.ts b/examples/example.ts new file mode 100644 index 0000000..197f0be --- /dev/null +++ b/examples/example.ts @@ -0,0 +1,105 @@ +/** + * This is an example of all the base features of the ngJwtAuth service. + * @todo A full demo running in github.io would be preferred + */ +import "angular" +import "angular-material" + +// import {NgJwtAuthServiceProvider} from "angular-jwt-auth" +import {NgJwtAuthServiceProvider} from "../dist" +import {NgJwtAuthCredentialsFailedException} from "../src/provider/ngJwtAuthServiceProvider"; +import {NgJwtAuthService} from "../src/service/ngJwtAuthService"; +import {ICredentials} from "../src/ngJwtAuthInterfaces"; + +class ExampleConfig { + + static $inject:string[] = ['ngJwtAuthServiceProvider',]; + constructor(private ngJwtAuthServiceProvider:NgJwtAuthServiceProvider) { + + ngJwtAuthServiceProvider + .configure({ + tokenLocation: 'token-custom', + apiEndpoints: { + base: '/api', + login: '/login-custom', + tokenExchange: '/token-custom', + refresh: '/refresh-custom', + } + }); + + } + +} + +class ExampleController { + + static $inject = ['$rootScope', '$mdDialog', '$mdToast', 'ngJwtAuthService', 'deferredCredentials', 'loginSuccess', 'userService']; + constructor(private $rootScope:global.IRootScope, + private $mdDialog:ng.material.IDialogService, + private $mdToast:ng.material.IToastService, + private ngJwtAuthService:NgJwtAuthService, + private deferredCredentials:ng.IDeferred, + private loginSuccess:{promise:ng.IPromise}, + private userService:common.services.user.UserService) { + + this.handleLoginSuccessPromise(); + + } + + /** + * Register the login success promise handler + */ + private handleLoginSuccessPromise() { + + //register error handling and close on success + this.loginSuccess.promise + .then( + (user) => this.$mdDialog.hide(user), //on success hide the dialog, pass through the returned user object + null, + (err:Error) => { + if (err instanceof NgJwtAuthCredentialsFailedException) { + this.$mdToast.show( + (this.$mdToast).simple() + .hideDelay(2000) + .position('top') + .content(err.message) + .parent('#loginDialog') + ); + } else { + console.error(err); + } + } + ); + } + + /** + * allow the user to manually close the dialog + */ + public cancelLoginDialog() { + this.ngJwtAuthService.logout(); //make sure the user is logged out + this.$mdDialog.cancel('closed'); + } + + /** + * Attempt login + * @param username + * @param password + */ + public login(username, password) { + + let credentials:ICredentials = { + username: username, + password: password, + }; + + this.deferredCredentials.notify(credentials); //resolve the deferred credentials with the passed creds + + } + +} + +angular.module('example', [ + 'ngJwtAuth', + ]) + .config(ExampleConfig) + .controller('ExampleController', ExampleController); \ No newline at end of file diff --git a/examples/index.html b/examples/index.html deleted file mode 100644 index c89ac98..0000000 --- a/examples/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/gulpfile.js b/gulpfile.js index cf61a02..3c5e850 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -21,92 +21,39 @@ var gulpCore = require('gulp'), }), gulp = plugins.help(gulpCore), _ = require('lodash'), - path = require('path'), - packageJson = require('./package.json') - ; + path = require('path') +; -var tsDefinitions = './typings/**/*.d.ts'; +var tsDefinitions = './typings/browser/**/*.d.ts'; var sources = { - tsd: './typings/**/*.d.ts', app: { - ts: [tsDefinitions, './src/**/*.ts'] - }, - test: { - ts: [tsDefinitions, './test/**/*.ts'] + ts: [tsDefinitions, './src/**/*.ts', '!**/*.spec.ts', '!src/test.ts'] } }; var destinations = { app: './dist', - testTmp: './test/tmp', coverage: 'reports/**/lcov.info' }; -gulp.task('test', 'runs test sequence for frontend', function (cb) { - return plugins.runSequence('clean', 'js:app', 'js:test', 'test:karma', cb); -}); - -gulp.task('js:test', function () { - - var tsResult = gulp.src(sources.test.ts) - .pipe(plugins.typescript({ - target: "ES5", - typescript: require('typescript') - })); - - return tsResult.js.pipe(gulp.dest(destinations.testTmp)) -}); - -gulp.task('test:karma', function () { +gulp.task('typescript', function () { - var vendorFiles = plugins.mainBowerFiles({ - includeDev: true, - paths: { - bowerDirectory: 'bower_components', - bowerJson: 'bower.json' - } + var tsProject = plugins.typescript.createProject('tsconfig.build.json', { + declarationFiles: true, + noExternalResolve: true }); - vendorFiles = vendorFiles.map(function (path) { - return path.replace(/\\/g, "\/").replace(/^.+bower_components\//i, './bower_components/'); - }); - - var testFiles = [].concat( - vendorFiles, destinations.testTmp + '**/*.js', destinations.app + '**/*.js' - ); - - gulp.src(testFiles) - .pipe(plugins.karma({ - configFile: 'karma.conf.js', - action: 'run' - })) - .on('error', function (err) { - // Make sure failed tests cause gulp to exit non-zero - throw err; - }); - -}); - -gulp.task('js:app', function () { - - var tsResult = gulp.src(sources.app.ts) + var tsStream = gulp.src(sources.app.ts) .pipe(plugins.sourcemaps.init()) - .pipe(plugins.typescript({ - target: "ES5", - noExternalResolve: true, - typescript: require('typescript'), - out: path.basename(packageJson.main), - declarationFiles: true - }, undefined, plugins.typescript.reporter.longReporter())); + .pipe(plugins.typescript(tsProject, undefined, plugins.typescript.reporter.longReporter())); return plugins.merge2([ - tsResult.dts - .pipe(plugins.replace(' Date: Wed, 6 Apr 2016 18:13:54 +0100 Subject: [PATCH 11/13] Added github token for pr-checker --- .travis.yml | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3c1487b..b1bce90 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,36 +6,31 @@ addons: apt: sources: - libnotify-bin - cache: directories: - node_modules - branches: except: - - /^v[0-9\.]+/ - + - "/^v[0-9\\.]+/" before_install: - - npm install -g pr-bumper - - pr-bumper check - +- npm install -g pr-bumper +- pr-bumper check install: - travis_retry npm install -g gulp - travis_retry npm install - script: - npm test - npm run build - after_script: - gulp coveralls - before_deploy: - - pr-bumper bump - +- pr-bumper bump deploy: provider: npm on: tags: true api_key: secure: aQCcMzb4VCbedVdkz75n7/hN+ovFz8iOKdApcA1VvyP2j/CudOyCbTr8BGB48K7YTs83ZYWeTSXSU/lC3/b8Z8C768nWW6gK9e15lx5+ENFBfMyRI5CY84z6AfW3dNB3vmUObKeEACSJGuchldKtPE1B2+Ysmw5h9qH9kEjoJpRxMalg2bSlbvA1ZMPjnLk4Mr0sOVPGtQaEtR7VZOmpQNxPfyTDEAFxZlMYjJOWFpH9987tkgyYmTI9n5J74zb8hQLwLEJ3D7GWOf/skJ37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5fuVXDyzmLCV51CX8mmqT4X29Ck= From 1fe58369a8c22373857e7895d9e4d0861f0497ef Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 18:19:08 +0100 Subject: [PATCH 12/13] #MAJOR# Finalised module release with update to readme and version bump directive in commit --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3826f66..b8d9e0a 100644 --- a/README.md +++ b/README.md @@ -101,8 +101,7 @@ Full typescript example from the [Spira](https://github.com/spira/spira) project Note this example is in typescript, but it is the same process in plain javascript. ```ts - - namespace app.guest.login { +namespace app.guest.login { export const namespace = 'app.guest.login'; @@ -201,4 +200,5 @@ Note this example is in typescript, but it is the same process in plain javascri ``` ## Todo -Better documentation with examples in javascript. +* Better documentation with examples in typescript. +* Site hosted on github showing off examples with material \ No newline at end of file From 2890a5a5afcf213479562352b122ec6e447278d0 Mon Sep 17 00:00:00 2001 From: Zak Henry Date: Wed, 6 Apr 2016 18:27:37 +0100 Subject: [PATCH 13/13] Excluded examples from test tsconfig to avoid compiler errors --- tsconfig.test.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tsconfig.test.json b/tsconfig.test.json index af7e937..100c4e4 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -15,7 +15,8 @@ "dev", "typings/main.d.ts", "typings/main", - "reports" + "reports", + "examples" ], "version": "1.8.9" } \ No newline at end of file