diff --git a/angular-mocks/angular-mocks-tests.ts b/angular-mocks/angular-mocks-tests.ts index 8ea42e4122..cabbf7c578 100644 --- a/angular-mocks/angular-mocks-tests.ts +++ b/angular-mocks/angular-mocks-tests.ts @@ -118,6 +118,7 @@ httpBackendService.flush(); httpBackendService.flush(1234); httpBackendService.resetExpectations(); httpBackendService.verifyNoOutstandingExpectation(); +httpBackendService.verifyNoOutstandingExpectation(false); httpBackendService.verifyNoOutstandingRequest(); requestHandler = httpBackendService.expect('GET', 'http://test.local'); diff --git a/angular-mocks/index.d.ts b/angular-mocks/index.d.ts index ddded4d0a8..8b94fab445 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -132,8 +132,9 @@ declare module 'angular' { /** * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. + * @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code. */ - verifyNoOutstandingExpectation(): void; + verifyNoOutstandingExpectation(digest?: boolean): void; /** * Verifies that there are no outstanding requests that need to be flushed. diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index 1a4841ab8c..cca4dfc420 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -271,18 +271,28 @@ angular.module('qprovider-test', []) let foo: ng.IPromise; foo.then((x) => { // x is inferred to be a number + x.toFixed(); return 'asdf'; }).then((x) => { // x is inferred to be string const len = x.length; return 123; +}, (e) => { + return anyOf2([123], toPromise([123])); // IPromise | T, both are good for the 2nd arg of .then() }).then((x) => { - // x is infered to be a number - const fixed = x.toFixed(); + // x is infered to be a number or number[] + if (Array.isArray(x)) { + x[0].toFixed(); + } else { + x.toFixed(); + } return; -}).then((x) => { - // x is infered to be void - // Typescript will prevent you to actually use x as a local variable +}).catch(e => { + return foo || 123; // IPromise | T, both are good for .catch() +}).then(x => { + // x is infered to be void | number + x && x.toFixed(); + // Typescript will prevent you to actually use x as a local variable before you check it is not void // Try object: return { a: 123 }; }).then((x) => { @@ -290,7 +300,8 @@ foo.then((x) => { x.a = 123; //Try a promise var y: ng.IPromise; - return y; + var condition: boolean; + return condition ? y : x.a; // IPromise | T, both are good for the 1st arg of .then() }).then((x) => { // x is infered to be a number, which is the resolved value of a promise x.toFixed(); @@ -307,14 +318,22 @@ namespace TestQ { e: number; f: boolean; } + interface TOther { + g: string; + h: number; + } var tResult: TResult; var promiseTResult: angular.IPromise; var tValue: TValue; var promiseTValue: angular.IPromise; + var tOther: TOther; + var promiseTOther: angular.IPromise; var $q: angular.IQService; var promiseAny: angular.IPromise; + const assertPromiseType = (arg: angular.IPromise) => arg; + // $q constructor { let result: angular.IPromise; @@ -349,13 +368,20 @@ namespace TestQ { { let result: angular.IDeferred; result = $q.defer(); + result.resolve(tResult); + var anyValue: any; + result.reject(anyValue); + result.promise.then(result => { + return $q.resolve(result); + }); } // $q.reject { - let result: angular.IPromise; + let result: angular.IPromise; result = $q.reject(); result = $q.reject(''); + result.catch(() => 5).then(x => x.toFixed()); } // $q.resolve @@ -367,6 +393,8 @@ namespace TestQ { let result: angular.IPromise; result = $q.resolve(tResult); result = $q.resolve(promiseTResult); + result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); + result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); } // $q.when @@ -376,6 +404,8 @@ namespace TestQ { } { let result: angular.IPromise; + let resultOther: angular.IPromise; + result = $q.when(tResult); result = $q.when(promiseTResult); @@ -384,16 +414,20 @@ namespace TestQ { result = $q.when(tValue, (result: TValue) => tResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => tResult); - result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => promiseTResult); - result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther, (any) => any); } } @@ -466,20 +500,26 @@ namespace TestInjector { // Promise signature tests namespace TestPromise { - let result: any; var any: any; interface TResult { + kind: 'result'; a: number; b: string; c: boolean; } + interface TOther { + kind: 'other'; d: number; e: string; f: boolean; } + function isTResult(x: TResult | TOther): x is TResult { + return x.kind === 'result'; + } + var tresult: TResult; var tresultPromise: ng.IPromise; var tresultHttpPromise: ng.IHttpPromise; @@ -489,45 +529,83 @@ namespace TestPromise { var totherHttpPromise: ng.IHttpPromise; var promise: angular.IPromise; + var $q: angular.IQService; + + const assertPromiseType = (arg: angular.IPromise) => arg; + const reject = $q.reject(); // promise.then - result = promise.then((result) => any) as angular.IPromise; - result = promise.then((result) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => any, (any) => any, (any) => any) as angular.IPromise; + assertPromiseType(promise.then((result) => any)); + assertPromiseType(promise.then((result) => any, (any) => any)); + assertPromiseType(promise.then((result) => any, (any) => any, (any) => any)); - result = promise.then((result) => result) as angular.IPromise; - result = promise.then((result) => result, (any) => any) as angular.IPromise; - result = promise.then((result) => result, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => tresultPromise) as angular.IPromise; - result = promise.then((result) => tresultPromise, (any) => any) as angular.IPromise; - result = promise.then((result) => tresultPromise, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => tresultHttpPromise) as angular.IPromise>; - result = promise.then((result) => tresultHttpPromise, (any) => any) as angular.IPromise>; - result = promise.then((result) => tresultHttpPromise, (any) => any, (any) => any) as angular.IPromise>; + assertPromiseType(promise.then((result) => reject)); + assertPromiseType(promise.then((result) => reject, (any) => reject)); + assertPromiseType(promise.then((result) => reject, (any) => reject, (any) => any)); - result = promise.then((result) => tother) as angular.IPromise; - result = promise.then((result) => tother, (any) => any) as angular.IPromise; - result = promise.then((result) => tother, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => totherPromise) as angular.IPromise; - result = promise.then((result) => totherPromise, (any) => any) as angular.IPromise; - result = promise.then((result) => totherPromise, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => totherHttpPromise) as angular.IPromise>; - result = promise.then((result) => totherHttpPromise, (any) => any) as angular.IPromise>; - result = promise.then((result) => totherHttpPromise, (any) => any, (any) => any) as angular.IPromise>; + assertPromiseType(promise.then((result) => result)); + assertPromiseType(promise.then((result) => tresult)); + assertPromiseType(promise.then((result) => tresultPromise)); + assertPromiseType(promise.then((result) => result, (any) => any)); + assertPromiseType(promise.then((result) => result, (any) => any, (any) => any)); + assertPromiseType(promise.then((result) => result, (any) => reject, (any) => any)); + + assertPromiseType(promise.then((result) => anyOf2(reject, result))); + assertPromiseType(promise.then((result) => anyOf3(result, tresultPromise, reject))); + assertPromiseType(promise.then( + (result) => anyOf3(reject, result, tresultPromise), + (reason) => anyOf3(reject, tresult, tresultPromise) + )); + + + assertPromiseType>(promise.then((result) => tresultHttpPromise)); + + assertPromiseType(promise.then((result) => result, (any) => tother)); + assertPromiseType(promise.then( + (result) => anyOf3(reject, result, totherPromise), + (reason) => anyOf3(reject, tother, tresultPromise) + )); + + assertPromiseType(promise.then( + (result) => anyOf3(tresultPromise, result, totherPromise) + )); + + assertPromiseType(promise.then((result) => result, (any) => tother, (any) => any)); + assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise)); + assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise, (any) => any)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise, (any) => any)); + + assertPromiseType(promise.then((result) => tother)); + assertPromiseType(promise.then((result) => tother, (any) => any)); + assertPromiseType(promise.then((result) => tother, (any) => any, (any) => any)); + assertPromiseType(promise.then((result) => totherPromise)); + assertPromiseType(promise.then((result) => totherPromise, (any) => any)); + assertPromiseType(promise.then((result) => totherPromise, (any) => any, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any, (any) => any)); + + assertPromiseType(promise.then((result) => tresult, (any) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); // promise.catch - result = promise.catch((err) => any) as angular.IPromise; - result = promise.catch((err) => tresult) as angular.IPromise; - result = promise.catch((err) => tresultPromise) as angular.IPromise; - result = promise.catch((err) => tresultHttpPromise) as angular.IPromise>; - result = promise.catch((err) => tother) as angular.IPromise; - result = promise.catch((err) => totherPromise) as angular.IPromise; - result = promise.catch((err) => totherHttpPromise) as angular.IPromise>; + assertPromiseType(promise.catch((err) => err)); + assertPromiseType(promise.catch((err) => any)); + assertPromiseType(promise.catch((err) => tresult)); + assertPromiseType(promise.catch((err) => anyOf2(tresult, reject))); + assertPromiseType(promise.catch((err) => anyOf3(tresult, tresultPromise, reject))); + assertPromiseType(promise.catch((err) => tresultPromise)); + assertPromiseType>(promise.catch((err) => tresultHttpPromise)); + assertPromiseType(promise.catch((err) => tother)); + assertPromiseType(promise.catch((err) => totherPromise)); + assertPromiseType>(promise.catch((err) => totherHttpPromise)); + + assertPromiseType(promise.catch((err) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); // promise.finally - result = promise.finally(() => any) as angular.IPromise; - result = promise.finally(() => tresult) as angular.IPromise; - result = promise.finally(() => tother) as angular.IPromise; + assertPromiseType(promise.finally(() => any)); + assertPromiseType(promise.finally(() => tresult)); + assertPromiseType(promise.finally(() => tother)); } function test_angular_forEach() { @@ -1212,3 +1290,17 @@ function testIHttpParamSerializerJQLikeProvider() { a: 'b' }); } + +function anyOf2(v1: T1, v2: T2) { + return Math.random() < 1/2 ? v1 : v2; +} + +function anyOf3(v1: T1, v2: T2, v3: T3) { + const rnd = Math.random(); + return rnd < 1/3 ? v1 : rnd < 2/3 ? v2 : v3; +} + +function toPromise(val: T): ng.IPromise { + var p: ng.IPromise; + return p; +} diff --git a/angular/index.d.ts b/angular/index.d.ts index 3f094f3185..73535e9922 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -1044,13 +1044,14 @@ declare namespace angular { * * @param reason Constant, message, exception or an object representing the rejection reason. */ - reject(reason?: any): IPromise; + 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 */ resolve(value: IPromise|T): IPromise; + resolve(value: IPromise|T2): 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. */ @@ -1061,7 +1062,10 @@ declare namespace angular { * @param value Value or a promise */ when(value: IPromise|T): IPromise; - when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + when(value: IPromise|T2): IPromise; + when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult): IPromise; + when(value: T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: null | undefined | ((reason: any) => any), notifyCallback?: (state: any) => any): IPromise; + when(value: IPromise, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: (reason: any) => TResult2 | IPromise, notifyCallback?: (state: any) => 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. */ @@ -1090,15 +1094,20 @@ declare namespace angular { 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. - * The successCallBack may return IPromise for when a $q.reject() needs to be returned + * The successCallBack may return IPromise for when a $q.reject() needs to be returned * 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) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise; + + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: (reason: any) => IPromise|TCatch, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback: (reason: any) => IPromise|TCatch2, notifyCallback?: (state: any) => any): IPromise; /** * Shorthand for promise.then(null, errorCallback) */ - catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + catch(onRejected: (reason: any) => IPromise|TCatch): IPromise; + catch(onRejected: (reason: any) => IPromise|TCatch2): 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. diff --git a/archiver/index.d.ts b/archiver/index.d.ts index ea117239ac..665624143e 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -31,7 +31,6 @@ declare namespace archiver { } export interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; append(source: STREAM.Readable | Buffer | string, name: nameInterface): void; directory(dirpath: string, destpath: nameInterface | string): void; diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts index 197256ddd5..68d4e1797b 100644 --- a/auth0-js/auth0-js-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,23 +1,151 @@ /// -var auth0 = new Auth0({ +let webAuth = new auth0.WebAuth({ domain: 'mine.auth0.com', - clientID: 'dsa7d77dsa7d7', - callbackURL: 'http://my-app.com/callback', - callbackOnLocationHash: true + clientID: 'dsa7d77dsa7d7' }); -auth0.login({ - connection: 'google-oauth2', - popup: true, - popupOptions: { - width: 450, - height: 800 +webAuth.authorize({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + responseType: 'token', + redirectUri: 'https://example.com/auth/callback' +}); + +webAuth.parseHash(window.location.hash, (err, authResult) => { + if (err) { + return console.log(err); } -}, (err, profile, idToken, accessToken, state) => { - if (err) { - alert("something went wrong: " + err.message); - return; - } - alert('hello ' + profile.name); + + // The contents of authResult depend on which authentication parameters were used. + // It can include the following: + // authResult.accessToken - access token for the API specified by `audience` + // authResult.expiresIn - string with the access token's expiration time in seconds + // authResult.idToken - ID token JWT containing user profile information + + webAuth.client.userInfo(authResult.accessToken, (err, user) => { + // Now you have the user's information }); +}); + +webAuth.renewAuth({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback', + + // this will use postMessage to comunicate between the silent callback + // and the SPA. When false the SDK will attempt to parse the url hash + // should ignore the url hash and no extra behaviour is needed. + usePostMessage: true +}, function (err, authResult) { + // Renewed tokens or error +}); + +webAuth.changePassword({connection: 'the_connection', + email: 'me@example.com', + password: '123456' +}, (err) => {}); + +webAuth.passwordlessStart({ + connection: 'the_connection', + email: 'me@example.com', + send: 'code' +}, (err, data) => {}); + +webAuth.signupAndAuthorize({ + connection: 'the_connection', + email: 'me@example.com', + password: '123456', + scope: 'openid' +}, function (err, data) { + +}); + + + +webAuth.client.login({ + ealm: 'Username-Password-Authentication', //connection name or HRD domain + username: 'info@auth0.com', + password: 'areallystrongpassword', + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', +}, function(err, authResult) { + // Auth tokens in the result or an error +}); + +let authentication = new auth0.Authentication({ + domain: 'me.auth0.com', + clientID: '...', + redirectUri: 'http://page.com/callback', + responseType: 'code', + _sendTelemetry: false +}); + +authentication.buildAuthorizeUrl({state:'1234'}); +authentication.buildAuthorizeUrl({ + responseType: 'token', + redirectUri: 'http://anotherpage.com/callback2', + prompt: 'none', + state: '1234', + connection_scope: 'scope1,scope2' +}); + +authentication.buildLogoutUrl('asdfasdfds'); +authentication.buildLogoutUrl(); +authentication.userInfo('abcd1234', (err, data) => { + //user info retrieved +}); + +authentication.delegation({ + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + refresh_token: 'your_refresh_token', + api_type: 'app' +}, (err, data) => { + +}); + +authentication.loginWithDefaultDirectory({ + username: 'someUsername', + password: '123456' +}, (err, data) => { + +}); + +authentication.oauthToken({ + username: 'someUsername', + password: '123456', + grantType: 'password' +}, (err, data) => { + +}); + +authentication.getUserCountry((err, data) => { + +}); + +authentication.getSSOData(); +authentication.getSSOData(true, (err, data) => {}); + +authentication.dbConnection.signup({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); +authentication.dbConnection.changePassword({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); + +authentication.passwordless.start({ connection: 'bla', send: 'blabla' }, () => {}); +authentication.passwordless.verify({ connection: 'bla', send: 'link', verificationCode: 'asdfasd', email: 'me@example.com' }, () => {}); + +authentication.loginWithResourceOwner({ + username: 'the username', + password: 'the password', + connection: 'the_connection', + scope: 'openid' +}, (err, data) => {}); + +let management = new auth0.Management({ + domain: 'me.auth0.com', + token: 'token' +}); + +management.getUser('asd', (err, user) => {}); + +management.patchUserMetadata('asd', {role: 'admin'}, (err, user) => {}); + +management.linkUser('asd', 'eqwe', (err, user) => {}); diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index bd97fed1cc..0a0e004303 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -1,136 +1,456 @@ -// Type definitions for Auth0.js +// Type definitions for Auth0.js v8.1.3 // Project: https://github.com/auth0/auth0.js -// Definitions by: Robert McLaws +// Definitions by: Adrian Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** Extensions to the browser Window object. */ -interface Window { - /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ - token: string; -} - -/** This is the interface for the main Auth0 client. */ -interface Auth0Static { - - new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; - decodeJwt(jwt: string): any; - login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; - loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - logout(query: string): void; - getConnections(callback?: Function): void; - refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; - parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; - validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; -} - -/** Represents constructor options for the Auth0 client. */ -interface Auth0ClientOptions { - clientID: string; - callbackURL: string; - callbackOnLocationHash?: boolean; - responseType?: string; - domain: string; - forceJSONP?: boolean; -} - -/** Represents a normalized UserProfile. */ -interface Auth0UserProfile { - email: string; - email_verified: boolean; - family_name: string; - gender: string; - given_name: string; - locale: string; - name: string; - nickname: string; - picture: string; - user_id: string; - /** Represents one or more Identities that may be associated with the User. */ - identities: Auth0Identity[]; - user_metadata?: any; - app_metadata?: any; -} - -/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ -interface MicrosoftUserProfile extends Auth0UserProfile { - emails: string[]; -} - -/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ -interface Office365UserProfile extends Auth0UserProfile { - tenantid: string; - upn: string; -} - -/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ -interface AdfsUserProfile extends Auth0UserProfile { - issuer: string; -} - -/** Represents multiple identities assigned to a user. */ -interface Auth0Identity { - access_token: string; - connection: string; - isSocial: boolean; - provider: string; - user_id: string; -} - -interface Auth0DecodedHash { - access_token: string; - idToken: string; - profile: Auth0UserProfile; - state: any; - error: string; -} - -interface Auth0PopupOptions { - width: number; - height: number; -} - -interface Auth0LoginOptions { - auto_login?: boolean; - responseType?: string; - connection?: string; - email?: string; - username?: string; - password?: string; - popup?: boolean; - popupOptions?: Auth0PopupOptions; -} - -interface Auth0SignupOptions extends Auth0LoginOptions { - auto_login: boolean; -} - -interface Auth0Error { - code: any; - details: any; - name: string; - message: string; - status: any; -} - -/** Represents the response from an API Token Delegation request. */ -interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - expires_in: string; - /** The JWT for delegated access. */ - id_token: string; - /** The type of token being returned. Possible values: "Bearer" */ - token_type: string; -} - -declare const Auth0: Auth0Static; - -declare module "auth0-js" { - export = Auth0 +declare namespace auth0 { + + export class Authentication { + constructor(options: AuthOptions); + + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; + + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; + + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; + + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + * @deprecated `delegation` will be soon deprecated. + */ + delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; + } + + export class PasswordlessAuthentication { + constructor(request: any, option: any); + + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; + + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: any): void; + } + + export class DBConnection { + constructor(request: any, option: any); + + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: any): void; + + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: any): void; + } + + export class Management { + constructor(options: ManagementOptions); + + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; + } + + export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; + + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; + + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: any): void; + + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: any): void; + + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; + + passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; + + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + } + + export class Redirect { + constructor(client: any, options: any); + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + export class Popup { + constructor(client: any, options: any); + + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; + + /** + * Internal use. + * + * @method getPopupHandler + */ + getPopupHandler(options: any, preload: boolean): any; + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: any): void; + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; + } + + interface Auth0Error { + error: any; + errorDescription: string + } + + interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; + } + + /** Represents the response from an API Token Delegation request. */ + interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + ExpiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; + } + + interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; + } + + interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string, + authParams?: any; + } + + interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; + } + } diff --git a/auth0-js/v7/auth0-js-tests.ts b/auth0-js/v7/auth0-js-tests.ts new file mode 100644 index 0000000000..d5ca0250d4 --- /dev/null +++ b/auth0-js/v7/auth0-js-tests.ts @@ -0,0 +1,22 @@ +/// +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0-js/v7/index.d.ts b/auth0-js/v7/index.d.ts new file mode 100644 index 0000000000..ee834d5c61 --- /dev/null +++ b/auth0-js/v7/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for Auth0.js v7.x +// Project: https://github.com/auth0/auth0.js +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: Function): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: Function): void; + refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: Function): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: Function): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: Function): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLocationHash?: boolean; + responseType?: string; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + email_verified: boolean; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + idToken: string; + profile: Auth0UserProfile; + state: any; + error: string; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + responseType?: string; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare const Auth0: Auth0Static; + +declare module "auth0-js" { + export = Auth0 +} diff --git a/auth0-js/v7/tsconfig.json b/auth0-js/v7/tsconfig.json new file mode 100644 index 0000000000..7413e97f44 --- /dev/null +++ b/auth0-js/v7/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "auth0-js": [ + "auth0-js/v7" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "auth0-js-tests.ts" + ] +} diff --git a/auth0-lock/auth0-lock-tests.ts b/auth0-lock/auth0-lock-tests.ts index deb046f3e7..4b72edcfa1 100644 --- a/auth0-lock/auth0-lock-tests.ts +++ b/auth0-lock/auth0-lock-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts index fc9a047115..09c3f4fedd 100644 --- a/auth0-lock/index.d.ts +++ b/auth0-lock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index ec5502ca7e..6277d4cc3a 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,4 +1,4 @@ -/// +/// var widget: Auth0WidgetStatic = new Auth0Widget({ diff --git a/auth0.widget/index.d.ts b/auth0.widget/index.d.ts index 1c30d83b6f..cdefd9e0fd 100644 --- a/auth0.widget/index.d.ts +++ b/auth0.widget/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0WidgetStatic { diff --git a/bufferstream/index.d.ts b/bufferstream/index.d.ts index ab048e437f..1d1ffcdb10 100644 --- a/bufferstream/index.d.ts +++ b/bufferstream/index.d.ts @@ -58,7 +58,7 @@ declare class BufferStream extends stream.Duplex { shortcut for buffer.length */ length: number; -} +} // https://github.com/dodo/node-bufferstream/blob/master/src/buffer-stream.coffee#L28 declare namespace BufferStream { export interface Opts { diff --git a/cron/index.d.ts b/cron/index.d.ts index e962a9eb27..d4fa027c93 100644 --- a/cron/index.d.ts +++ b/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.0.9 +// Type definitions for cron 1.2 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,9 +6,9 @@ interface CronJobStatic { - new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob; + new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean): CronJob; new (options: { - cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any + cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any; runOnInit?: boolean }): CronJob; } interface CronJob { diff --git a/d3-hierarchy/d3-hierarchy-tests.ts b/d3-hierarchy/d3-hierarchy-tests.ts index ce7354afe3..7079fae827 100644 --- a/d3-hierarchy/d3-hierarchy-tests.ts +++ b/d3-hierarchy/d3-hierarchy-tests.ts @@ -125,6 +125,13 @@ hierarchyRootNode = hierarchyRootNode.sum(function (d) { return d.val; }); num = hierarchyRootNode.value; +// count() and value ---------------------------------------------------------- + +hierarchyRootNode = hierarchyRootNode.count(); + +num = hierarchyRootNode.value; + + // sort --------------------------------------------------------------------- hierarchyRootNode = hierarchyRootNode.sort(function (a, b) { @@ -307,6 +314,12 @@ clusterRootNode = clusterRootNode.sum(function (d) { return d.val; }); num = clusterRootNode.value; +// count() and value ---------------------------------------------------------- + +clusterRootNode = clusterRootNode.count(); + +num = clusterRootNode.value; + // sort --------------------------------------------------------------------- clusterRootNode = clusterRootNode.sort(function (a, b) { @@ -584,6 +597,11 @@ treemapRootNode = treemapRootNode.sum(function (d) { return d.val; }); num = treemapRootNode.value; +// count() and value ---------------------------------------------------------- + +treemapRootNode = treemapRootNode.count(); + +num = treemapRootNode.value; // sort --------------------------------------------------------------------- treemapRootNode = treemapRootNode.sort(function (a, b) { @@ -766,6 +784,11 @@ packRootNode = packRootNode.sum(function (d) { return d.val; }); num = packRootNode.value; +// count() and value ---------------------------------------------------------- + +packRootNode = packRootNode.count(); + +num = packRootNode.value; // sort --------------------------------------------------------------------- packRootNode = packRootNode.sort(function (a, b) { diff --git a/d3-hierarchy/index.d.ts b/d3-hierarchy/index.d.ts index 7eef444875..bfe750b31e 100644 --- a/d3-hierarchy/index.d.ts +++ b/d3-hierarchy/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for D3JS d3-hierarchy module v1.0.2 +// Type definitions for D3JS d3-hierarchy module 1.1 // Project: https://github.com/d3/d3-hierarchy/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last module patch version validated against: 1.1.1 + // ----------------------------------------------------------------------- // Hierarchy // ----------------------------------------------------------------------- @@ -20,7 +22,7 @@ export interface HierarchyNode { parent: HierarchyNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -35,6 +37,7 @@ export interface HierarchyNode { path(target: HierarchyNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyNode, b: HierarchyNode) => number): this; each(func: (node: HierarchyNode) => void): this; eachAfter(func: (node: HierarchyNode) => void): this; @@ -43,7 +46,7 @@ export interface HierarchyNode { } -export function hierarchy(data: Datum, children?: (d: Datum) => (Array | null)): HierarchyNode; +export function hierarchy(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode; // ----------------------------------------------------------------------- // Stratify @@ -53,11 +56,11 @@ export function hierarchy(data: Datum, children?: (d: Datum) => (Array { - (data: Array): HierarchyNode; - id(): (d: Datum, i: number, data: Array) => (string | null | '' | undefined); - id(id: (d: Datum, i?: number, data?: Array) => (string | null | '' | undefined)): this; - parentId(): (d: Datum, i: number, data: Array) => (string | null | '' | undefined); - parentId(parentId: (d: Datum, i?: number, data?: Array) => (string | null | '' | undefined)): this; + (data: Datum[]): HierarchyNode; + id(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; + parentId(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; } export function stratify(): StratifyOperator; @@ -80,7 +83,7 @@ export interface HierarchyPointNode { parent: HierarchyPointNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -95,6 +98,7 @@ export interface HierarchyPointNode { path(target: HierarchyPointNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; each(func: (node: HierarchyPointNode) => void): this; eachAfter(func: (node: HierarchyPointNode) => void): this; @@ -150,7 +154,7 @@ export interface HierarchyRectangularNode { parent: HierarchyRectangularNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -165,6 +169,7 @@ export interface HierarchyRectangularNode { path(target: HierarchyRectangularNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyRectangularNode, b: HierarchyRectangularNode) => number): this; each(func: (node: HierarchyRectangularNode) => void): this; eachAfter(func: (node: HierarchyRectangularNode) => void): this; @@ -258,7 +263,7 @@ export interface HierarchyCircularNode { parent: HierarchyCircularNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -273,6 +278,7 @@ export interface HierarchyCircularNode { path(target: HierarchyCircularNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyCircularNode, b: HierarchyCircularNode) => number): this; each(func: (node: HierarchyCircularNode) => void): this; eachAfter(func: (node: HierarchyCircularNode) => void): this; @@ -310,6 +316,6 @@ export interface PackCircle { // For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment // on the mandatory nature, then to create separate interfaces and having to deal with recasting. -export function packSiblings(circles: Array): Array; +export function packSiblings(circles: Datum[]): Datum[]; -export function packEnclose(circles: Array): { r: number, x: number, y: number }; +export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; diff --git a/d3/index.d.ts b/d3/index.d.ts index 61953fe148..bf7fa8e6b6 100644 --- a/d3/index.d.ts +++ b/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 4.4 +// Type definitions for D3JS d3 standard bundle 4.5 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/express-jwt/index.d.ts b/express-jwt/index.d.ts index e721094edc..4b6883a258 100644 --- a/express-jwt/index.d.ts +++ b/express-jwt/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for express-jwt // Project: https://www.npmjs.org/package/express-jwt -// Definitions by: Wonshik Kim +// Definitions by: Wonshik Kim , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import express = require('express'); @@ -37,3 +37,10 @@ declare namespace jwt { unless?: typeof unless; } } +declare global { + namespace Express { + export interface Request { + user?: any + } + } +} diff --git a/express-rate-limit/express-rate-limit-tests.ts b/express-rate-limit/express-rate-limit-tests.ts new file mode 100644 index 0000000000..761a6d23f8 --- /dev/null +++ b/express-rate-limit/express-rate-limit-tests.ts @@ -0,0 +1,25 @@ +import RateLimit = require("express-rate-limit"); + +var apiLimiter = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + delayMs: 0 // disabled +}); + +var createAccountLimiter = new RateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour window + delayAfter: 1, // begin slowing down responses after the first request + delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request + max: 5, // start blocking after 5 requests + message: "Too many accounts created from this IP, please try again after an hour" +}); + +class SomeStore implements RateLimit.Store { + incr(key: string, cb: RateLimit.StoreIncrementCallback) { } + resetAll() { } + resetKey(key: string) { }; +}; + +var limiterWithStore = new RateLimit({ + store: new SomeStore() +}); diff --git a/express-rate-limit/index.d.ts b/express-rate-limit/index.d.ts new file mode 100644 index 0000000000..38ef8f8b29 --- /dev/null +++ b/express-rate-limit/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for express-rate-limit 2.6 +// Project: https://github.com/nfriedly/express-rate-limit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import express = require("express"); + +declare namespace RateLimit { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + export interface Store { + incr: (key: string, cb: StoreIncrementCallback) => void; + resetAll: () => void; + resetKey: (key: string) => void; + } + + export interface Options { + delayAfter?: number; + delayMs?: number; + handlers?: () => any; + headers?: boolean; + keyGenerator?: () => string; + max?: number; + message?: string; + skip?: () => boolean; + statusCode?: number; + store?: Store; + windowMs?: number; + } +} + +interface RateLimitStatic { + new(options: RateLimit.Options): express.RequestHandler; +} + +declare var RateLimit: RateLimitStatic; +export = RateLimit; diff --git a/express-rate-limit/tsconfig.json b/express-rate-limit/tsconfig.json new file mode 100644 index 0000000000..ca3c32c3bb --- /dev/null +++ b/express-rate-limit/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-rate-limit-tests.ts" + ] +} diff --git a/express-rate-limit/tslint.json b/express-rate-limit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/express-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/history/v2/history-tests.ts b/history/v2/history-tests.ts index 454b223e09..598d934e8d 100644 --- a/history/v2/history-tests.ts +++ b/history/v2/history-tests.ts @@ -1,4 +1,4 @@ -import { createBrowserHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' +import { createHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' import { getUserConfirmation } from 'history/lib/DOMUtils' @@ -10,7 +10,7 @@ let doSomethingAsync: () => Promise; let input = { value: "" }; { - let history = createBrowserHistory() + let history = createHistory() // Listen for changes to the current location. The // listener is called once immediately. @@ -46,7 +46,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() // Pushing a path string. history.push('/the/path') @@ -63,7 +63,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() history.listenBefore(function(location) { if (input.value !== '') return 'Are you sure you want to leave this page?' @@ -75,7 +75,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory({ + let history = createHistory({ getUserConfirmation(message, callback) { callback(window.confirm(message)) // The default behavior } @@ -83,7 +83,7 @@ let input = { value: "" }; } { - let history = useBeforeUnload(createBrowserHistory)() + let history = useBeforeUnload(createHistory)() history.listenBeforeUnload(function() { return 'Are you sure you want to leave this page?' @@ -91,7 +91,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)() + let history = useQueries(createHistory)() history.listen(function(location) { console.log(location.query) @@ -99,7 +99,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)({ + let history = useQueries(createHistory)({ parseQueryString: function(queryString) { // TODO: return a parsed version of queryString return {}; @@ -116,7 +116,7 @@ let input = { value: "" }; { // Run our app under the /base URL. - let history = useBasename(createBrowserHistory)({ + let history = useBasename(createHistory)({ basename: '/base' }) @@ -128,4 +128,4 @@ let input = { value: "" }; history.createPath('/the/path') // /base/the/path history.push('/the/path') // push /base/the/path -} \ No newline at end of file +} diff --git a/history/v2/index.d.ts b/history/v2/index.d.ts index 5f719c2f0b..6b61fa1b77 100644 --- a/history/v2/index.d.ts +++ b/history/v2/index.d.ts @@ -127,7 +127,7 @@ export interface Module { }; } -export { default as createBrowserHistory } from "./lib/createBrowserHistory"; +export { default as createHistory } from "./lib/createBrowserHistory"; export { default as createHashHistory } from "./lib/createHashHistory"; export { default as createMemoryHistory } from "./lib/createMemoryHistory"; export { default as createLocation } from "./lib/createLocation"; diff --git a/howler/index.d.ts b/howler/index.d.ts index 1b6604b1aa..df3f6a363b 100644 --- a/howler/index.d.ts +++ b/howler/index.d.ts @@ -66,7 +66,7 @@ interface Howl { rate(idOrSetRate: number): this | number; rate(rate: number, id: number): this; - seek(seek?: number, id?: number): this; + seek(seek?: number, id?: number): this | number; loop(loop?: boolean, id?: number): this; playing(id?: number): boolean; duration(id?: number): number; diff --git a/jquery.datatables/index.d.ts b/jquery.datatables/index.d.ts index c7c4bd8682..5d1bbd50c9 100644 --- a/jquery.datatables/index.d.ts +++ b/jquery.datatables/index.d.ts @@ -908,7 +908,7 @@ declare namespace DataTables { * @param d Data to use for the row. */ data(d: any[] | Object): DataTable; - + /** * Get the id of the selected row. Since: 1.10.8 @@ -1456,9 +1456,9 @@ declare namespace DataTables { } export interface AjaxData { - draw: number; - recordsTotal: number; - recordsFiltered: number; + draw?: number; + recordsTotal?: number; + recordsFiltered?: number; data: any; error?: string; } diff --git a/jquery.validation/index.d.ts b/jquery.validation/index.d.ts index 953755a065..2bb690c07e 100644 --- a/jquery.validation/index.d.ts +++ b/jquery.validation/index.d.ts @@ -217,6 +217,7 @@ declare namespace JQueryValidation interface Validator { element(element: string|JQuery): boolean; + checkForm(): boolean; /** * Validates the form, returns true if it is valid, false otherwise. */ diff --git a/jquery.validation/jquery.validation-tests.ts b/jquery.validation/jquery.validation-tests.ts index 15bb9f790c..0b2de520f2 100644 --- a/jquery.validation/jquery.validation-tests.ts +++ b/jquery.validation/jquery.validation-tests.ts @@ -208,6 +208,7 @@ function test_methods() { $("#myform").submit(); $("#myinput").attr(rules); }); + $("#myform").validate().checkForm(); $("#myform").validate().form(); $("#myform").validate().element("#myselect"); $("#myform").validate().element($("#myselect")); diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 32ef8b30ff..690279bbe4 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,36 +1,32 @@ -// Type definitions for js-md5 v0.3.0 +// Type definitions for js-md5 0.4 // Project: https://github.com/emn178/js-md5 -// Definitions by: Roland Greim +// Definitions by: Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ -/// +declare namespace md5 { + type message = string | any[] | Uint8Array | ArrayBuffer; -interface JQuery { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; + interface Md5 { + array: () => number[]; + arrayBuffer: () => ArrayBuffer; + buffer: () => ArrayBuffer; + digest: () => number[]; + hex: () => string; + toString: () => string; + update: (message: message) => Md5; + } + + interface md5 { + (message: message): string; + hex: (message: message) => string; + array: (message: message) => number[]; + digest: (message: message) => number[]; + arrayBuffer: (message: message) => ArrayBuffer; + buffer: (message: message) => ArrayBuffer; + create: () => Md5; + update: (message: message) => Md5; + } } -interface JQueryStatic { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; -} - -interface md5 { - (value: string): string; - (value: Array): string; - (value: Uint8Array): string; -} - -interface String { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; -} - -declare module "js-md5" { - export = md5; -} - -declare var md5: md5; +declare const md5: md5.md5; +export = md5; diff --git a/js-md5/js-md5-tests.ts b/js-md5/js-md5-tests.ts index 984a919ec3..231b12ebf2 100644 --- a/js-md5/js-md5-tests.ts +++ b/js-md5/js-md5-tests.ts @@ -1,20 +1,29 @@ +import md5 = require("js-md5"); +let str: string = md5.hex('The quick brown fox jumps over the lazy dog'); +str = md5('The quick brown fox jumps over the lazy dog'); +let arr: number[] = md5.digest('The quick brown fox jumps over the lazy dog'); +arr = md5.array('The quick brown fox jumps over the lazy dog'); +let buf: ArrayBuffer = md5.arrayBuffer('The quick brown fox jumps over the lazy dog'); +buf = md5.buffer('The quick brown fox jumps over the lazy dog'); -md5('Message to hash'); -md5(''); -md5('中文'); -md5([]); -md5(new Uint8Array([])); +const hash1 = md5.create(); +hash1.update('The quick brown fox jumps over the lazy dog'); +str = hash1.hex(); +str = hash1.toString(); +arr = hash1.digest(); +arr = hash1.array(); +buf = hash1.arrayBuffer(); +buf = hash1.buffer(); -$.md5('message'); -$.md5('Message to hash'); -$.md5(''); -$.md5('中文'); -$.md5([]); -$.md5(new Uint8Array([])); +const hash2 = md5.update('The quick brown fox jumps over the lazy dog'); +str = hash2.hex(); +str = hash2.toString(); +arr = hash2.digest(); +arr = hash2.array(); +buf = hash2.arrayBuffer(); +buf = hash2.buffer(); -'message'.md5('Message to hash'); -'message'.md5(''); -'message'.md5('中文'); -'message'.md5([]); -'message'.md5(new Uint8Array([])); \ No newline at end of file +str = md5([]); +str = md5(new Uint8Array([])); +str = md5(new ArrayBuffer(0)); diff --git a/js-md5/tsconfig.json b/js-md5/tsconfig.json index eceeb1fb3d..f0ae291e30 100644 --- a/js-md5/tsconfig.json +++ b/js-md5/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +19,4 @@ "index.d.ts", "js-md5-tests.ts" ] -} \ No newline at end of file +} diff --git a/js-md5/tslint.json b/js-md5/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/js-md5/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index 665cdc6a24..a8504aee65 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -453,7 +453,10 @@ declare namespace __MaterialUI { var lightBaseTheme: RawTheme; var darkBaseTheme: RawTheme; - export function muiThemeable, P, S>(): (component: TComponent) => TComponent; + export function muiThemeable(): < + TComponent extends React.ComponentClass

| React.StatelessComponent

, + P extends {muiTheme?: MuiTheme} + >(component: TComponent) => TComponent; interface MuiThemeProviderProps { muiTheme?: Styles.MuiTheme; diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index 04b8f0ec32..8dcc0fe07e 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -7,6 +7,7 @@ import * as React from 'react'; import {Component, PropTypes} from 'react'; import * as ReactDOM from 'react-dom'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; +import {muiThemeable} from 'material-ui/styles/muiThemeable'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import {MuiTheme} from 'material-ui/styles'; @@ -321,6 +322,35 @@ class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}, {}> { } +const MuiThemeableFunction = muiThemeable()((props: {label: string, muiTheme?: MuiTheme}) => { + return ( + + Applied the Theme to functional component: {props.label}. + + ); +}); + +@muiThemeable() +class MuiThemeableClass extends React.Component<{label: string} & {muiTheme?: MuiTheme}, {}> { + render() { + return ( + + Applied the Theme to class component decorated: {this.props.label}. + + ); + } +} + +const MuiThemeableContainer = (props: {}) => ( + +

+ + +
+ +); + + // "http://www.material-ui.com/#/customization/inline-styles" const InlineStylesCheckbox = () => ( +// Definitions by: onokums , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// interface MetisMenuOptions { toggle?: boolean; - doubleTapToGo?: boolean; activeClass?: string; collapseClass?: string; collapseInClass?: string; collapsingClass?: string; + preventDefault?: boolean; } +type MetisMenuEvents = "show.metisMenu" | "shown.metisMenu" | "hide.metisMenu" | "hidden.metisMenu"; + interface JQuery { - metisMenu(options?: MetisMenuOptions): JQuery; + metisMenu(options?: MetisMenuOptions | "dispose"): JQuery; + on(events: MetisMenuEvents, handler: (eventObject: JQueryEventObject) => any): JQuery; } diff --git a/metismenu/metismenu-tests.ts b/metismenu/metismenu-tests.ts index b2e36f1d53..eb17270021 100644 --- a/metismenu/metismenu-tests.ts +++ b/metismenu/metismenu-tests.ts @@ -1,12 +1,28 @@ /// $('#menu').metisMenu(); + $('.metismenu').metisMenu({toggle: false}); + $('.test').metisMenu({ toggle: false, - doubleTapToGo: true, activeClass: 'active', collapseClass: 'collapse', collapseInClass: 'in', - collapsingClass: 'collapsing' + collapsingClass: 'collapsing', + preventDefault: true }); + +$('.metismenu').metisMenu('dispose'); + +$('.metismenu') + .metisMenu() + .on('show.metisMenu', function(e) { + // empty logic + }).on('shown.metisMenu', function(e) { + // empty logic + }).on('hide.metisMenu', function(e) { + // empty logic + }).on('hidden.metisMenu', function(e) { + // empty logic + }); diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 41d08c685d..40210dc69d 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -120,6 +120,7 @@ declare namespace Mocha { interface IHookCallbackContext { skip(): void; timeout(ms: number): void; + [index: string]: any; } @@ -128,6 +129,7 @@ declare namespace Mocha { timeout(ms: number): void; retries(n: number): void; slow(ms: number): void; + [index: string]: any; } /** Partial interface for Mocha's `Runnable` class. */ diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index fc17a18221..8e8dc0d938 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -47,6 +47,8 @@ function test_it() { it('does something', () => { }); + it('does something', function () { this['sharedState'] = true; }); + it('does something', (done) => { done(); }); it.only('does something', () => { }); @@ -64,6 +66,8 @@ function test_test() { test('does something', () => { }); + test('does something', function () { this['sharedState'] = true; }); + test('does something', (done) => { done(); }); test.only('does something', () => { }); @@ -81,6 +85,8 @@ function test_specify() { specify('does something', () => { }); + specify('does something', function () { this['sharedState'] = true; }); + specify('does something', (done) => { done(); }); specify.only('does something', () => { }); @@ -97,6 +103,8 @@ function test_specify() { function test_before() { before(() => { }); + before(function () { this['sharedState'] = true; }); + before((done) => { done(); }); before("my description", () => { }); @@ -120,6 +128,17 @@ function test_setup() { string = this.currentTest.state; }); + setup(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + setup(function (done) { done(); boolean = this.currentTest.async; @@ -135,6 +154,8 @@ function test_setup() { function test_after() { after(() => { }); + after(function () { this['sharedState'] = true; }); + after((done) => { done(); }); after("my description", () => { }); @@ -153,6 +174,17 @@ function test_teardown() { string = this.currentTest.state; }); + teardown(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + teardown(function(done) { done(); boolean = this.currentTest.async; @@ -176,6 +208,17 @@ function test_beforeEach() { string = this.currentTest.state; }); + beforeEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + beforeEach(function (done) { done(); boolean = this.currentTest.async; @@ -212,6 +255,8 @@ function test_beforeEach() { function test_suiteSetup() { suiteSetup(() => { }); + suiteSetup(function () { this['sharedState'] = true; }); + suiteSetup((done) => { done(); }); } @@ -226,6 +271,17 @@ function test_afterEach() { string = this.currentTest.state; }); + afterEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + afterEach(function (done) { done(); boolean = this.currentTest.async; @@ -263,6 +319,8 @@ function test_afterEach() { function test_suiteTeardown() { suiteTeardown(() => { }); + suiteTeardown(function () { this['sharedState'] = true; }); + suiteTeardown((done) => { done(); }); } diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index bdf89c32f6..bab845a01d 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1172,8 +1172,6 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe - pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read @@ -1184,8 +1182,6 @@ export interface Cursor extends Readable { rewind(): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption setCursorOption(field: string, value: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding - setEncoding(encoding: string): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId @@ -1201,8 +1197,6 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe - unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift unshift(stream: Buffer | string): void; } @@ -1260,8 +1254,6 @@ export interface AggregationCursor extends Readable { next(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out out(destination: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe - pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project project(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read @@ -1271,16 +1263,12 @@ export interface AggregationCursor extends Readable { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind rewind(): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding - setEncoding(encoding: string): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip skip(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort sort(document: Object): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe - unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift unshift(stream: Buffer | string): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind @@ -1305,21 +1293,15 @@ export interface CommandCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe - pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind rewind(): CommandCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding - setEncoding(encoding: string): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe - unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift unshift(stream: Buffer | string): void; } diff --git a/needle/index.d.ts b/needle/index.d.ts index 7607fdfc78..8cc61f2a2f 100644 --- a/needle/index.d.ts +++ b/needle/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for needle 0.7.8 +// Type definitions for needle 1.4 // Project: https://github.com/tomas/needle -// Definitions by: San Chen +// Definitions by: San Chen , Niklas Mollenhauer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,85 +8,111 @@ declare module "needle" { import * as http from 'http'; import * as Buffer from 'buffer'; - module Needle { + import * as https from 'https'; + namespace Needle { interface NeedleResponse extends http.IncomingMessage { body: any; raw: Buffer; bytes: number; } - interface ReadableStream extends NodeJS.ReadableStream { + type ReadableStream = NodeJS.ReadableStream; + + type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void; + + interface Cookies { + [name: string]: any; } - interface Callback { - (error: Error, response: NeedleResponse, body: any): void; - } + type NeedleOptions = RequestOptions & ResponseOptions & RedirectOptions & https.RequestOptions; interface RequestOptions { + open_timeout?: number; + read_timeout?: number; + /** + * Alias for open_timeout + */ timeout?: number; - follow?: number; + follow_max?: number; + /** + * Alias for follow_max + */ + follow?: number; + multipart?: boolean; + agent?: http.Agent | boolean; proxy?: string; - agent?: string; - headers?: Object; - auth?: string; // auto | digest | basic (default) + headers?: {}; + auth?: "auto" | "digest" | "basic"; json?: boolean; // These properties are overwritten by those in the 'headers' field + cookies?: Cookies; compressed?: boolean; - cookies?: { [name: string]: any; }; // Overwritten if present in the URI username?: string; password?: string; + accept?: string; + connection?: string; + user_agent?: string; } interface ResponseOptions { + decode_response?: boolean; + /** + * Alias for decode_response + */ decode?: boolean; + parse_response?: boolean; + /** + * Alias for parse_response + */ parse?: boolean; - output?: any; + + parse_cookies?: boolean; + output?: string; } - interface TLSOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: any; - rejectUnauthorized?: boolean; - secureProtocol?: any; + interface RedirectOptions { + follow_set_cookie?: boolean; + follow_set_referer?: boolean; + follow_keep_method?: boolean; + follow_if_same_host?: boolean; + follow_if_same_protocol?: boolean; } + interface KeyValue { + [key: string]: any; + } + + type BodyData = Buffer | KeyValue | NodeJS.ReadableStream | string | null; + interface NeedleStatic { - defaults(options?: any): void; + defaults(options: NeedleOptions): void; - head(url: string): ReadableStream; - head(url: string, callback?: Callback): ReadableStream; - head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + head(url: string, callback?: NeedleCallback): ReadableStream; + head(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - get(url: string): ReadableStream; - get(url: string, callback?: Callback): ReadableStream; - get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + get(url: string, callback?: NeedleCallback): ReadableStream; + get(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - post(url: string, data: any): ReadableStream; - post(url: string, data: any, callback?: Callback): ReadableStream; - post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + post(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + post(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - put(url: string, data: any): ReadableStream; - put(url: string, data: any, callback?: Callback): ReadableStream; - put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + put(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + put(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - delete(url: string, data: any): ReadableStream; - delete(url: string, data: any, callback?: Callback): ReadableStream; - delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + patch(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + patch(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - request(method: string, url: string, data: any): ReadableStream; - request(method: string, url: string, data: any, callback?: Callback): ReadableStream; - request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + delete(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + delete(url: string, data: BodyData, options?: NeedleOptions, callback ?: NeedleCallback): ReadableStream; + + request(method: string, url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + request(method: string, url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; } } - - var needle: Needle.NeedleStatic; + const needle: Needle.NeedleStatic; export = needle; -} \ No newline at end of file +} diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 3df14952c3..1c5090027a 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -1,4 +1,5 @@ -import needle = require("needle"); +import * as needle from "needle"; +import * as fs from "fs"; function Usage() { // using callback @@ -14,7 +15,7 @@ function Usage() { function ResponsePipeline() { needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { - console.log(resp.body); // this little guy won't be a Gzipped binary blob + console.log(resp.body); // this little guy won't be a Gzipped binary blob // but a nice object containing all the latest entries }); @@ -24,21 +25,26 @@ function ResponsePipeline() { rejectUnauthorized: true }; - // in this case, we'll ask Needle to follow redirects (disabled by default), + // in this case, we'll ask Needle to follow redirects (disabled by default), // but also to verify their SSL certificates when connecting. var stream = needle.get('https://backend.server.com/everything.html', options); stream.on('readable', function () { var data: any; - while (data = this.read()) { + while (data = stream.read()) { console.log(data.toString()); } }); + + stream.on('end', function(err: any) { + // if our request had an error, our 'end' event will tell us. + if (!err) console.log('Great success!'); + }) } function API_head() { var options = { - timeout: 5000 // if we don't get a response in 5 seconds, boom. + open_timeout: 5000 // if we don't get a response in 5 seconds, boom. }; needle.head('https://my.backend.server.com', function (err, resp) { @@ -93,14 +99,131 @@ function API_delete() { } function API_request() { - var data = { + var params = { q: 'a very smart query', page: 2, - format: 'json' }; - needle.request('get', 'forum.com/search', data, function (err, resp) { + needle.request('get', 'forum.com/search', params, function (err, resp) { if (!err && resp.statusCode == 200) console.log(resp.body); // here you go, mister. }); + + needle.request('get', 'forum.com/search', params, { json: true }, function(err, resp) { + if (resp.statusCode == 200) console.log('It worked!'); + }); +} + +function HttpGetWithBasicAuth() { + needle.get('https://api.server.com', { username: 'you', password: 'secret' }, function(err, resp) { + // used HTTP auth + }); + needle.get('https://username:password@api.server.com', function(err, resp) { + // used HTTP auth from URL + }); +} + +function DigestAuth() { + needle.get('other.server.com', { username: 'you', password: 'secret', auth: 'digest' }, function(err, resp, body) { + // needle prepends 'http://' to your URL, if missing + }); +} + +function CustomAcceptHeaderDeflate() { + var options = { + compressed: true, + follow: 10, + accept: 'application/vnd.github.full+json' + } + + needle.get('api.github.com/users/tomas', options, function(err, resp, body) { + // body will contain a JSON.parse(d) object + // if parsing fails, you'll simply get the original body + }); + +} + +function Various() { + + needle.get('https://news.ycombinator.com/rss', function(err, resp, body) { + // if xml2js is installed, you'll get a nice object containing the nodes in the RSS + }); + needle.get('http://upload.server.com/tux.png', { output: '/tmp/tux.png' }, function(err, resp, body) { + // you can dump any response to a file, not only binaries. + }); + needle.get('http://search.npmjs.org', { proxy: 'http://localhost:1234' }, function(err, resp, body) { + // request passed through proxy + }); + const stream1 = needle.get('http://www.as35662.net/100.log'); + stream1.on('readable', function() { + let chunk: any; + while (chunk = stream1.read()) { + console.log('got data: ', chunk); + } + }); + const stream2 = needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }); + stream2.on('readable', function() { + let node: any; + + // our stream2 will only emit a single JSON root node. + while (node = stream2.read()) { + console.log('got data: ', node); + } + }); + + /* + // Sample omitted, no JSONStream + needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }) + .pipe(new JSONStream.parse('posts.*.title')) + .on('data', function (obj) { + console.log('got post title: %s', obj); + }); + */ +} + +function FileUpload() { + var data = { + foo: 'bar', + image: { file: '/home/tomas/linux.png', content_type: 'image/png' } + }; + + needle.post('http://my.other.app.com', data, { multipart: true }, function(err, resp, body) { + // needle will read the file and include it in the form-data as binary + }); + needle.put('https://api.app.com/v2', fs.createReadStream('myfile.txt'), function(err, resp, body) { + // stream content is uploaded verbatim + }); +} + +function Multipart() { + var buffer = fs.readFileSync('/path/to/package.zip'); + + var data = { + zip_file: { + buffer: buffer, + filename: 'mypackage.zip', + content_type: 'application/octet-stream' + } + } + + needle.post('http://somewhere.com/over/the/rainbow', data, { multipart: true }, function(err, resp, body) { + // if you see, when using buffers we need to pass the filename for the multipart body. + // you can also pass a filename when using the file path method, in case you want to override + // the default filename to be received on the other end. + }); +} + +function MultipartContentType() { + var data = { + token: 'verysecret', + payload: { + value: JSON.stringify({ title: 'test', version: 1 }), + content_type: 'application/json' + } + } + + needle.post('http://test.com/', data, { timeout: 5000, multipart: true }, function(err, resp, body) { + // in this case, if the request takes more than 5 seconds + // the callback will return a [Socket closed] error + }); } diff --git a/needle/tsconfig.json b/needle/tsconfig.json index 5af602dd4f..59f9b2b49e 100644 --- a/needle/tsconfig.json +++ b/needle/tsconfig.json @@ -5,8 +5,8 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "needle-tests.ts" ] -} \ No newline at end of file +} diff --git a/needle/v0/index.d.ts b/needle/v0/index.d.ts new file mode 100644 index 0000000000..28b5b8119f --- /dev/null +++ b/needle/v0/index.d.ts @@ -0,0 +1,83 @@ +// Type definitions for needle 0.7 +// Project: https://github.com/tomas/needle +// Definitions by: San Chen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "needle" { + import * as http from 'http'; + import * as Buffer from 'buffer'; + namespace Needle { + interface NeedleResponse extends http.IncomingMessage { + body: any; + raw: Buffer; + bytes: number; + } + + type ReadableStream = NodeJS.ReadableStream; + + type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void; + + interface RequestOptions { + timeout?: number; + follow?: number; + follow_max?: number; + multipart?: boolean; + proxy?: string; + agent?: string; + headers?: {}; + auth?: string; // auto | digest | basic (default) + json?: boolean; + + // These properties are overwritten by those in the 'headers' field + compressed?: boolean; + cookies?: { [name: string]: any; }; + // Overwritten if present in the URI + username?: string; + password?: string; + } + + interface ResponseOptions { + decode?: boolean; + parse?: boolean; + output?: any; + } + + interface TLSOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: any; + rejectUnauthorized?: boolean; + secureProtocol?: any; + } + + interface NeedleStatic { + defaults(options?: any): void; + + head(url: string, callback?: NeedleCallback): ReadableStream; + head(url: string, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + get(url: string, callback?: NeedleCallback): ReadableStream; + get(url: string, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + post(url: string, data: any, callback?: NeedleCallback): ReadableStream; + post(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + put(url: string, data: any, callback?: NeedleCallback): ReadableStream; + put(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + delete(url: string, data: any, callback?: NeedleCallback): ReadableStream; + delete(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + request(method: string, url: string, data: any, callback?: NeedleCallback): ReadableStream; + request(method: string, url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + } + } + + var needle: Needle.NeedleStatic; + export = needle; +} diff --git a/needle/v0/needle-tests.ts b/needle/v0/needle-tests.ts new file mode 100644 index 0000000000..5a849ec204 --- /dev/null +++ b/needle/v0/needle-tests.ts @@ -0,0 +1,106 @@ +import needle = require("needle"); + +function Usage() { + // using callback + needle.get('http://ifconfig.me/all.json', function (error, response) { + if (!error) + console.log(response.body.ip_addr); // JSON decoding magic. :) + }); + + // using streams + var out: any; // = fs.createWriteStream('logo.png'); + needle.get('https://google.com/images/logo.png').pipe(out); +} + +function ResponsePipeline() { + needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { + console.log(resp.body); // this little guy won't be a Gzipped binary blob + // but a nice object containing all the latest entries + }); + + var options = { + compressed: true, + follow: 5, + rejectUnauthorized: true + }; + + // in this case, we'll ask Needle to follow redirects (disabled by default), + // but also to verify their SSL certificates when connecting. + var stream = needle.get('https://backend.server.com/everything.html', options); + + stream.on('readable', function () { + var data: any; + while (data = stream.read()) { + console.log(data.toString()); + } + }); +} + +function API_head() { + var options = { + timeout: 5000 // if we don't get a response in 5 seconds, boom. + }; + + needle.head('https://my.backend.server.com', function (err, resp) { + if (err) { + console.log('Shoot! Something is wrong: ' + err.message); + } + else { + console.log('Yup, still alive.'); + } + }); +} + +function API_get() { + needle.get('google.com/search?q=syd+barrett', function (err, resp) { + // if no http:// is found, Needle will automagically prepend it. + }); +} + +function API_post() { + var options = { + headers: { 'X-Custom-Header': 'Bumbaway atuna' } + }; + + needle.post('https://my.app.com/endpoint', 'foo=bar', options, function (err, resp) { + // you can pass params as a string or as an object. + }); +} + +function API_put() { + var nested = { + params: { + are: { + also: 'supported' + } + } + }; + + needle.put('https://api.app.com/v2', nested, function (err, resp) { + console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella. + }); +} + +function API_delete() { + var options = { + username: 'fidelio', + password: 'x' + }; + + needle.delete('https://api.app.com/messages/123', null, options, function (err, resp) { + // in this case, data may be null, but you need to explicity pass it. + }); +} + +function API_request() { + var data = { + q: 'a very smart query', + page: 2, + format: 'json' + }; + + needle.request('get', 'forum.com/search', data, function (err, resp) { + if (!err && resp.statusCode == 200) + console.log(resp.body); // here you go, mister. + }); +} diff --git a/needle/v0/tsconfig.json b/needle/v0/tsconfig.json new file mode 100644 index 0000000000..44c8b59654 --- /dev/null +++ b/needle/v0/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../../" + ], + "paths": { + "needle": [ + "needle/v0" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "needle-tests.ts" + ] +} diff --git a/node/index.d.ts b/node/index.d.ts index 93c0d7c709..d23cc981e4 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -11,7 +11,7 @@ // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build interface Console { - Console: typeof NodeJS.Console; + Console: NodeJS.ConsoleConstructor; assert(value: any, message?: string, ...optionalParams: any[]): void; dir(obj: any, options?: {showHidden?: boolean, depth?: number, colors?: boolean}): void; error(message?: any, ...optionalParams: any[]): void; @@ -247,7 +247,7 @@ declare var Buffer: { * * ************************************************/ declare namespace NodeJS { - export var Console: { + export interface ConsoleConstructor { prototype: Console; new(stdout: WritableStream, stderr?: WritableStream): Console; } @@ -281,12 +281,12 @@ declare namespace NodeJS { readable: boolean; isTTY?: boolean; read(size?: number): string | Buffer; - setEncoding(encoding: string | null): void; - pause(): ReadableStream; - resume(): ReadableStream; + setEncoding(encoding: string | null): this; + pause(): this; + resume(): this; isPaused(): boolean; pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; + unpipe(destination?: T): this; unshift(chunk: string): void; unshift(chunk: Buffer): void; wrap(oldStream: ReadableStream): ReadableStream; @@ -303,10 +303,7 @@ declare namespace NodeJS { end(str: string, encoding?: string, cb?: Function): void; } - export interface ReadWriteStream extends ReadableStream, WritableStream { - pause(): ReadWriteStream; - resume(): ReadWriteStream; - } + export interface ReadWriteStream extends ReadableStream, WritableStream { } export interface Events extends EventEmitter { } @@ -1904,11 +1901,11 @@ declare module "net" { connect(port: number, host?: string, connectionListener?: Function): void; connect(path: string, connectionListener?: Function): void; bufferSize: number; - setEncoding(encoding?: string): void; + setEncoding(encoding?: string): this; write(data: any, encoding?: string, callback?: Function): void; destroy(): void; - pause(): Socket; - resume(): Socket; + pause(): this; + resume(): this; setTimeout(timeout: number, callback?: Function): void; setNoDelay(noDelay?: boolean): void; setKeepAlive(enable?: boolean, initialDelay?: number): void; @@ -3398,12 +3395,12 @@ declare module "stream" { constructor(opts?: ReadableOptions); protected _read(size: number): void; read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Readable; - resume(): Readable; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; isPaused(): boolean; pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; + unpipe(destination?: T): this; unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; @@ -3562,8 +3559,8 @@ declare module "stream" { // Note: Duplex extends both Readable and Writable. export class Duplex extends Readable implements NodeJS.ReadWriteStream { // Readable - pause(): Duplex; - resume(): Duplex; + pause(): this; + resume(): this; // Writeable writable: boolean; constructor(opts?: DuplexOptions); @@ -3588,12 +3585,12 @@ declare module "stream" { protected _transform(chunk: any, encoding: string, callback: Function): void; protected _flush(callback: Function): void; read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Transform; - resume(): Transform; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; isPaused(): boolean; pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; + unpipe(destination?: T): this; unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; diff --git a/node/node-tests.ts b/node/node-tests.ts index 03c3e9a1b6..9585b3893a 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1634,6 +1634,11 @@ namespace console_tests { var _c: Console = console; _c = c; } + { + var writeStream = fs.createWriteStream('./index.d.ts'); + var consoleInstance = new console.Console(writeStream) + + } } /////////////////////////////////////////////////// diff --git a/paymentrequest/index.d.ts b/paymentrequest/index.d.ts index 50ef94e1e6..5231f53bc3 100644 --- a/paymentrequest/index.d.ts +++ b/paymentrequest/index.d.ts @@ -1,26 +1,33 @@ // Type definitions for PaymentRequest // Project: https://www.w3.org/TR/payment-request/ -// Definitions by: Adam Cmiel +// Definitions by: Adam Cmiel , Eiji Kitamura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface PaymentRequest extends EventTarget { new (methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; show(): PromiseLike; abort(): PromiseLike; - shippingAddress?: PaymentAddress; - shippingOption?: string; + canMakePayment(): Promise; + readonly paymentRequestID: string; + readonly shippingAddress?: PaymentAddress; + readonly shippingOption?: string; + readonly shippingType?: string; onshippingaddresschange: PaymentUpdateEventListener; onshippingoptionchange: PaymentUpdateEventListener; } interface PaymentMethodData { supportedMethods: string[]; - data?: Object; + data?: { + supportedNetworks: string[]; + supportedTypes: string[]; + }; } interface PaymentCurrencyAmount { currency: string; value: string; + currencySystem?:string; } interface PaymentDetails { @@ -28,55 +35,63 @@ interface PaymentDetails { displayItems?: PaymentItem[]; shippingOptions?: PaymentShippingOption[]; modifiers?: PaymentDetailsModifier[]; + error?: string; } interface PaymentDetailsModifier { supportedMethods: string[]; total?: PaymentItem; - additionalDisplayItems: PaymentItem[]; + additionalDisplayItems?: PaymentItem[]; + data?: Object; } interface PaymentOptions { - requestShipping: boolean; - requestPayerEmail: boolean; - requestPayerPhone: boolean; + requestShipping?: boolean; + requestPayerEmail?: boolean; + requestPayerPhone?: boolean; + requestPayerName?: boolean; + shippingType?: 'shipping' | 'delivery' | 'pickup'; } interface PaymentItem { label: string; - amount: PaymentCurrencyAmount + amount: PaymentCurrencyAmount; + pending?: boolean; } interface PaymentAddress { - country: string; - addressLine: string[]; - region: string; - city: string; - dependentLocality: string; - postalCode: string; - sortingCode: string; - languageCode: string; - organization: string; - recipient: string; - careOf: string; - phone: string; + readonly country: string; + readonly addressLine: string[]; + readonly region: string; + readonly city: string; + readonly dependentLocality: string; + readonly postalCode: string; + readonly sortingCode: string; + readonly languageCode: string; + readonly organization: string; + readonly recipient: string; + readonly phone: string; } interface PaymentShippingOption { id: string; label: string; amount: PaymentCurrencyAmount; + selected?: boolean; } interface PaymentResponse { - methodName: string; - details: Object; - shippingAddress?: PaymentAddress; - shippingOption?: string; - payerEmail?: string; - payerPhone?: string; + readonly paymentRequestID: string; + readonly methodName: string; + readonly details: Object; + readonly shippingAddress?: PaymentAddress; + readonly shippingOption?: string; + readonly payerEmail?: string; + readonly payerPhone?: string; + readonly payerName?: string; complete(result?: '' | 'success' | 'fail'): PromiseLike; + toJSON(): Object; } interface PaymentUpdateEventListener extends EventListener { diff --git a/paymentrequest/paymentrequest-tests.ts b/paymentrequest/paymentrequest-tests.ts index 4c36c3ff76..62c2721bfb 100644 --- a/paymentrequest/paymentrequest-tests.ts +++ b/paymentrequest/paymentrequest-tests.ts @@ -3,7 +3,7 @@ /// Code examples derived from /// https://developers.google.com/web/fundamentals/discovery-and-monetization/payment-request/ -function makeRequest() { +async function makeRequest() { if (!window.PaymentRequest) { return Promise.reject(new Error("PaymentRequest not available")) } @@ -31,10 +31,12 @@ function makeRequest() { } } - const options = { + const options: PaymentOptions = { requestShipping: true, requestPayerEmail: true, - requestPayerPhone: true + requestPayerPhone: true, + requestPayerName: true, + shippingType: 'delivery' } const request = new window.PaymentRequest(methodData, details, options) @@ -72,7 +74,12 @@ function makeRequest() { })(details, request.shippingAddress)); }) - return request.show() + let canMakePayment = await request.canMakePayment() + if (canMakePayment) { + return request.show() + } else { + throw 'can not make payment on this environment.' + } } async function processPayment(): Promise { diff --git a/paymentrequest/tsconfig.json b/paymentrequest/tsconfig.json index 221e0618af..e5754a139a 100644 --- a/paymentrequest/tsconfig.json +++ b/paymentrequest/tsconfig.json @@ -5,6 +5,7 @@ "es6", "dom" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index 6ecb6a0cdd..7b54ec7372 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,212 +1,301 @@ // Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout +// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout , Ben Vinegar , Ilya Pirogov , Eli White , David Cramer , Connor Peet , comaz , Luca Vazzano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var Raven: RavenStatic; -declare module 'raven-js' { - export default Raven; -} - -interface RavenOptions { - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** The release version of the application you are monitoring with Sentry */ - release?: string; - - /** The environment in which the application is running. */ - environment?: string; - - /** The name of the server or device that the client is running on */ - serverName?: string; - - /** List of messages to be fitlered out before being sent to Sentry. */ - ignoreErrors?: string[]; - - /** Similar to ignoreErrors, but will ignore errors from whole urls patching a regex pattern. */ - ignoreUrls?: RegExp[]; - - /** The inverse of ignoreUrls. Only report errors from whole urls matching a regex pattern. */ - whitelistUrls?: RegExp[]; - - /** An array of regex patterns to indicate which urls are a part of your app. */ - includePaths?: RegExp[]; - - /** Additional data to be tagged onto the error. */ - tags?: { - [id: string]: string; - }; - - /** A function which allows mutation of the data payload right before being sent to Sentry */ - dataCallback?: (data: any) => any; - - /** A callback function that allows you to apply your own filters to determine if the message should be sent to Sentry. */ - shouldSendCallback?: (data: any) => boolean; - - /** By default, Raven does not truncate messages. If you need to truncate characters for whatever reason, you may set this to limit the length. */ - maxMessageLength?: number; - - /** Enables/disables automatic collection of breadcrumbs. Default: true. */ - autoBreadcrumbs?: any; - - /** The max number of breadcrumb captures. Default: 100. */ - maxBreadcrumbs?: number; - - /** Override the default HTTP data transport handler. */ - transport?: (options: RavenTransportOptions) => void; - - /** Allow the use of a Sentry DSN with a private key. Default: false. */ - allowSecretKey?: boolean; -} - -interface RavenAdditionalData { - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** The log level associated with this event. Default: error */ - level?: string; - - /** Additional data to be tagged onto the error. */ - tags?: { - [id: string]: string; - }; - - extra?: any; -} +declare let Raven: RavenStatic; +export default Raven; interface RavenStatic { - /** Raven.js version. */ VERSION: string; + /** A list of currently active plugins. */ Plugins: { [id: string]: RavenPlugin }; - /* - * Allow Raven to be configured as soon as it is loaded + /** + * Allow Raven to be configured as soon as it is loaded. * It uses a global RavenConfig = {dsn: '...', config: {}} - * - * @return undefined */ afterLoad(): void; - /* + /** * Allow multiple versions of Raven to be installed. * Strip Raven from the global context and returns the instance. - * - * @return {Raven} */ noConflict(): RavenStatic; - /* + /** * Configure Raven with a DSN and extra options * - * @param {string} dsn The public Sentry DSN - * @param {object} options Optional set of of global options [optional] - * @return {Raven} + * @param dsn The public Sentry DSN + * @param options Optional set of of global options */ - config(dsn: string, options?: RavenOptions): RavenStatic; + config(dsn: string, options?: RavenGlobalOptions): RavenStatic; - /* - * Installs a global window.onerror error handler - * to capture and report uncaught exceptions. - * At this point, install() is required to be called due - * to the way TraceKit is set up. + /** + * Set the DSN (can be called multiple times, unlike config) * - * @return {Raven} + * @param dsn The public Sentry DSN + */ + setDSN(dsn: string): RavenStatic; + + /** + * Installs a global window.onerror error handler to capture and report uncaught exceptions. + * At this point, install() is required to be called due to the way TraceKit is set up. */ install(): RavenStatic; - /* + /** * Adds a plugin to Raven - * - * @return {Raven} */ addPlugin(plugin: RavenPlugin, ...pluginArgs: any[]): RavenStatic; - /* - * Wrap code within a context so Raven can capture errors - * reliably across domains that is executed immediately. + /** + * Wrap code within a context so Raven can capture errors reliably across domains that is + * executed immediately. * - * @param {object} options A specific set of options for this context [optional] - * @param {function} func The callback to be immediately executed within the context - * @param {array} args An array of arguments to be called with the callback [optional] + * @param options A specific set of options for this context + * @param func The callback to be immediately executed within the context + * @param args An array of arguments to be called with the callback */ context(func: Function, ...args: any[]): void; - context(options: RavenAdditionalData, func: Function, ...args: any[]): void; + context(options: RavenWrapOptions, func: Function, ...args: any[]): void; - /* + /** * Wrap code within a context and returns back a new function to be executed * - * @param {object} options A specific set of options for this context [optional] - * @param {function} func The function to be wrapped in a new context - * @return {function} The newly wrapped functions with a context + * @param options A specific set of options for this context + * @param func The function to be wrapped in a new context + * @return The newly wrapped functions with a context */ wrap(func: Function): Function; - wrap(options: RavenAdditionalData, func: Function): Function; + wrap(options: RavenWrapOptions, func: Function): Function; wrap(func: T): T; - wrap(options: RavenAdditionalData, func: T): T; + wrap(options: RavenWrapOptions, func: T): T; - /* + /** * Uninstalls the global error handler. - * - * @return {Raven} */ uninstall(): RavenStatic; - /* + /** * Manually capture an exception and send it over to Sentry * - * @param {error} ex An exception to be logged - * @param {object} options A specific set of options for this error [optional] - * @return {Raven} + * @param ex An exception to be logged + * @param options A specific set of options for this error */ - captureException(ex: Error, options?: RavenAdditionalData): RavenStatic; + captureException(ex: Error, options?: RavenOptions): RavenStatic; /* * Manually send a message to Sentry * - * @param {string} msg A plain message to be captured in Sentry - * @param {object} options A specific set of options for this message [optional] - * @return {Raven} + * @param msg A plain message to be captured in Sentry + * @param options A specific set of options for this message */ - captureMessage(msg: string, options?: RavenAdditionalData): RavenStatic; + captureMessage(msg: string, options?: RavenOptions): RavenStatic; + + /** + * Add a breadcrumb + * @param crumb The trail which should be added to the trail + */ + captureBreadcrumb(crumb: RavenBreadcrumb): RavenStatic; + + /** + * Set a user to be sent along with payloads. + * + * @param user The definition of the currently active user's unique identity + */ + setUserContext(user: RavenUserContext): RavenStatic; /** * Clear the user context, removing the user data that would be sent to Sentry. */ setUserContext(): RavenStatic; - /* - * Set a user to be sent along with the payload. - * - * @param {object} user An object representing user data [optional] - * @return {Raven} + /** + * Add arbitrary data to be sent along with the payload. + * @param extra data of an arbitrary, nested type which will be added */ - setUserContext(user: { - id?: string; - username?: string; - email?: string; - }): RavenStatic; + setExtraContext(extra: { [prop: string]: any }): RavenStatic; - /** Override the default HTTP data transport handler. */ - setTransport(transportFunction: (options: RavenTransportOptions) => void): RavenStatic; + /** + * Add additional tags to be sent along with payloads. + * @param tags A key/value-pair which will be added + */ + setTagsContext(tags: { [id: string]: string }): RavenStatic; - /** An event id is a globally unique id for the event that was just sent. This event id can be used to find the exact event from within Sentry. */ + /** + * Clear the whole currently set context. + */ + clearContext(): RavenStatic; + + /** + * Get a copy of the current context. + */ + getContext(): Object; + + /** + * Set environment of application + * @param environment Typically something like 'production' + */ + setEnvironment(environment: string): RavenStatic; + + /** + * Set release version of application + * @param release Typically something like a git SHA to identify the current version + */ + setRelease(release: string): RavenStatic; + + /** + * Specify a function that can mutate the payload right before it is being sent to Sentry. + * @param callback The function which can mutate the data + */ + setDataCallback(callback: (data: any, orig?: string) => any): RavenStatic; + + /** + * Specify a callback function that can mutate or filter breadcrumbs when they are captured. + * @param callback The function which applies the filter + */ + setBreadcrumbCallback(callback :(data: any, orig?: string) => any): RavenStatic; + + /** + * Specify a callback function that determines if the given message should be sent to Sentry. + * @param callback The function which determines if the given blob should be sent + */ + setShouldSendCallback(callback: (data: any, orig?: string) => boolean): RavenStatic; + + /** + * Override the default HTTP data transport handler. + * @param transport The function which will be invoked to handle the data transmission + */ + setTransport(transport: (options: RavenTransportOptions) => void): RavenStatic; + + /** + * Get the latest raw exception that was captured by Raven. + */ + lastException(): Error; + + /** + * Get the ID of the last Event captured by Raven. + */ lastEventId(): string; - /** If you need to conditionally check if raven needs to be initialized or not, you can use the isSetup function. It will return true if Raven is already initialized. */ + /** + * Determine if Raven is setup and ready to go. + */ isSetup(): boolean; - showReportDialog(options: RavenOptions): void; - - setTagsContext(tags: { [id: string]: string; }): void; - - setExtraContext(context: any): void; + /** + * Show the User Feedback Dialog of Sentry + * @param RavenReportDialogOptions Optional Options to set for the User Feedback + */ + showReportDialog(options?: RavenReportDialogOptions): void; } -interface RavenTransportOptions { + +// --- Helper Interfaces for Options -------------- +export interface RavenBreadcrumOptions { + /** Whether to collect XHR calls, defaults to true */ + xhr?: boolean; + + /** Whether to collect console logs, defaults to true */ + console?: boolean; + + /** Whether to collect dom events, defaults to true */ + dom?: boolean; + + /** Whether to record window location and navigation, defaults to true */ + location?: boolean; +} + +export interface CommonRavenOptions { + /** The environment of the application you are monitoring with Sentry */ + environment?: string; + + /** The release version of the application you are monitoring with Sentry */ + release?: string; + + /** Additional key/value-data to be tagged onto the error. */ + tags?: { [id: string]: string }; + + /** Additional, arbitrary metadata to collect */ + extra?: { [prop: string]: any }; + + /** The name of the logger used by Sentry. Default: javascript */ + logger?: string; + + /** set to true to get the strack trace of your message */ + stacktrace?: boolean; +} + +export interface RavenOptions extends CommonRavenOptions { + /** The name of the server or device that the client is running on */ + server_name?: string; + + /** The log level associated with this event. Default: error */ + level?: string; + + /** In some cases you may see issues where Sentry groups multiple events together when they + * should be separate entities. In other cases, Sentry simply doesn’t group events together + * because they’re so sporadic that they never look the same. */ + fingerprint?: string[]; + + /** Number of frames to trim off the stacktrace. Default: 1 */ + trimHeadFrames?: number; + + /** The name of the device platform. Default: "javascript" */ + platform?: string; +} + +export interface RavenGlobalOptions extends CommonRavenOptions { + /** The name of the server or device that the client is running on */ + serverName?: string; + + /** Configures which breadcrumbs are collected automatically */ + autoBreadcrumbs?: boolean | RavenBreadcrumOptions; + + /** Whether to collect errors on the window via TraceKit.collectWindowErrors. Default: true. */ + collectWindowErrors?: boolean; + + /** Max number of breadcrumbs to collect. Default: 100 */ + maxBreadcrumbs?: number; + + /** Exclude messages which match one of the given RegEx-Patterns from being sent to Sentry. */ + ignoreErrors?: (RegExp | string)[]; + + /** Exclude messages which come from whole urls matching one of the given RegEx patterns. */ + ignoreUrls?: (RegExp | string)[]; + + /** Only report messages which come from whole urls matching one of the given RegEx patterns. */ + whitelistUrls?: (RegExp | string)[]; + + /** An array of RegEx patterns to indicate which urls are a part of your app. */ + includePaths?: (RegExp | string)[]; + + /** Maximum amount of stack frames to collect. Default: Infinity */ + stackTraceLimit?: number; + + /** Override the default HTTP data transport handler. */ + transport?: (options: RavenTransportOptions) => void; + + /** Limit the maxium length of a message to this number of characters. Default: Infinity */ + maxMessageLength?: number; + + /** Allows you to apply your own filters to determine if the message should be sent to Sentry. */ + shouldSendCallback?: (data: any) => boolean; + + /** A function which allows mutation of the data payload right before being sent to Sentry */ + dataCallback?: (data: any) => any; +} + +export interface RavenWrapOptions extends RavenOptions { + /** Whether to run the wrap recursively. Default: false. */ + deep?: boolean; +} + +export interface RavenTransportOptions { url: string; data: any; auth: { @@ -218,6 +307,32 @@ interface RavenTransportOptions { onFailure: () => void; } -interface RavenPlugin { +export interface RavenReportDialogOptions { + eventId?: number, + dsn?: string, + user?: { + name?: string, + email?: string + } +} + + +// --- Helper Interfaces for complex Data Structures -------------- +export interface RavenPlugin { (raven: RavenStatic, ...args: any[]): RavenStatic; } + +export interface RavenUserContext { + id?: string; + username?: string; + email?: string; + ip_address?: string; + extra?: { [prop: string]: any }; +} + +export interface RavenBreadcrumb { + message: string; + data: { [id: string]: string }; + category: string; + level: string; +} diff --git a/raven-js/raven-js-tests.ts b/raven-js/raven-js-tests.ts index 9608e41322..bbd3285e1e 100644 --- a/raven-js/raven-js-tests.ts +++ b/raven-js/raven-js-tests.ts @@ -1,24 +1,24 @@ - - import RavenJS from 'raven-js'; RavenJS.config('https://public@getsentry.com/1').install(); -var options: RavenOptions = { - logger: 'my-logger', - ignoreUrls: [ - /graph\.facebook\.com/i - ], - ignoreErrors: [ - 'fb_xd_fragment' - ], - includePaths: [ - /https?:\/\/(www\.)?getsentry\.com/, - /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ - ] -}; -Raven.config('https://public@getsentry.com/1', options).install(); +RavenJS.config( + 'https://public@getsentry.com/1', + { + logger: 'my-logger', + ignoreUrls: [ + /graph\.facebook\.com/i + ], + ignoreErrors: [ + 'fb_xd_fragment' + ], + includePaths: [ + /https?:\/\/(www\.)?getsentry\.com/, + /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ + ] + } +).install(); var throwsError = () => { throw new Error('broken'); @@ -27,28 +27,35 @@ var throwsError = () => { try { throwsError(); } catch(e) { - Raven.captureException(e); - Raven.captureException(e, {tags: { key: "value" }}); + RavenJS.captureException(e); + RavenJS.captureException(e, {tags: { key: "value" }}); } -Raven.context(throwsError); -Raven.context({tags: { key: "value" }}, throwsError); -Raven.context({extra: {planet: {name: 'Earth'}}}, throwsError); +RavenJS.context(throwsError); +RavenJS.context({tags: { key: "value" }}, throwsError); +RavenJS.context({extra: {planet: {name: 'Earth'}}}, throwsError); -setTimeout(Raven.wrap(throwsError), 1000); -Raven.wrap({logger: "my.module"}, throwsError)(); -Raven.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); +setTimeout(RavenJS.wrap(throwsError), 1000); +RavenJS.wrap({logger: "my.module"}, throwsError)(); +RavenJS.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); -Raven.setUserContext({ +RavenJS.setUserContext({ email: 'matt@example.com', id: '123' }); -Raven.captureMessage('Broken!'); -Raven.captureMessage('Broken!', {tags: { key: "value" }}); +RavenJS.captureMessage('Broken!'); +RavenJS.captureMessage('Broken!', {tags: { key: "value" }}); -Raven.showReportDialog(options); +RavenJS.showReportDialog({ + eventId: 0815, + dsn:'1337asdf', + user: { + name: 'DefenitelyTyped', + email: 'df@ts.ms' + } +}); -Raven.setTagsContext({ key: "value" }); +RavenJS.setTagsContext({ key: "value" }); -Raven.setExtraContext({ foo: "bar" }); +RavenJS.setExtraContext({ foo: "bar" }); diff --git a/react-breadcrumbs/index.d.ts b/react-breadcrumbs/index.d.ts index af35bccaa1..6fecdb7dc2 100644 --- a/react-breadcrumbs/index.d.ts +++ b/react-breadcrumbs/index.d.ts @@ -1,14 +1,18 @@ -// Type definitions for react-breadcrumbs 1.3.16 +// Type definitions for react-breadcrumbs 1.3 // Project: https://github.com/svenanders/react-breadcrumbs // Definitions by: Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// -/// +import * as React from "react"; +import * as ReactRouter from "react-router"; -declare namespace ReactBreadcrumbs { - interface BreadcrumbsProps extends React.Props { +export = Breadcrumbs; +type Breadcrumbs = React.ComponentClass; +declare const Breadcrumbs: Breadcrumbs; + +declare namespace Breadcrumbs { + interface Props extends React.ClassAttributes { separator?: string | JSX.Element; displayMissing?: boolean; prettify?: boolean; @@ -27,13 +31,4 @@ declare namespace ReactBreadcrumbs { setDocumentTitle?: boolean; params?: any; // todo make it compatible with params of the ReactRouter.RouteComponentProps } - - interface Breadcrumbs extends React.ComponentClass {} - const Breadcrumbs: Breadcrumbs; -} - -declare module 'react-breadcrumbs' { - import Breadcrumbs = ReactBreadcrumbs.Breadcrumbs; - - export = Breadcrumbs; } diff --git a/react-breadcrumbs/tsconfig.json b/react-breadcrumbs/tsconfig.json index 0092616bce..d1a0ccc542 100644 --- a/react-breadcrumbs/tsconfig.json +++ b/react-breadcrumbs/tsconfig.json @@ -10,7 +10,8 @@ "strictNullChecks": false, "baseUrl": "../", "paths": { - "history": ["history/v2"] + "history": ["history/v2"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" diff --git a/react-datepicker/index.d.ts b/react-datepicker/index.d.ts index 3ceedaa99a..ae33a5c24f 100644 --- a/react-datepicker/index.d.ts +++ b/react-datepicker/index.d.ts @@ -1,12 +1,13 @@ -// Type definitions for react-datepicker v0.28.1 +// Type definitions for react-datepicker v0.40.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// - declare module "react-datepicker" { + import * as React from "react"; + import * as moment from "moment"; + interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; @@ -15,7 +16,7 @@ declare module "react-datepicker" { dateFormat?: string; dateFormatCalendar?: string; disabled?: boolean; - endDate?: {}; + endDate?: moment.Moment; excludeDates?: any[]; filterDate?(): any; fixedHeight?: boolean; @@ -23,12 +24,12 @@ declare module "react-datepicker" { includeDates?: any[]; isClearable?: boolean; locale?: string; - maxDate?: {}; - minDate?: {}; + maxDate?: moment.Moment; + minDate?: moment.Moment; name?: string; - onBlur?(e: any): void; - onChange(date?: any, e?: any): void; - onFocus?(e: any): void; + onBlur?(event: React.FocusEvent): void; + onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): any; + onFocus?(event: React.FocusEvent): void; peekNextMonth?: boolean; placeholderText?: string; popoverAttachment?: string; @@ -38,13 +39,13 @@ declare module "react-datepicker" { renderCalendarTo?: any; required?: boolean; scrollableYearDropdown?: boolean; - selected?: {}; + selected?: moment.Moment | null; selectsEnd?: boolean; selectsStart?: boolean; showMonthDropdown?: boolean; showYearDropdown?: boolean; showWeekNumbers?: boolean; - startDate?: {}; + startDate?: moment.Moment; tabIndex?: number; tetherConstraints?: any[]; title?: string; diff --git a/react-datepicker/react-datepicker-tests.tsx b/react-datepicker/react-datepicker-tests.tsx index 53cd4723b5..df1b02dacf 100644 --- a/react-datepicker/react-datepicker-tests.tsx +++ b/react-datepicker/react-datepicker-tests.tsx @@ -2,8 +2,8 @@ import * as React from "react"; import * as moment from 'moment'; import * as DatePicker from 'react-datepicker'; -class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:string}> { - constructor(props:any) { +class ReactDatePicker extends React.Component<{}, { startDate: moment.Moment; displayName:string; }> { + constructor(props: {}) { super(); this.state = { startDate: moment(), @@ -12,7 +12,7 @@ class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:str this.handleChange = this.handleChange.bind(this); } - handleChange = function(date?:any) { + handleChange = function(date?: moment.Moment | null) { this.setState({ startDate: date }); diff --git a/react-i18next/tsconfig.json b/react-i18next/tsconfig.json index bba519bbd3..c64579c2e8 100644 --- a/react-i18next/tsconfig.json +++ b/react-i18next/tsconfig.json @@ -11,7 +11,8 @@ "baseUrl": "../", "paths": { "history": ["history/v2"], - "history/*": ["history/v2/*"] + "history/*": ["history/v2/*"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" diff --git a/react-router-bootstrap/index.d.ts b/react-router-bootstrap/index.d.ts index 7cf6ebaafc..99e7a6052a 100644 --- a/react-router-bootstrap/index.d.ts +++ b/react-router-bootstrap/index.d.ts @@ -1,44 +1,8 @@ -// Type definitions for react-router-bootstrap +// Type definitions for react-router-bootstrap 0.23 // Project: https://github.com/react-bootstrap/react-router-bootstrap -// Definitions by: Vincent Lesierse +// Definitions by: Vincent Lesierse , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// -/// - -declare namespace ReactRouterBootstrap { - interface LinkContainerProps extends ReactRouter.LinkProps { - disabled?: boolean - } - interface LinkContainer extends React.ComponentClass {} - interface LinkContainerElement extends React.ReactElement {} - const LinkContainer: LinkContainer - - const IndexLinkContainer: LinkContainer -} - -declare module "react-router-bootstrap/lib/LinkContainer" { - - export default ReactRouterBootstrap.LinkContainer - -} - -declare module "react-router-bootstrap/lib/IndexLinkContainer" { - - export default ReactRouterBootstrap.IndexLinkContainer - -} - -declare module "react-router-bootstrap" { - - import LinkContainer from "react-router-bootstrap/lib/LinkContainer" - - import IndexLinkContainer from "react-router-bootstrap/lib/IndexLinkContainer" - - export { - LinkContainer, - IndexLinkContainer - } - -} +export { default as LinkContainer } from "react-router-bootstrap/lib/LinkContainer" +export { default as IndexLinkContainer } from "react-router-bootstrap/lib/IndexLinkContainer" diff --git a/react-router-bootstrap/lib/IndexLinkContainer.d.ts b/react-router-bootstrap/lib/IndexLinkContainer.d.ts new file mode 100644 index 0000000000..045edc1fde --- /dev/null +++ b/react-router-bootstrap/lib/IndexLinkContainer.d.ts @@ -0,0 +1,7 @@ +import { ComponentClass } from "react"; +import { IndexLinkProps } from "react-router/lib/IndexLink"; + +type IndexLinkContainer = ComponentClass; +declare const IndexLinkContainer: IndexLinkContainer; + +export default IndexLinkContainer; diff --git a/react-router-bootstrap/lib/LinkContainer.d.ts b/react-router-bootstrap/lib/LinkContainer.d.ts new file mode 100644 index 0000000000..df5ac3cbdb --- /dev/null +++ b/react-router-bootstrap/lib/LinkContainer.d.ts @@ -0,0 +1,7 @@ +import { ComponentClass } from "react"; +import { LinkProps } from "react-router/lib/Link"; + +type LinkContainer = ComponentClass; +declare const LinkContainer: LinkContainer; + +export default LinkContainer; diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index 7e111b1004..1760fc3f1a 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -10,9 +10,6 @@ "strictNullChecks": false, "jsx": "preserve", "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], @@ -22,6 +19,8 @@ }, "files": [ "index.d.ts", + "lib/IndexLinkContainer.d.ts", + "lib/LinkContainer.d.ts", "react-router-bootstrap-tests.tsx" ] } diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index 62c6137a7a..226b3152e3 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -1,66 +1,60 @@ -// Type definitions for react-router-redux v4.0.0 +// Type definitions for react-router-redux 4.0 // Project: https://github.com/rackt/react-router-redux -// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg +// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +import { Action, Middleware, Store } from "redux"; +import { History } from "history"; +import { Location, LocationDescriptor } from "react-router"; -import * as Redux from "redux"; -import * as History from "history"; +export const CALL_HISTORY_METHOD: string; +export const LOCATION_CHANGE: string; -export = ReactRouterRedux; - -declare namespace ReactRouterRedux { - import R = Redux; - - const CALL_HISTORY_METHOD: string; - const LOCATION_CHANGE: string; - - const push: PushAction; - const replace: ReplaceAction; - const go: GoAction; - const goBack: GoForwardAction; - const goForward: GoBackAction; - const routerActions: RouteActions; - - type LocationDescriptor = History.LocationDescriptor; - type PushAction = (nextLocation: LocationDescriptor) => RouterAction; - type ReplaceAction = (nextLocation: LocationDescriptor) => RouterAction; - type GoAction = (n: number) => RouterAction; - type GoForwardAction = () => RouterAction; - type GoBackAction = () => RouterAction; - - type RouterAction = { - type: string - payload?: LocationDescriptor - } - - interface RouteActions { - push: PushAction; - replace: ReplaceAction; - go: GoAction; - goForward: GoForwardAction; - goBack: GoBackAction; - } - interface ReactRouterReduxHistory extends History.History { - unsubscribe(): void; - } - - interface DefaultSelectLocationState extends Function { - (state: any): any; - } - - interface SyncHistoryWithStoreOptions { - selectLocationState?: DefaultSelectLocationState; - adjustUrlOnReplay?: boolean; - } - - interface RouterState { - locationBeforeTransitions: History.Location - } - - function routerReducer(state?: RouterState, action?: R.Action): RouterState; - function syncHistoryWithStore(history: History.History, store: R.Store, options?: SyncHistoryWithStoreOptions): ReactRouterReduxHistory; - function routerMiddleware(history: History.History): R.Middleware; +export interface LocationActionPayload { + method: string; + args?: any[]; } + +export interface RouterAction extends Action { + payload?: LocationActionPayload; +} + +type LocationAction = (nextLocation: LocationDescriptor) => RouterAction; +type GoAction = (n: number) => RouterAction; +type NavigateAction = () => RouterAction; + +export const push: LocationAction; +export const replace: LocationAction; +export const go: GoAction; +export const goBack: NavigateAction; +export const goForward: NavigateAction; + +interface RouteActions { + push: typeof push; + replace: typeof replace; + go: typeof go; + goForward: typeof goForward; + goBack: typeof goBack; +} + +export const routerActions: RouteActions; + +export interface RouterState { + locationBeforeTransitions: Location; +} + +export type DefaultSelectLocationState = (state: any) => RouterState; + +export interface SyncHistoryWithStoreOptions { + selectLocationState?: DefaultSelectLocationState; + adjustUrlOnReplay?: boolean; +} + +export interface HistoryUnsubscribe { + unsubscribe(): void; +} + +export function routerReducer(state?: RouterState, action?: Action): RouterState; +export function syncHistoryWithStore(history: History, store: Store, options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribe; +export function routerMiddleware(history: History): Middleware; diff --git a/react-router-redux/react-router-redux-tests.ts b/react-router-redux/react-router-redux-tests.ts index 1d73706c4e..bcf4eaaed1 100644 --- a/react-router-redux/react-router-redux-tests.ts +++ b/react-router-redux/react-router-redux-tests.ts @@ -1,13 +1,21 @@ -/// -/// - import { createStore, combineReducers, applyMiddleware } from 'redux'; -import { browserHistory } from 'react-router'; -import { syncHistoryWithStore, routerReducer, routerMiddleware, push, replace, go, goForward, goBack } from 'react-router-redux'; +import { createBrowserHistory } from 'history'; +import { + syncHistoryWithStore, + routerReducer, + routerMiddleware, + push, + replace, + go, + goForward, + goBack, + routerActions +} from 'react-router-redux'; const reducer = combineReducers({ routing: routerReducer }); // Apply the middleware to the store +const browserHistory = createBrowserHistory() const middleware = routerMiddleware(browserHistory); const store = createStore( reducer, @@ -25,3 +33,8 @@ store.dispatch(replace('/foo')); store.dispatch(go(1)); store.dispatch(goForward()); store.dispatch(goBack()); +store.dispatch(routerActions.push('/foo')); +store.dispatch(routerActions.replace('/foo')); +store.dispatch(routerActions.go(1)); +store.dispatch(routerActions.goForward()); +store.dispatch(routerActions.goBack()); diff --git a/react-router-redux/tsconfig.json b/react-router-redux/tsconfig.json index 66c3e91f9b..0b29093460 100644 --- a/react-router-redux/tsconfig.json +++ b/react-router-redux/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "react-router-redux-tests.ts" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -11,16 +7,17 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ - "../" + "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } -} \ No newline at end of file + }, + "files": [ + "index.d.ts", + "react-router-redux-tests.ts" + ] +} diff --git a/react-router-redux/tslint.json b/react-router-redux/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-router-redux/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-router-redux/v3/index.d.ts b/react-router-redux/v3/index.d.ts index e0b3a62698..105d081f30 100644 --- a/react-router-redux/v3/index.d.ts +++ b/react-router-redux/v3/index.d.ts @@ -7,40 +7,38 @@ import * as Redux from "redux"; import * as History from "history"; -/// -declare namespace ReactRouterRedux { - const TRANSITION: string; - const UPDATE_LOCATION: string; +export const TRANSITION: string; +export const UPDATE_LOCATION: string; - const push: PushAction; - const replace: ReplaceAction; - const go: GoAction; - const goBack: GoForwardAction; - const goForward: GoBackAction; - const routeActions: RouteActions; +export const push: PushAction; +export const replace: ReplaceAction; +export const go: GoAction; +export const goBack: GoForwardAction; +export const goForward: GoBackAction; +export const routeActions: RouteActions; - type LocationDescriptor = History.LocationDescriptor; - type PushAction = (nextLocation: LocationDescriptor) => void; - type ReplaceAction = (nextLocation: LocationDescriptor) => void; - type GoAction = (n: number) => void; - type GoForwardAction = () => void; - type GoBackAction = () => void; +export type LocationDescriptor = History.LocationDescriptor; +export type PushAction = (nextLocation: LocationDescriptor) => void; +export type ReplaceAction = (nextLocation: LocationDescriptor) => void; +export type GoAction = (n: number) => void; +export type GoForwardAction = () => void; +export type GoBackAction = () => void; - interface RouteActions { - push: PushAction; - replace: ReplaceAction; - go: GoAction; - goForward: GoForwardAction; - goBack: GoBackAction; - } - interface HistoryMiddleware extends Redux.Middleware { - listenForReplays(store: Redux.Store, selectLocationState?: Function): void; - unsubscribe(): void; - } - - function routeReducer(state?: any, options?: any): Redux.Reducer; - function syncHistory(history: History.History): HistoryMiddleware; +export interface RouteActions { + push: PushAction; + replace: ReplaceAction; + go: GoAction; + goForward: GoForwardAction; + goBack: GoBackAction; } -export = ReactRouterRedux; +export interface HistoryMiddleware extends Redux.Middleware { + listenForReplays(store: Redux.Store, selectLocationState?: Function): void; + unsubscribe(): void; +} + +export function routeReducer(state?: any, options?: any): Redux.Reducer; +export function syncHistory(history: History.History): HistoryMiddleware; + + diff --git a/react-router-redux/v3/react-router-redux-tests.ts b/react-router-redux/v3/react-router-redux-tests.ts index b92af315b2..90d68841ff 100644 --- a/react-router-redux/v3/react-router-redux-tests.ts +++ b/react-router-redux/v3/react-router-redux-tests.ts @@ -1,16 +1,11 @@ - -/// -/// - - - import { createStore, combineReducers, applyMiddleware } from 'redux'; -import { browserHistory } from 'react-router'; +import { createBrowserHistory } from 'history'; import { syncHistory, routeReducer } from 'react-router-redux'; const reducer = combineReducers({ routing: routeReducer }); // Sync dispatched route actions to the history +const browserHistory = createBrowserHistory() const reduxRouterMiddleware = syncHistory(browserHistory); const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware)(createStore); diff --git a/react-router-redux/v3/tslint.json b/react-router-redux/v3/tslint.json new file mode 100644 index 0000000000..5e200e7d9b --- /dev/null +++ b/react-router-redux/v3/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-empty-interface": false + } +} diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 4e265ce99f..da1f23c87e 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -1,92 +1,70 @@ // Type definitions for react-router 3.0 // Project: https://github.com/rackt/react-router -// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , John Reilly +// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , John Reilly , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +/* Replacement from old history definitions */ +export interface HistoryOptions { + getCurrentLocation?(): Location; + getUserConfirmation?(message: string, callback: (result: boolean) => void): void; + pushLocation?(nextLocation: Location): void; + replaceLocation?(nextLocation: Location): void; + go?(n: number): void; + keyLength?: number; +} -export as namespace ReactRouter; - -import * as React from 'react'; - -export const routerShape: React.Requireable; - -export const locationShape: React.Requireable; - -import Router from "./lib/Router"; -import Link from "./lib/Link"; -import IndexLink from "./lib/IndexLink"; -import IndexRedirect from "./lib/IndexRedirect"; -import IndexRoute from "./lib/IndexRoute"; -import Redirect from "./lib/Redirect"; -import Route from "./lib/Route"; -import * as History from "./lib/routerHistory"; -import Lifecycle from "./lib/Lifecycle"; -import RouteContext from "./lib/RouteContext"; -import browserHistory from "./lib/browserHistory"; -import hashHistory from "./lib/hashHistory"; -import useRoutes from "./lib/useRoutes"; -import { createRoutes } from "./lib/RouteUtils"; -import { formatPattern } from "./lib/PatternUtils"; -import RouterContext from "./lib/RouterContext"; -import PropTypes from "./lib/PropTypes"; -import match from "./lib/match"; -import useRouterHistory from "./lib/useRouterHistory"; -import createMemoryHistory from "./lib/createMemoryHistory"; -import withRouter from "./lib/withRouter"; -import applyRouterMiddleware from "./lib/applyRouterMiddleware"; - -// PlainRoute is defined in the API documented at: -// https://github.com/rackt/react-router/blob/master/docs/API.md -// but not included in any of the .../lib modules above. -export type PlainRoute = Router.PlainRoute; - -// The following definitions are also very useful to export -// because by using these types lots of potential type errors -// can be exposed: -export type EnterHook = Router.EnterHook; -export type LeaveHook = Router.LeaveHook; -export type ParseQueryString = Router.ParseQueryString; -export type LocationDescriptor = Router.LocationDescriptor; -export type RedirectFunction = Router.RedirectFunction; -export type RouteComponent = Router.RouteComponent; -export type RouteComponentProps = Router.RouteComponentProps; -export type RouteConfig = Router.RouteConfig; -export type RouteHook = Router.RouteHook; -export type StringifyQuery = Router.StringifyQuery; -export type RouterListener = Router.RouterListener; -export type RouterState = Router.RouterState; -export type InjectedRouter = Router.InjectedRouter; - -export type HistoryBase = History.HistoryBase; -export type RouterOnContext = Router.RouterOnContext; -export type RouteProps = Route.RouteProps; -export type LinkProps = Link.LinkProps; +export type CreateHistory = (options?: HistoryOptions) => T; +export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; export { - Router, - Link, - IndexLink, - IndexRedirect, - IndexRoute, - Redirect, - Route, - History, - browserHistory, - hashHistory, - Lifecycle, - RouteContext, - useRoutes, - createRoutes, - formatPattern, - RouterContext, - PropTypes, - match, - useRouterHistory, - createMemoryHistory, - withRouter, - applyRouterMiddleware -}; + Basename, + ChangeHook, + EnterHook, + InjectedRouter, + LeaveHook, + Location, + LocationDescriptor, + ParseQueryString, + RouteComponent, + RouteComponents, + RouteComponentProps, + RouteConfig, + RoutePattern, + RouterProps, + RouterState, + StringifyQuery, + Query +} from "react-router/lib/Router"; +export { LinkProps } from "react-router/lib/Link"; +export { IndexLinkProps } from "react-router/lib/IndexLink"; +export { RouteProps, PlainRoute } from "react-router/lib/Route"; +export { IndexRouteProps } from "react-router/lib/IndexRoute"; +export { RedirectProps } from "react-router/lib/Redirect"; +export { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -export default Router; +/* components */ +export { default as Router } from "react-router/lib/Router"; +export { default as Link } from "react-router/lib/Link"; +export { default as IndexLink } from "react-router/lib/IndexLink"; +export { default as withRouter } from "react-router/lib/withRouter"; + +/* components (configuration) */ +export { default as IndexRedirect } from "react-router/lib/IndexRedirect"; +export { default as IndexRoute } from "react-router/lib/IndexRoute"; +export { default as Redirect } from "react-router/lib/Redirect"; +export { default as Route } from "react-router/lib/Route"; + +/* utils */ +export { createRoutes } from "react-router/lib/RouteUtils"; +export { default as RouterContext } from "react-router/lib/RouterContext"; +export { routerShape, locationShape } from "react-router/lib/PropTypes"; +export { default as match } from "react-router/lib/match"; +export { default as useRouterHistory } from "react-router/lib/useRouterHistory"; +export { formatPattern } from "react-router/lib/PatternUtils"; +export { default as applyRouterMiddleware } from "react-router/lib/applyRouterMiddleware"; + +/* histories */ +export { default as browserHistory } from "react-router/lib/browserHistory"; +export { default as hashHistory } from "react-router/lib/hashHistory"; +export { default as createMemoryHistory } from "react-router/lib/createMemoryHistory"; diff --git a/react-router/lib/IndexLink.d.ts b/react-router/lib/IndexLink.d.ts index 56ecf82c1d..0c62010262 100644 --- a/react-router/lib/IndexLink.d.ts +++ b/react-router/lib/IndexLink.d.ts @@ -1,5 +1,15 @@ -import Link from './Link'; +import { ComponentClass, CSSProperties, HTMLProps } from "react"; +import { Location, LocationDescriptor } from "react-router/lib/Router"; + +type ToLocationFunction = (location: Location) => LocationDescriptor; + +export interface IndexLinkProps extends HTMLProps { + to: LocationDescriptor | ToLocationFunction; + activeClassName?: string; + activeStyle?: CSSProperties; +} + +type IndexLink = ComponentClass; +declare const IndexLink: IndexLink; -declare const IndexLink: Link; export default IndexLink; - diff --git a/react-router/lib/IndexRedirect.d.ts b/react-router/lib/IndexRedirect.d.ts index 41dab299c8..3b8187d09b 100644 --- a/react-router/lib/IndexRedirect.d.ts +++ b/react-router/lib/IndexRedirect.d.ts @@ -1,17 +1,12 @@ -import Router from './Router'; -import * as React from 'react'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { RoutePattern, Query } from "react-router"; -declare const self: self.IndexRedirect; -type self = self.IndexRedirect; -export default self; - -declare namespace self { - interface IndexRedirectProps extends React.Props { - to: Router.RoutePattern; - query?: H.Query; - state?: H.LocationState; - } - interface IndexRedirectElement extends React.ReactElement { } - interface IndexRedirect extends React.ComponentClass { } +export interface IndexRedirectProps extends ClassAttributes { + to: RoutePattern; + query?: Query; } + +type IndexRedirect = ComponentClass; +declare const IndexRedirect: IndexRedirect; + +export default IndexRedirect; diff --git a/react-router/lib/IndexRoute.d.ts b/react-router/lib/IndexRoute.d.ts index b11b16d0e2..b0574df26a 100644 --- a/react-router/lib/IndexRoute.d.ts +++ b/react-router/lib/IndexRoute.d.ts @@ -1,20 +1,28 @@ -import * as React from 'react'; -import Router from './Router'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { LocationState } from "history"; +import { + EnterHook, + ChangeHook, + LeaveHook, + RouteComponent, + RouteComponents, + RouterState +} from "react-router"; -declare const self: self.IndexRoute; -type self = self.IndexRoute; -export default self; +type ComponentCallback = (err: any, component: RouteComponent) => void; +type ComponentsCallback = (err: any, components: RouteComponents) => void; -declare namespace self { - interface IndexRouteProps extends React.Props { - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (location: H.Location, cb: (error: any, component?: Router.RouteComponent) => void) => void; - getComponents?: (location: H.Location, cb: (error: any, components?: Router.RouteComponents) => void) => void; - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - } - interface IndexRoute extends React.ComponentClass { } - interface IndexRouteElement extends React.ReactElement { } -} \ No newline at end of file +export interface IndexRouteProps { + component?: RouteComponent; + components?: RouteComponents; + getComponent?(nextState: RouterState, callback: ComponentCallback): void; + getComponents?(nextState: RouterState, callback: ComponentsCallback): void; + onEnter?: EnterHook; + onChange?: ChangeHook; + onLeave?: LeaveHook; +} + +type IndexRoute = ComponentClass; +declare const IndexRoute: IndexRoute; + +export default IndexRoute; diff --git a/react-router/lib/Link.d.ts b/react-router/lib/Link.d.ts index d90578b9f9..eca6e66abd 100644 --- a/react-router/lib/Link.d.ts +++ b/react-router/lib/Link.d.ts @@ -1,19 +1,11 @@ -import * as React from 'react'; -import Router from './Router'; +import { ComponentClass, CSSProperties, HTMLProps } from "react"; +import { IndexLinkProps } from "react-router/lib/IndexLink"; +export interface LinkProps extends IndexLinkProps { + onlyActiveOnIndex?: boolean; +} + +type Link = ComponentClass; declare const Link: Link; -type Link = Link.Link; export default Link; - -declare namespace Link { - interface LinkProps extends React.HTMLAttributes { - activeStyle?: React.CSSProperties; - activeClassName?: string; - onlyActiveOnIndex?: boolean; - to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); - } - - interface Link extends React.ComponentClass {} - interface LinkElement extends React.ReactElement {} -} diff --git a/react-router/lib/PatternUtils.d.ts b/react-router/lib/PatternUtils.d.ts index 50e90f6e49..2c32b2a286 100644 --- a/react-router/lib/PatternUtils.d.ts +++ b/react-router/lib/PatternUtils.d.ts @@ -1 +1,3 @@ -export function formatPattern(pattern: string, params: {}): string; +import { RoutePattern } from "react-router"; + +export function formatPattern(pattern: RoutePattern, params: any): string; diff --git a/react-router/lib/PropTypes.d.ts b/react-router/lib/PropTypes.d.ts index bbd6431070..c9140777cb 100644 --- a/react-router/lib/PropTypes.d.ts +++ b/react-router/lib/PropTypes.d.ts @@ -1,19 +1,22 @@ -import * as React from 'react'; +import { Requireable, Validator } from "react"; -export function falsy(props: any, propName: string, componentName: string): Error; -export const history: React.Requireable; -export const location: React.Requireable; -export const component: React.Requireable; -export const components: React.Requireable; -export const route: React.Requireable; -export const routes: React.Requireable; +export interface RouterShape extends Validator { + push: Requireable; + replace: Requireable; + go: Requireable; + goBack: Requireable; + goForward: Requireable; + setRouteLeaveHook: Requireable; + isActive: Requireable; +} -export default { - falsy, - history, - location, - component, - components, - route -}; +export interface LocationShape extends Validator { + pathname: Requireable; + search: Requireable; + state: any; + action: Requireable; + key: any; +} +export const routerShape: RouterShape; +export const locationShape: LocationShape; diff --git a/react-router/lib/Redirect.d.ts b/react-router/lib/Redirect.d.ts index e09b576d53..bb8254b4f5 100644 --- a/react-router/lib/Redirect.d.ts +++ b/react-router/lib/Redirect.d.ts @@ -1,19 +1,12 @@ -import * as React from 'react'; -import Router from './Router'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { RoutePattern, Query } from "react-router"; +import { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -declare const self: self.Redirect; -type self = typeof self; -export default self; - -declare namespace self { - interface RedirectProps extends React.Props { - path?: Router.RoutePattern; - from?: Router.RoutePattern; // alias for path - to: Router.RoutePattern; - query?: H.Query; - state?: H.LocationState; - } - interface Redirect extends React.ComponentClass { } - interface RedirectElement extends React.ReactElement { } +export interface RedirectProps extends IndexRedirectProps { + from: RoutePattern; } + +type Redirect = ComponentClass; +declare const Redirect: Redirect; + +export default Redirect; diff --git a/react-router/lib/Route.d.ts b/react-router/lib/Route.d.ts index cf1e6a7fc4..15aafebc75 100644 --- a/react-router/lib/Route.d.ts +++ b/react-router/lib/Route.d.ts @@ -1,25 +1,31 @@ -import * as React from 'react'; -import Router from './Router'; -import { Location } from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { LocationState } from "history"; +import { + EnterHook, + ChangeHook, + LeaveHook, + RouteComponent, + RouteComponents, + RoutePattern, + RouterState +} from "react-router"; +import { IndexRouteProps } from "react-router/lib/IndexRoute"; -declare const self: self.Route; -type self = self.Route; -export default self; +export interface RouteProps extends IndexRouteProps { + path?: RoutePattern; +} -declare namespace self { +type Route = ComponentClass; +declare const Route: Route; - interface RouteProps extends React.Props { - path?: Router.RoutePattern; - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void; - getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void; - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - onChange?: Router.ChangeHook; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; - } - interface Route extends React.ComponentClass {} - interface RouteElement extends React.ReactElement {} -} \ No newline at end of file +export default Route; + +type RouteCallback = (err: any, route: PlainRoute) => void; +type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; + +export interface PlainRoute extends RouteProps { + childRoutes?: PlainRoute[]; + getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; + indexRoute?: PlainRoute; + getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): void; +} diff --git a/react-router/lib/RouteUtils.d.ts b/react-router/lib/RouteUtils.d.ts index 7065056ff5..6304f5d7bf 100644 --- a/react-router/lib/RouteUtils.d.ts +++ b/react-router/lib/RouteUtils.d.ts @@ -1,8 +1,3 @@ -import * as React from 'react'; -import Router from './Router'; +import { RouteConfig, PlainRoute } from "react-router"; -type E = React.ReactElement; -export function isReactChildren(object: E | E[]): boolean; -export function createRouteFromReactElement(element: E): Router.PlainRoute; -export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[]; -export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[]; +export function createRoutes(routes: RouteConfig): PlainRoute[]; diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index ccfc22979a..dbd2d43fff 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -1,117 +1,108 @@ -import * as React from 'react'; -import RouterContext from './RouterContext'; +import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; import { - QueryString, Query, - Location, LocationDescriptor, LocationState as HLocationState, - History, Href, - Pathname, Path } from 'history'; + Action, + Hash, + History, + Href, + LocationKey, + LocationState, + Path, + Pathname, + Search +} from "history"; +import { PlainRoute } from "react-router"; +/* Replacement from old history definitions */ +export type Basename = string; +export type Query = any; +export interface Params { + [key: string]: string; +} + +export type RoutePattern = string; +export type RouteComponent = ComponentClass | StatelessComponent; +export interface RouteComponents { + [name: string]: RouteComponent; +} +export type RouteConfig = ReactNode | PlainRoute | PlainRoute[]; + +export type ParseQueryString = (queryString: Search) => Query; +export type StringifyQuery = (queryObject: Query) => Search; + +type AnyFunction = (...args: any[]) => any; + +export type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; +export type LeaveHook = (prevState: RouterState) => any; +export type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; +export type RouteHook = (nextLocation?: Location) => any; + +export interface Location { + patname: Pathname; + search: Search; + query: Query; + state: LocationState; + action: Action; + key: LocationKey; +} + +export interface LocationDescriptorObject { + pathname?: Pathname; + query?: Query; + hash?: Hash; + state?: LocationState; +} + +export type LocationDescriptor = Path | LocationDescriptorObject; + +export interface RedirectFunction { + (location: LocationDescriptor): void; + (state: LocationState, pathname: Pathname | Path, query?: Query): void; +} + +export interface RouterState { + location: Location; + routes: PlainRoute[]; + params: Params; + components: RouteComponent[]; +} + +type LocationFunction = (location: LocationDescriptor) => void; +type GoFunction = (n: number) => void; +type NavigateFunction = () => void; +type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean; +type LeaveHookFunction = (route: any, callback: RouteHook) => void; +type CreatePartFunction = (path: Path, query?: any) => Part; + +export interface InjectedRouter { + push: LocationFunction; + replace: LocationFunction; + go: GoFunction; + goBack: NavigateFunction; + goForward: NavigateFunction; + setRouteLeaveHook: LeaveHookFunction; + createPath: CreatePartFunction; + createHref: CreatePartFunction; + isActive: ActiveFunction; +} + +export interface RouteComponentProps { + location?: Location; + params?: P & R; + route?: PlainRoute; + router?: InjectedRouter; + routeParams?: R; +} + +export interface RouterProps extends ClassAttributes { + routes?: RouteConfig; + history?: History; + createElement?(component: RouteComponent, props: any): any; + onError?(error: any): any; + onUpdate?(): any; + render?(props: any): ReactNode; +} + +type Router = ComponentClass; declare const Router: Router; -interface Router extends React.ComponentClass { } export default Router; - -// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md - -declare namespace Router { - type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; - type RoutePattern = string; - interface RouteComponents { [key: string]: RouteComponent; } - - type ParseQueryString = (queryString: QueryString) => Query; - type StringifyQuery = (queryObject: Query) => QueryString; - - type Component = React.ReactType; - type RouteComponent = Component; - - type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; - type LeaveHook = () => void; - type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; - type RouteHook = (nextLocation?: Location) => any; - - interface Params { [param: string]: string; } - - type RouterListener = (error: Error, nextState: RouterState) => void; - - interface LocationDescriptor { - pathname?: Pathname; - query?: Query; - hash?: Href; - state?: HLocationState; - } - - interface RedirectFunction { - (location: LocationDescriptor): void; - /** - * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated - */ - (state: HLocationState, pathname: Pathname | Path, query?: Query): void; - } - - interface RouterState { - location: Location; - routes: PlainRoute[]; - params: Params; - components: RouteComponent[]; - } - - interface RouterProps extends React.Props { - history?: History; - routes?: RouteConfig; // alias for children - createElement?: (component: RouteComponent, props: Object) => any; - onError?: (error: any) => any; - onUpdate?: () => any; - parseQueryString?: ParseQueryString; - stringifyQuery?: StringifyQuery; - basename?: string; - render?: (renderProps: React.Props<{}>) => RouterContext; - } - - interface PlainRoute { - path?: RoutePattern; - component?: RouteComponent; - components?: RouteComponents; - getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; - getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; - onEnter?: EnterHook; - onLeave?: LeaveHook; - indexRoute?: PlainRoute; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; - childRoutes?: PlainRoute[]; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; - } - - interface RouteComponentProps { - history?: History; - location?: Location; - params?: P; - route?: PlainRoute; - routeParams?: R; - router?: InjectedRouter; - routes?: PlainRoute[]; - children?: React.ReactElement; - } - - interface RouterOnContext extends History { - setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; - isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; - } - - // Wrap a component using withRouter(Component) to provide a router object - // to the Component's props, allowing the Component to programmatically call - // push and other functions. - // - // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md - - interface InjectedRouter { - push: (pathOrLoc: Path | LocationDescriptor) => void; - replace: (pathOrLoc: Path | LocationDescriptor) => void; - go: (n: number) => void; - goBack: () => void; - goForward: () => void; - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void; - createPath(path: History.Path, query?: History.Query): History.Path; - createHref(path: History.Path, query?: History.Query): History.Href; - isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean; - } -} diff --git a/react-router/lib/RouterContext.d.ts b/react-router/lib/RouterContext.d.ts index b6eab5831c..b04e6e01ae 100644 --- a/react-router/lib/RouterContext.d.ts +++ b/react-router/lib/RouterContext.d.ts @@ -1,25 +1,6 @@ -import * as React from 'react'; -import * as H from 'history'; -import Router from './Router'; +import { ComponentClass } from "react"; -declare const self: self.RouterContext; -type self = self.RouterContext; -export default self; +type RouterContext = ComponentClass; +declare const RouterContext: RouterContext; -declare namespace self { - interface RouterContextProps extends React.Props { - history?: H.History; - router: Router; - createElement: (component: Router.RouteComponent, props: Object) => any; - location: H.Location; - routes: Router.RouteConfig; - params: Router.Params; - components?: Router.RouteComponent[]; - } - interface RouterContext extends React.ComponentClass {} - interface RouterContextElement extends React.ReactElement { - history?: H.History; - location: H.Location; - router?: Router; - } -} \ No newline at end of file +export default RouterContext; diff --git a/react-router/lib/applyRouterMiddleware.d.ts b/react-router/lib/applyRouterMiddleware.d.ts index ed87d815db..e4d023a792 100644 --- a/react-router/lib/applyRouterMiddleware.d.ts +++ b/react-router/lib/applyRouterMiddleware.d.ts @@ -1,9 +1,9 @@ -import * as React from 'react'; -import Router from './Router'; -import RouterContext from './RouterContext'; +import { RouteComponent } from "react-router"; +import RouterContext from "react-router/lib/RouterContext"; export interface Middleware { - renderRouterContext?: (previous: RouterContext, props: React.Props<{}>) => RouterContext; - renderRouteComponent?: (previous: Router.RouteComponent, props: React.Props<{}>) => Router.RouteComponent; + renderRouterContext?: (previous: RouterContext, props: any) => RouterContext; + renderRouteComponent?: (previous: RouteComponent, props: any) => RouteComponent; } -export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => RouterContext; + +export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: any) => RouterContext; diff --git a/react-router/lib/browserHistory.d.ts b/react-router/lib/browserHistory.d.ts index aabbdc23f9..8f45db6412 100644 --- a/react-router/lib/browserHistory.d.ts +++ b/react-router/lib/browserHistory.d.ts @@ -1,3 +1,5 @@ -import { History } from './routerHistory'; +import { History } from "history"; + declare const browserHistory: History; + export default browserHistory; diff --git a/react-router/lib/createMemoryHistory.d.ts b/react-router/lib/createMemoryHistory.d.ts index 5df481bfa1..038e707e6b 100644 --- a/react-router/lib/createMemoryHistory.d.ts +++ b/react-router/lib/createMemoryHistory.d.ts @@ -1,3 +1,6 @@ -import * as H from 'history'; +import { History } from "history"; +import { CreateHistory } from "react-router"; -export default function createMemoryHistory(options?: H.HistoryOptions): H.History; \ No newline at end of file +declare const createMemoryHistory: CreateHistory; + +export default createMemoryHistory; diff --git a/react-router/lib/hashHistory.d.ts b/react-router/lib/hashHistory.d.ts index 79f89c2f1a..6a17e65af9 100644 --- a/react-router/lib/hashHistory.d.ts +++ b/react-router/lib/hashHistory.d.ts @@ -1,3 +1,5 @@ -import { History } from './routerHistory'; +import { History } from "history"; + declare const hashHistory: History; + export default hashHistory; diff --git a/react-router/lib/match.d.ts b/react-router/lib/match.d.ts index e311ea69df..407bcc80c2 100644 --- a/react-router/lib/match.d.ts +++ b/react-router/lib/match.d.ts @@ -1,17 +1,24 @@ -import * as H from 'history'; -import Router from './Router'; +import { History } from "history"; +import { Basename, LocationDescriptor, ParseQueryString, RouteConfig, StringifyQuery } from "react-router"; interface MatchArgs { - routes?: Router.RouteConfig; - history?: H.History; - location?: H.Location | string; - parseQueryString?: Router.ParseQueryString; - stringifyQuery?: Router.StringifyQuery; + routes: RouteConfig; + basename?: Basename; + parseQueryString?: ParseQueryString; + stringifyQuery?: StringifyQuery; } -interface MatchState extends Router.RouterState { - history: H.History; - router: Router; - createElement: (component: Router.RouteComponent, props: Object) => any; + +interface MatchLocationArgs extends MatchArgs { + location: LocationDescriptor; + history?: History; } -export default function match(args: MatchArgs, cb: (error: any, nextLocation: H.Location, nextState: MatchState) => void): void; + +interface MatchHistoryArgs extends MatchArgs { + location?: LocationDescriptor; + history: History; +} + +export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => void; + +export default function match(args: MatchLocationArgs | MatchHistoryArgs, cb: MatchCallback): void; diff --git a/react-router/lib/useRouterHistory.d.ts b/react-router/lib/useRouterHistory.d.ts index 160375d2f0..7dc2bdd3ab 100644 --- a/react-router/lib/useRouterHistory.d.ts +++ b/react-router/lib/useRouterHistory.d.ts @@ -1,3 +1,6 @@ -import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; +import { History } from "history"; +import { CreateHistoryEnhancer } from "react-router"; -export default function useRouterHistory(createHistory: CreateHistory): (options?: HistoryOptions) => History & HistoryQueries; +declare const useRouterHistory: CreateHistoryEnhancer; + +export default useRouterHistory; diff --git a/react-router/lib/withRouter.d.ts b/react-router/lib/withRouter.d.ts index 71330bbb21..25f9d357c7 100644 --- a/react-router/lib/withRouter.d.ts +++ b/react-router/lib/withRouter.d.ts @@ -1,4 +1,9 @@ -import * as React from 'react'; +import { ComponentClass, StatelessComponent } from "react"; -declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C; -export default withRouter; +interface Options { + withRef?: boolean; +} + +type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export default function withRouter

(component: ComponentConstructor

, options?: Options): ComponentClass

; diff --git a/react-router/react-router-tests.tsx b/react-router/react-router-tests.tsx index 6c83ca180a..894dfec8c7 100644 --- a/react-router/react-router-tests.tsx +++ b/react-router/react-router-tests.tsx @@ -1,22 +1,39 @@ -import * as React from "react" -import * as ReactDOM from "react-dom" -import {renderToString} from "react-dom/server"; +import * as React from "react"; +import { Component, ValidationMap } from "react"; +import * as ReactDOM from "react-dom"; +import { renderToString } from "react-dom/server"; -import { applyRouterMiddleware, browserHistory, hashHistory, match, createMemoryHistory, withRouter, routerShape, Router, Route, IndexRoute, InjectedRouter, Link, RouterOnContext, RouterContext, LinkProps} from "react-router"; +import { + applyRouterMiddleware, + browserHistory, + hashHistory, + match, + createMemoryHistory, + withRouter, + routerShape, + Router, + Route, + IndexRoute, + InjectedRouter, + Link, + RouterContext, + LinkProps +} from "react-router"; const NavLink = (props: LinkProps) => ( ) interface MasterContext { - router: RouterOnContext; + router: InjectedRouter; } -class Master extends React.Component, {}> { +class Master extends Component { - static contextTypes: React.ValidationMap = { - router: routerShape + static contextTypes: ValidationMap = { + "router": routerShape }; + context: MasterContext; navigate() { @@ -106,7 +123,11 @@ const routes = ( ); -match({history, routes, location: "baseurl"}, (error, redirectLocation, renderProps) => { +match({ routes, location: "baseurl" }, (error, redirectLocation, renderProps) => { + renderToString(); +}); + +match({ history, routes }, (error, redirectLocation, renderProps) => { renderToString(); }); diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index 69c7baf8e5..e2a4e054ad 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "react-router-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -14,14 +10,31 @@ "strictNullChecks": false, "jsx": "react", "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "lib/applyRouterMiddleware.d.ts", + "lib/browserHistory.d.ts", + "lib/createMemoryHistory.d.ts", + "lib/hashHistory.d.ts", + "lib/IndexLink.d.ts", + "lib/IndexRedirect.d.ts", + "lib/IndexRoute.d.ts", + "lib/Link.d.ts", + "lib/match.d.ts", + "lib/PatternUtils.d.ts", + "lib/PropTypes.d.ts", + "lib/Redirect.d.ts", + "lib/Route.d.ts", + "lib/Router.d.ts", + "lib/RouterContext.d.ts", + "lib/RouteUtils.d.ts", + "lib/useRouterHistory.d.ts", + "lib/withRouter.d.ts", + "react-router-tests.tsx" + ] } diff --git a/react-router/tslint.json b/react-router/tslint.json index e050abdce9..f9e30021f4 100644 --- a/react-router/tslint.json +++ b/react-router/tslint.json @@ -1,7 +1,3 @@ { - "extends": "../tslint.json", - "rules": { - "forbidden-types": false, - "no-empty-interface": false - } -} \ No newline at end of file + "extends": "../tslint.json" +} diff --git a/react-router/v2/index.d.ts b/react-router/v2/index.d.ts new file mode 100644 index 0000000000..b0a96487bf --- /dev/null +++ b/react-router/v2/index.d.ts @@ -0,0 +1,90 @@ +// Type definitions for react-router 2.0 +// Project: https://github.com/rackt/react-router +// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace ReactRouter; + +import * as React from 'react'; + +export const routerShape: React.Requireable; + +export const locationShape: React.Requireable; + +import Router from "./lib/Router"; +import Link from "./lib/Link"; +import IndexLink from "./lib/IndexLink"; +import IndexRedirect from "./lib/IndexRedirect"; +import IndexRoute from "./lib/IndexRoute"; +import Redirect from "./lib/Redirect"; +import Route from "./lib/Route"; +import * as History from "./lib/routerHistory"; +import Lifecycle from "./lib/Lifecycle"; +import RouteContext from "./lib/RouteContext"; +import browserHistory from "./lib/browserHistory"; +import hashHistory from "./lib/hashHistory"; +import useRoutes from "./lib/useRoutes"; +import { createRoutes } from "./lib/RouteUtils"; +import { formatPattern } from "./lib/PatternUtils"; +import RouterContext from "./lib/RouterContext"; +import PropTypes from "./lib/PropTypes"; +import match from "./lib/match"; +import useRouterHistory from "./lib/useRouterHistory"; +import createMemoryHistory from "./lib/createMemoryHistory"; +import withRouter from "./lib/withRouter"; +import applyRouterMiddleware from "./lib/applyRouterMiddleware"; + +// PlainRoute is defined in the API documented at: +// https://github.com/rackt/react-router/blob/master/docs/API.md +// but not included in any of the .../lib modules above. +export type PlainRoute = Router.PlainRoute; + +// The following definitions are also very useful to export +// because by using these types lots of potential type errors +// can be exposed: +export type EnterHook = Router.EnterHook; +export type LeaveHook = Router.LeaveHook; +export type ParseQueryString = Router.ParseQueryString; +export type LocationDescriptor = Router.LocationDescriptor; +export type RedirectFunction = Router.RedirectFunction; +export type RouteComponent = Router.RouteComponent; +export type RouteComponentProps = Router.RouteComponentProps; +export type RouteConfig = Router.RouteConfig; +export type RouteHook = Router.RouteHook; +export type StringifyQuery = Router.StringifyQuery; +export type RouterListener = Router.RouterListener; +export type RouterState = Router.RouterState; +export type InjectedRouter = Router.InjectedRouter; + +export type HistoryBase = History.HistoryBase; +export type RouterOnContext = Router.RouterOnContext; +export type RouteProps = Route.RouteProps; +export type LinkProps = Link.LinkProps; + +export { + Router, + Link, + IndexLink, + IndexRedirect, + IndexRoute, + Redirect, + Route, + History, + browserHistory, + hashHistory, + Lifecycle, + RouteContext, + useRoutes, + createRoutes, + formatPattern, + RouterContext, + PropTypes, + match, + useRouterHistory, + createMemoryHistory, + withRouter, + applyRouterMiddleware +}; + +export default Router; diff --git a/react-router/v2/lib/IndexLink.d.ts b/react-router/v2/lib/IndexLink.d.ts new file mode 100644 index 0000000000..56ecf82c1d --- /dev/null +++ b/react-router/v2/lib/IndexLink.d.ts @@ -0,0 +1,5 @@ +import Link from './Link'; + +declare const IndexLink: Link; +export default IndexLink; + diff --git a/react-router/v2/lib/IndexRedirect.d.ts b/react-router/v2/lib/IndexRedirect.d.ts new file mode 100644 index 0000000000..41dab299c8 --- /dev/null +++ b/react-router/v2/lib/IndexRedirect.d.ts @@ -0,0 +1,17 @@ +import Router from './Router'; +import * as React from 'react'; +import * as H from 'history'; + +declare const self: self.IndexRedirect; +type self = self.IndexRedirect; +export default self; + +declare namespace self { + interface IndexRedirectProps extends React.Props { + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface IndexRedirectElement extends React.ReactElement { } + interface IndexRedirect extends React.ComponentClass { } +} diff --git a/react-router/v2/lib/IndexRoute.d.ts b/react-router/v2/lib/IndexRoute.d.ts new file mode 100644 index 0000000000..b11b16d0e2 --- /dev/null +++ b/react-router/v2/lib/IndexRoute.d.ts @@ -0,0 +1,20 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.IndexRoute; +type self = self.IndexRoute; +export default self; + +declare namespace self { + interface IndexRouteProps extends React.Props { + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (location: H.Location, cb: (error: any, component?: Router.RouteComponent) => void) => void; + getComponents?: (location: H.Location, cb: (error: any, components?: Router.RouteComponents) => void) => void; + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + } + interface IndexRoute extends React.ComponentClass { } + interface IndexRouteElement extends React.ReactElement { } +} \ No newline at end of file diff --git a/react-router/lib/Lifecycle.d.ts b/react-router/v2/lib/Lifecycle.d.ts similarity index 100% rename from react-router/lib/Lifecycle.d.ts rename to react-router/v2/lib/Lifecycle.d.ts diff --git a/react-router/v2/lib/Link.d.ts b/react-router/v2/lib/Link.d.ts new file mode 100644 index 0000000000..d90578b9f9 --- /dev/null +++ b/react-router/v2/lib/Link.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; + +declare const Link: Link; +type Link = Link.Link; + +export default Link; + +declare namespace Link { + interface LinkProps extends React.HTMLAttributes { + activeStyle?: React.CSSProperties; + activeClassName?: string; + onlyActiveOnIndex?: boolean; + to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); + } + + interface Link extends React.ComponentClass {} + interface LinkElement extends React.ReactElement {} +} diff --git a/react-router/v2/lib/PatternUtils.d.ts b/react-router/v2/lib/PatternUtils.d.ts new file mode 100644 index 0000000000..50e90f6e49 --- /dev/null +++ b/react-router/v2/lib/PatternUtils.d.ts @@ -0,0 +1 @@ +export function formatPattern(pattern: string, params: {}): string; diff --git a/react-router/v2/lib/PropTypes.d.ts b/react-router/v2/lib/PropTypes.d.ts new file mode 100644 index 0000000000..bbd6431070 --- /dev/null +++ b/react-router/v2/lib/PropTypes.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; + +export function falsy(props: any, propName: string, componentName: string): Error; +export const history: React.Requireable; +export const location: React.Requireable; +export const component: React.Requireable; +export const components: React.Requireable; +export const route: React.Requireable; +export const routes: React.Requireable; + +export default { + falsy, + history, + location, + component, + components, + route +}; + diff --git a/react-router/v2/lib/Redirect.d.ts b/react-router/v2/lib/Redirect.d.ts new file mode 100644 index 0000000000..e09b576d53 --- /dev/null +++ b/react-router/v2/lib/Redirect.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.Redirect; +type self = typeof self; +export default self; + +declare namespace self { + interface RedirectProps extends React.Props { + path?: Router.RoutePattern; + from?: Router.RoutePattern; // alias for path + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface Redirect extends React.ComponentClass { } + interface RedirectElement extends React.ReactElement { } +} diff --git a/react-router/v2/lib/Route.d.ts b/react-router/v2/lib/Route.d.ts new file mode 100644 index 0000000000..7e4b548a21 --- /dev/null +++ b/react-router/v2/lib/Route.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import Router from './Router'; +import { Location } from 'history'; + +declare const self: self.Route; +type self = self.Route; +export default self; + +declare namespace self { + + interface RouteProps extends React.Props { + path?: Router.RoutePattern; + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void; + getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void; + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + onChange?: Router.ChangeHook; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; + } + interface Route extends React.ComponentClass {} + interface RouteElement extends React.ReactElement {} +} diff --git a/react-router/lib/RouteContext.d.ts b/react-router/v2/lib/RouteContext.d.ts similarity index 100% rename from react-router/lib/RouteContext.d.ts rename to react-router/v2/lib/RouteContext.d.ts diff --git a/react-router/v2/lib/RouteUtils.d.ts b/react-router/v2/lib/RouteUtils.d.ts new file mode 100644 index 0000000000..7065056ff5 --- /dev/null +++ b/react-router/v2/lib/RouteUtils.d.ts @@ -0,0 +1,8 @@ +import * as React from 'react'; +import Router from './Router'; + +type E = React.ReactElement; +export function isReactChildren(object: E | E[]): boolean; +export function createRouteFromReactElement(element: E): Router.PlainRoute; +export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[]; +export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[]; diff --git a/react-router/v2/lib/Router.d.ts b/react-router/v2/lib/Router.d.ts new file mode 100644 index 0000000000..a7dff58369 --- /dev/null +++ b/react-router/v2/lib/Router.d.ts @@ -0,0 +1,116 @@ +import * as React from 'react'; +import RouterContext from './RouterContext'; +import { + QueryString, Query, + Location, LocationDescriptor, LocationState as HLocationState, + History, Href, + Pathname, Path } from 'history'; + +declare const Router: Router; +interface Router extends React.ComponentClass { } + +export default Router; + +// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md + +declare namespace Router { + type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; + type RoutePattern = string; + interface RouteComponents { [key: string]: RouteComponent; } + + type ParseQueryString = (queryString: QueryString) => Query; + type StringifyQuery = (queryObject: Query) => QueryString; + + type Component = React.ReactType; + type RouteComponent = Component; + + type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; + type LeaveHook = () => void; + type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; + type RouteHook = (nextLocation?: Location) => any; + + interface Params { [param: string]: string; } + + type RouterListener = (error: Error, nextState: RouterState) => void; + + interface LocationDescriptor { + pathname?: Pathname; + query?: Query; + hash?: Href; + state?: HLocationState; + } + + interface RedirectFunction { + (location: LocationDescriptor): void; + /** + * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated + */ + (state: HLocationState, pathname: Pathname | Path, query?: Query): void; + } + + interface RouterState { + location: Location; + routes: PlainRoute[]; + params: Params; + components: RouteComponent[]; + } + + interface RouterProps extends React.Props { + history?: History; + routes?: RouteConfig; // alias for children + createElement?: (component: RouteComponent, props: Object) => any; + onError?: (error: any) => any; + onUpdate?: () => any; + parseQueryString?: ParseQueryString; + stringifyQuery?: StringifyQuery; + basename?: string; + render?: (renderProps: React.Props<{}>) => RouterContext; + } + + interface PlainRoute { + path?: RoutePattern; + component?: RouteComponent; + components?: RouteComponents; + getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; + getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; + onEnter?: EnterHook; + onLeave?: LeaveHook; + indexRoute?: PlainRoute; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; + childRoutes?: PlainRoute[]; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; + } + + interface RouteComponentProps { + history?: History; + location?: Location; + params?: P; + route?: PlainRoute; + routeParams?: R; + routes?: PlainRoute[]; + children?: React.ReactElement; + } + + interface RouterOnContext extends History { + setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; + isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; + } + + // Wrap a component using withRouter(Component) to provide a router object + // to the Component's props, allowing the Component to programmatically call + // push and other functions. + // + // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md + + interface InjectedRouter { + push: (pathOrLoc: Path | LocationDescriptor) => void; + replace: (pathOrLoc: Path | LocationDescriptor) => void; + go: (n: number) => void; + goBack: () => void; + goForward: () => void; + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void; + createPath(path: History.Path, query?: History.Query): History.Path; + createHref(path: History.Path, query?: History.Query): History.Href; + isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean; + } +} diff --git a/react-router/v2/lib/RouterContext.d.ts b/react-router/v2/lib/RouterContext.d.ts new file mode 100644 index 0000000000..b6eab5831c --- /dev/null +++ b/react-router/v2/lib/RouterContext.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import * as H from 'history'; +import Router from './Router'; + +declare const self: self.RouterContext; +type self = self.RouterContext; +export default self; + +declare namespace self { + interface RouterContextProps extends React.Props { + history?: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; + location: H.Location; + routes: Router.RouteConfig; + params: Router.Params; + components?: Router.RouteComponent[]; + } + interface RouterContext extends React.ComponentClass {} + interface RouterContextElement extends React.ReactElement { + history?: H.History; + location: H.Location; + router?: Router; + } +} \ No newline at end of file diff --git a/react-router/v2/lib/applyRouterMiddleware.d.ts b/react-router/v2/lib/applyRouterMiddleware.d.ts new file mode 100644 index 0000000000..ed87d815db --- /dev/null +++ b/react-router/v2/lib/applyRouterMiddleware.d.ts @@ -0,0 +1,9 @@ +import * as React from 'react'; +import Router from './Router'; +import RouterContext from './RouterContext'; + +export interface Middleware { + renderRouterContext?: (previous: RouterContext, props: React.Props<{}>) => RouterContext; + renderRouteComponent?: (previous: Router.RouteComponent, props: React.Props<{}>) => Router.RouteComponent; +} +export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => RouterContext; diff --git a/react-router/v2/lib/browserHistory.d.ts b/react-router/v2/lib/browserHistory.d.ts new file mode 100644 index 0000000000..aabbdc23f9 --- /dev/null +++ b/react-router/v2/lib/browserHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const browserHistory: History; +export default browserHistory; diff --git a/react-router/v2/lib/createMemoryHistory.d.ts b/react-router/v2/lib/createMemoryHistory.d.ts new file mode 100644 index 0000000000..5df481bfa1 --- /dev/null +++ b/react-router/v2/lib/createMemoryHistory.d.ts @@ -0,0 +1,3 @@ +import * as H from 'history'; + +export default function createMemoryHistory(options?: H.HistoryOptions): H.History; \ No newline at end of file diff --git a/react-router/v2/lib/hashHistory.d.ts b/react-router/v2/lib/hashHistory.d.ts new file mode 100644 index 0000000000..79f89c2f1a --- /dev/null +++ b/react-router/v2/lib/hashHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const hashHistory: History; +export default hashHistory; diff --git a/react-router/v2/lib/match.d.ts b/react-router/v2/lib/match.d.ts new file mode 100644 index 0000000000..e311ea69df --- /dev/null +++ b/react-router/v2/lib/match.d.ts @@ -0,0 +1,17 @@ +import * as H from 'history'; +import Router from './Router'; + +interface MatchArgs { + routes?: Router.RouteConfig; + history?: H.History; + location?: H.Location | string; + parseQueryString?: Router.ParseQueryString; + stringifyQuery?: Router.StringifyQuery; +} +interface MatchState extends Router.RouterState { + history: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; +} +export default function match(args: MatchArgs, cb: (error: any, nextLocation: H.Location, nextState: MatchState) => void): void; + diff --git a/react-router/lib/routerHistory.d.ts b/react-router/v2/lib/routerHistory.d.ts similarity index 100% rename from react-router/lib/routerHistory.d.ts rename to react-router/v2/lib/routerHistory.d.ts diff --git a/react-router/v2/lib/useRouterHistory.d.ts b/react-router/v2/lib/useRouterHistory.d.ts new file mode 100644 index 0000000000..160375d2f0 --- /dev/null +++ b/react-router/v2/lib/useRouterHistory.d.ts @@ -0,0 +1,3 @@ +import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; + +export default function useRouterHistory(createHistory: CreateHistory): (options?: HistoryOptions) => History & HistoryQueries; diff --git a/react-router/lib/useRoutes.d.ts b/react-router/v2/lib/useRoutes.d.ts similarity index 100% rename from react-router/lib/useRoutes.d.ts rename to react-router/v2/lib/useRoutes.d.ts diff --git a/react-router/v2/lib/withRouter.d.ts b/react-router/v2/lib/withRouter.d.ts new file mode 100644 index 0000000000..71330bbb21 --- /dev/null +++ b/react-router/v2/lib/withRouter.d.ts @@ -0,0 +1,4 @@ +import * as React from 'react'; + +declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C; +export default withRouter; diff --git a/react-router/v2/tsconfig.json b/react-router/v2/tsconfig.json new file mode 100644 index 0000000000..d9c384bdcf --- /dev/null +++ b/react-router/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "history": ["history/v2"], + "react-router": ["react-router/v2"], + "react-router/*": ["react-router/v2/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} diff --git a/react-router/v2/tslint.json b/react-router/v2/tslint.json new file mode 100644 index 0000000000..d032145676 --- /dev/null +++ b/react-router/v2/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-empty-interface": false + } +} diff --git a/realm/index.d.ts b/realm/index.d.ts index ad77dc5598..034d9e390f 100644 --- a/realm/index.d.ts +++ b/realm/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for realm-js 0.14.3 +// Type definitions for realm-js 0.14 // Project: https://github.com/realm/realm-js // Definitions by: Akim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -94,7 +94,7 @@ declare namespace Realm { * Collection * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Collection.html } */ - export interface Collection { + export interface Collection { readonly length: number; /** @@ -107,24 +107,24 @@ declare namespace Realm { * @param {any[]} ...arg * @returns Results */ - filtered(query: string, ...arg: any[]): Results; + filtered(query: string, ...arg: any[]): Results; /** * @param {string|SortDescriptor} descriptor * @param {boolean} reverse? * @returns Results */ - sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; - + sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; + /** - * @returns Iterator + * @returns Iterator */ - [Symbol.iterator](): Iterator; + [Symbol.iterator](): Iterator; /** * @returns Results */ - snapshot(): Results; + snapshot(): Results; /** * @returns Iterator @@ -150,65 +150,65 @@ declare namespace Realm { /** * @param {number} start? * @param {number} end? - * @returns Object + * @returns T[] | Object[] */ - slice(start?: number, end?: number): Object[]; + slice(start?: number, end?: number): T[]; /** * @param {(object:any,index?:any,collection?:any)=>void} callback * @param {any} thisArg? * @returns Object|void */ - find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): Object | void; + find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): T | null | undefined; /** * @param {(object:any,index?:any,collection?:any)=>void} callback * @param {any} thisArg? * @returns number */ - findIndex(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): number; + findIndex(callback: (object: any, index?: number, collection?: any) => void, thisArg?: any): number; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T|any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns void */ - forEach(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): void; + forEach(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): void; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T|any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns boolean */ - every(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): boolean; + every(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): boolean; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns boolean */ - some(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): boolean; + some(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): boolean; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns any */ - map(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): any[]; + map(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): any[]; + + /** + * @param {(previousValue:T|any,object?:any,index?:number,collection?:any)=>void} callback + * @param {any} initialValue? + * @returns any + */ + reduce(callback: (previousValue: T, object?: T, index?: number, collection?: any) => void, initialValue?: any): any; /** * @param {(previousValue:any,object?:any,index?:any,collection?:any)=>void} callback * @param {any} initialValue? * @returns any */ - reduce(callback: (previousValue: any, object?: any, index?: any, collection?: any) => void, initialValue?: any): any; - - /** - * @param {(previousValue:any,object?:any,index?:any,collection?:any)=>void} callback - * @param {any} initialValue? - * @returns any - */ - reduceRight(callback: (previousValue: any, object?: any, index?: any, collection?: any) => void, initialValue?: any): any; + reduceRight(callback: (previousValue: T, object?: T, index?: any, collection?: any) => void, initialValue?: any): any; } /** @@ -226,22 +226,22 @@ declare namespace Realm { * List * @see { @link https://realm.io/docs/react-native/latest/api/Realm.List.html } */ - export interface List extends Collection { + export interface List extends Collection { /** * @returns Object|void */ - pop(): Object | void; + pop(): T | null | undefined; /** * @param {any} object * @returns number */ - push(object: any): number; + push(object: T): number; /** * @returns Object|void */ - shift(): Object | void; + shift(): T | null | undefined; /** * @param {number} index @@ -249,20 +249,20 @@ declare namespace Realm { * @param {any} object? * @returns Object */ - splice(index: number, count?: number, object?: any): Object[]; + splice(index: number, count?: number, object?: any): T[]; /** * @param {any} object * @returns number */ - unshift(object: any): number; + unshift(object: T): number; } /** * Results * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Results.html } */ - export interface Results extends Collection {} + export type Results = Collection; } declare class Realm { @@ -297,13 +297,13 @@ declare class Realm { * @param {boolean} update? * @returns Realm.Object|T|any */ - create(type: string | Realm.ObjectType, properties: Realm.ObjectPropsType, update?: boolean): Realm.Object | T | any; + create(type: string | Realm.ObjectType, properties: T & Realm.ObjectPropsType, update?: boolean): T; /** * @param {Realm.Object|Realm.Object[]|Realm.List|Realm.Results|any} object * @returns void */ - delete(object: Realm.Object | Realm.Object[] | Realm.List | Realm.Results | any): void; + delete(object: Realm.Object | Realm.Object[] | Realm.List | Realm.Results | any): void; /** * @returns void @@ -315,13 +315,13 @@ declare class Realm { * @param {number|string} key * @returns Realm.Object|void */ - objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): Realm.Object | void; + objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): T | void; /** * @param {string|Realm.ObjectType} type * @returns Realm.Results */ - objects(type: string | Realm.ObjectType): Realm.Results; + objects(type: string | Realm.ObjectType): Realm.ObjectType & Realm.Results; /** * @param {string} name diff --git a/realm/tslint.json b/realm/tslint.json new file mode 100644 index 0000000000..ccdb64abf2 --- /dev/null +++ b/realm/tslint.json @@ -0,0 +1,2 @@ +{ "extends": "../tslint.json" } + diff --git a/redis/index.d.ts b/redis/index.d.ts index 75745b99f4..0e7e2ec4de 100644 --- a/redis/index.d.ts +++ b/redis/index.d.ts @@ -94,6 +94,16 @@ export interface RedisClient extends NodeJS.EventEmitter { end(): void; unref(): void; + /** + * Stop sending commands and queue the commands. + */ + cork(): void; + + /** + * Resume and send the queued commands at once. + */ + uncork(): void; + // Low level command execution send_command(command: string, ...args: any[]): boolean; diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index d98979f256..e0315a809f 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -112,4 +112,10 @@ client.monitor(resCallback); // Send command client.send_command(str, args, resCallback); // Duplicate -client.duplicate(); \ No newline at end of file +client.duplicate(); + +// Pipeline +client.cork(); +client.set("abc", "fff", strCallback); +client.get("abc", resCallback); +client.uncork(); diff --git a/redux-bootstrap/index.d.ts b/redux-bootstrap/index.d.ts index 171cf4d764..60d53bb713 100644 --- a/redux-bootstrap/index.d.ts +++ b/redux-bootstrap/index.d.ts @@ -1,30 +1,30 @@ -// Type definitions for react-bootstrap v1.0.0 +// Type definitions for react-bootstrap 1.0 // Project: https://github.com/remojansen/redux-bootstrap // Definitions by: Remo H. Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -declare module "redux-bootstrap" { - import * as Redux from "redux"; - import ReactRouterRedux = require("react-router-redux"); +import * as React from "react"; +import { Middleware, Reducer, Store } from "redux"; +import { History } from "history"; - interface BootstrapOptions { - routes: JSX.Element; - reducers: ReducersOption; - middlewares?: Redux.Middleware[]; - initialState?: any; - container?: string; - } - - interface BootstrapResult { - store: Redux.Store; - history: ReactRouterRedux.ReactRouterReduxHistory; - root: JSX.Element; - } - - interface ReducersOption { - [index: string]: Redux.Reducer; - } - - export default function bootstrap(options: BootstrapOptions): BootstrapResult; +export interface BootstrapOptions { + routes: JSX.Element; + reducers: ReducersOption; + middlewares?: Middleware[]; + initialState?: any; + container?: string; } + +export interface BootstrapResult { + store: Store; + history: History; + root: JSX.Element; +} + +export interface ReducersOption { + [index: string]: Reducer; +} + +export default function bootstrap(options: BootstrapOptions): BootstrapResult; + diff --git a/redux-bootstrap/tsconfig.json b/redux-bootstrap/tsconfig.json index a5c0900ca4..cca0524f9c 100644 --- a/redux-bootstrap/tsconfig.json +++ b/redux-bootstrap/tsconfig.json @@ -9,9 +9,6 @@ "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], diff --git a/redux-router/tsconfig.json b/redux-router/tsconfig.json index 786008c59c..10120c4840 100644 --- a/redux-router/tsconfig.json +++ b/redux-router/tsconfig.json @@ -10,7 +10,8 @@ "strictNullChecks": false, "baseUrl": "../", "paths": { - "history": ["history/v2"] + "history": ["history/v2"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" diff --git a/roslib/index.d.ts b/roslib/index.d.ts index c195387901..923bcb6396 100644 --- a/roslib/index.d.ts +++ b/roslib/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for roslib.js +// Type definitions for roslib.js 1.9 // Project: http://wiki.ros.org/roslibjs // Definitions by: Stefan Profanter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -67,6 +67,16 @@ declare namespace ROSLIB { */ callOnConnection(message:any):void; + /** + * Retrieves list of actionlib servers in ROS as an array. + * + * @param callback function with params: + * * action_servers - Array of actionlib servers names + * @param failedCallback - the callback function when the ros call failed (optional). Params: + * * error - the error message reported by ROS + */ + getActionServers(callback:(action_servers:string[]) => void, failedCallback?:(error:any)=>void):void; + /** * Retrieves list of topics in ROS as an array. * diff --git a/rx-lite/index.d.ts b/rx-lite/index.d.ts index fb5056c478..7e085031aa 100644 --- a/rx-lite/index.d.ts +++ b/rx-lite/index.d.ts @@ -232,7 +232,7 @@ declare namespace Rx { withLatestFrom(souces: (Observable | IPromise)[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; concat(...sources: (Observable | IPromise)[]): Observable; concat(sources: (Observable | IPromise)[]): Observable; - concatAll(): Observable; + concatAll(): T; concatObservable(): Observable; // alias for concatAll concatMap(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat concatMap(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts new file mode 100644 index 0000000000..aec379f5f2 --- /dev/null +++ b/shipit-utils/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for shipit-utils 1.4 +// Project: https://github.com/shipitjs/shipit-utils +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import shipit = require("shipit"); + +type GruntOrShipit = typeof shipit | {}; +type EmptyCallback = () => void; + +export function equalValues(value: any[]): void; +export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; +export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; +export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependenciesOrTask: string[] | EmptyCallback): typeof shipit; +export function runTask(gruntOrShipit: {}): void; diff --git a/shipit-utils/shipit-utils-tests.ts b/shipit-utils/shipit-utils-tests.ts new file mode 100644 index 0000000000..81cb741054 --- /dev/null +++ b/shipit-utils/shipit-utils-tests.ts @@ -0,0 +1,11 @@ +import shipit = require("shipit"); +import utils = require("shipit-utils"); + +var originalShipit = utils.getShipit(shipit); + +var task = () => { + return shipit.local("sleep 10s"); +}; + +utils.registerTask(originalShipit, "myTask", task); +utils.registerTask(originalShipit, "myTask", ["some", "other", "tasks"]); diff --git a/shipit-utils/tsconfig.json b/shipit-utils/tsconfig.json new file mode 100644 index 0000000000..d2fdb45d17 --- /dev/null +++ b/shipit-utils/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-utils-tests.ts" + ] +} diff --git a/shipit-utils/tslint.json b/shipit-utils/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit-utils/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/shipit/index.d.ts b/shipit/index.d.ts new file mode 100644 index 0000000000..8c614f1627 --- /dev/null +++ b/shipit/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for shipit-cli 1.5 +// Project: https://github.com/shipitjs/shipit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as fs from "fs"; +import * as child_process from "child_process"; + +declare namespace shipit { + type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; + type EmptyCallback = () => void; + type TaskExecution = (name: string, depsOrFn: string[] | EmptyCallback, fn: () => void) => any; + + interface Options { + environment: string; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + interface ShipitLocal { + child: child_process.ChildProcess; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + interface Tasks { + [name: string]: Task; + } + + interface Task { + blocking: boolean; + dep: string[]; + fn: () => void; + name: string; + } + + export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; + export function emit(name: string): any; + export function initConfig(config: {}): typeof shipit; + export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function log(log: any): void; + export function log(...log: any[]): void; + export function on(name: string, callback: (e: any) => void): any; + export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function start(tasks: string | string[]): typeof shipit; + export function start(...tasks: string[]): typeof shipit; + export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; + + export var config: {}; + export var domain: any; + export var doneCallback: any; + export var environment: string; + export var seq: any[]; + export var tasks: Tasks; + export var isRunning: boolean; +} + +//tslint:disable-next-line:export-just-namespace +export = shipit; +export as namespace shipit; diff --git a/shipit/shipit-tests.ts b/shipit/shipit-tests.ts new file mode 100644 index 0000000000..a256f87e07 --- /dev/null +++ b/shipit/shipit-tests.ts @@ -0,0 +1,50 @@ +import shipit = require("shipit"); + +shipit.initConfig({ + default: { + workspace: "/tmp/github-monitor", + deployTo: "/tmp/deploy_to", + repositoryUrl: "https://github.com/user/repo.git", + ignores: [".git", "node_modules"], + rsync: ["--del"], + keepReleases: 2, + key: "/path/to/key", + shallowClone: true + }, + staging: { + servers: "user@myserver.com" + } +}); + +shipit.task("build", () => { + shipit.emit("built"); +}); + +shipit.on("built", () => { + shipit.start("start-server"); +}); + +shipit.task("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.blTask("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.start("task"); +shipit.start("task1", "task2"); +shipit.start(["task1", "task2"]); + +shipit.local("ls -lah", {cwd: "/tmp/deploy/workspace"}).then((res: any) => { + console.log(res.stdout); + console.log(res.stderr); +}); + +shipit.remote("ls -lah").then((res: any) => { + console.log(res[0].stdout); + console.log(res[0].stderr); +}); + +shipit.remoteCopy("/tmp/workspace", "/opt/web/myapp").then(() => {}); +shipit.log("hello %s", "world"); diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json new file mode 100644 index 0000000000..17049e7271 --- /dev/null +++ b/shipit/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-tests.ts" + ] +} diff --git a/shipit/tslint.json b/shipit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/stripe/index.d.ts b/stripe/index.d.ts index a7d887c747..2563af9882 100644 --- a/stripe/index.d.ts +++ b/stripe/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for stripe 0.0 +// Type definitions for stripe 2.x // Project: https://stripe.com/ -// Definitions by: Andy Hawkins , Eric J. Smith , Amrit Kahlon , Adam Cmiel +// Definitions by: Andy Hawkins , Eric J. Smith , Amrit Kahlon , Adam Cmiel , Justin Leider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare const Stripe: StripeStatic; @@ -12,13 +12,13 @@ interface StripeStatic { validateExpiry(month: string, year: string): boolean; validateCVC(cardCVC: string): boolean; cardType(cardNumber: string): StripeCardDataBrand; - getToken(token: string, responseHandler: (status: number, response: StripeTokenResponse) => void): void; - card: StripeCardData; - createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; + getToken(token: string, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + card: StripeCard; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; bankAccount: StripeBankAccount; } -interface StripeTokenData { +interface StripeCardTokenData { number: string; exp_month?: number; exp_year?: number; @@ -35,7 +35,6 @@ interface StripeTokenData { interface StripeTokenResponse { id: string; - card: StripeCardData; created: number; livemode: boolean; object: string; @@ -44,6 +43,10 @@ interface StripeTokenResponse { error?: StripeError; } +interface StripeCardTokenResponse extends StripeTokenResponse { + card: StripeCard; +} + interface StripeError { type: string; code: string; @@ -53,7 +56,7 @@ interface StripeError { type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; -interface StripeCardData { +interface StripeCard { object: string; last4: string; exp_month: number; @@ -67,7 +70,10 @@ interface StripeCardData { address_zip?: string; address_country?: string; brand?: StripeCardDataBrand; - createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + validateCardNumber(cardNumber: string): boolean; + validateExpiry(month: string, year: string): boolean; + validateCVC(cardCVC: string): boolean; } interface StripeBankAccount { @@ -85,8 +91,7 @@ interface StripeBankTokenParams { account_holder_type: string; } -interface StripeBankTokenResponse { - id: string; +interface StripeBankTokenResponse extends StripeTokenResponse { bank_account: { country: string; bank_name: string; @@ -94,12 +99,6 @@ interface StripeBankTokenResponse { validated: boolean; object: string; }; - created: number; - livemode: boolean; - type: string; - object: string; - used: boolean; - error?: StripeError; } interface StripeApplePay { @@ -134,7 +133,7 @@ interface StripeApplePayLineItem { } interface StripeApplePaySessionResult { - token: StripeTokenResponse; + token: StripeCardTokenResponse; shippingContact?: StripeApplePayPaymentContact; shippingMethod?: StripeApplePayShippingMethod; } diff --git a/stripe/stripe-tests.ts b/stripe/stripe-tests.ts index 44aa09d216..56e6343f5c 100644 --- a/stripe/stripe-tests.ts +++ b/stripe/stripe-tests.ts @@ -1,4 +1,4 @@ -function success(card: StripeCardData) { +function success(card: StripeCard) { console.log(card.brand && card.brand.toString()); } @@ -6,7 +6,7 @@ const cardNumber = '4242424242424242'; const isValid = Stripe.validateCardNumber(cardNumber); if (isValid) { - const tokenData: StripeTokenData = { + const tokenData: StripeCardTokenData = { number: cardNumber, exp_month: 1, exp_year: 2100,