diff --git a/README.md b/README.md index 854cae7e40..c50d026338 100644 --- a/README.md +++ b/README.md @@ -256,7 +256,7 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat #### I want to update a package to a new major version -Before making your change, please create a new subfolder with the current version e.g. `v2`, and copy existing files to it. You will need to: +If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to: 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. @@ -279,7 +279,8 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi } ``` -Please note that unless upgrading something backwards-compatible like `node`, all packages depending of the updated package need a path mapping to it, as well as packages depending on *those*. +If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version. + For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`; transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index eb1cecf2d6..5c7026d70e 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -701,7 +701,7 @@ declare namespace algoliasearch { * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObjects(objects: [{}]): Promise; + addObjects(objects: {}[]): Promise; /** * Add or replace a specific object * @param object @@ -729,7 +729,7 @@ declare namespace algoliasearch { * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObjects(objects: [{}]): Promise; + partialUpdateObjects(objects: {}[]): Promise; /** * Delete a specific object * @param objectID @@ -1387,6 +1387,12 @@ Interface describing options available for gettings the logs * https://github.com/algolia/algoliasearch-client-js#unretrievableattributes */ unretrievableAttributes?: string[]; + /** + * List of attributes you want to use for textual search + * default: [] + * https://github.com/algolia/algoliasearch-client-js#searchableattributes + */ + searchableAttributes?: string[]; /** * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer * default: * @@ -1602,7 +1608,7 @@ Interface describing options available for gettings the logs * default: [] * https://github.com/algolia/algoliasearch-client-js#altcorrections */ - altCorrections?: [{}]; + altCorrections?: {}[]; /** * Configure the precision of the proximity ranking criterion * default: 1 diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 795e74a058..7f5649befb 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -548,80 +548,158 @@ namespace TestPromise { const promise: angular.IPromise = null; const $q: angular.IQService = null; - const assertPromiseType = (arg: angular.IPromise) => arg; const reject = $q.reject(); // promise.then - assertPromiseType(promise.then((result) => any)); - assertPromiseType(promise.then((result) => any, (any) => any)); - assertPromiseType(promise.then((result) => any, (any) => any, (any) => any)); + // $ExpectType IPromise + promise.then(result => any); + // $ExpectType IPromise + promise.then(result => any, any => any); + // $ExpectType IPromise + promise.then(result => any, any => any, any => any); - assertPromiseType(promise.then((result) => reject)); - assertPromiseType(promise.then((result) => reject, (any) => reject)); - assertPromiseType(promise.then((result) => reject, (any) => reject, (any) => any)); + // $ExpectType IPromise + promise.then(result => reject); + // $ExpectType IPromise + promise.then(result => reject, any => reject); + // $ExpectType IPromise + promise.then(result => reject, any => reject, any => any); - 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)); + // $ExpectType IPromise + promise.then(result => result); + // $ExpectType IPromise + promise.then(result => tresult); + // $ExpectType IPromise + promise.then(result => tresultPromise); + // $ExpectType IPromise + promise.then(result => result, any => any); + // $ExpectType IPromise + promise.then(result => result, any => Math.random()); + // $ExpectType IPromise + promise.then(result => result, any => any, any => any); + // $ExpectType IPromise + promise.then(result => result, any => Math.random(), any => any); + // $ExpectType IPromise + promise.then(result => result, any => reject, any => any); - assertPromiseType | TResult>(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) - )); + // $ExpectType IPromise + promise.then(result => anyOf2(reject, result)); + // $ExpectType IPromise + promise.then(result => anyOf3(result, tresultPromise, reject)); + // $ExpectType IPromise + promise.then( + result => anyOf3(reject, result, tresultPromise), + reason => anyOf3(reject, tresult, tresultPromise) + ); - assertPromiseType>(promise.then((result) => tresultHttpPromise)); + // $ExpectType IPromise> + promise.then(result => tresultHttpPromise); - assertPromiseType(promise.then((result) => result, (any) => tother)); - assertPromiseType | angular.IPromise | TOther | angular.IPromise>(promise.then( - (result) => anyOf3(reject, result, totherPromise), - (reason) => anyOf3(reject, tother, tresultPromise) - )); + // $ExpectType IPromise + promise.then(result => result, any => tother); - assertPromiseType(promise.then( - (result) => anyOf3(tresultPromise, result, totherPromise) - )); + // These are broken and seemingly can't be made to work + // with the current limitations of TypeScript. - 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)); + // xExpectType IPromise + // promise.then(result => anyOf2(result, totherPromise)); + // xExpectType IPromise + // promise.then(result => anyOf3(reject, result, totherPromise)); + // xExpectType IPromise + // const a4 = promise.then( + // result => anyOf3(reject, result, totherPromise), + // reason => anyOf3(reject, tother, tresultPromise) + // ); - 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)); + // $ExpectType IPromise + promise.then(result => + anyOf3(tresultPromise, result, totherPromise) + ); - assertPromiseType(promise.then((result) => tresult, (any) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); + // $ExpectType IPromise + promise.then(result => result, any => tother, any => any); + // $ExpectType IPromise + promise.then(result => tresultPromise, any => totherPromise); + // $ExpectType IPromise + promise.then(result => tresultPromise, any => totherPromise, any => any); + // $ExpectType IPromise | IHttpResponse> + promise.then(result => tresultHttpPromise, any => totherHttpPromise); + // $ExpectType IPromise | IHttpResponse> + promise.then(result => tresultHttpPromise, any => totherHttpPromise, any => any); + + // $ExpectType IPromise + promise.then(result => tother); + // $ExpectType IPromise + promise.then(result => tother, any => any); + // $ExpectType IPromise + promise.then(result => tother, any => any, any => any); + // $ExpectType IPromise + promise.then(result => totherPromise); + // $ExpectType IPromise + promise.then(result => totherPromise, any => any); + // $ExpectType IPromise + promise.then(result => totherPromise, any => any, any => any); + // $ExpectType IPromise> + promise.then(result => totherHttpPromise); + // $ExpectType IPromise + promise.then(result => totherHttpPromise, any => any); + // $ExpectType IPromise + promise.then(result => totherHttpPromise, any => any, any => any); + + // $ExpectType IPromise + promise + .then(result => tresult, any => tother) + .then(ambiguous => (isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); + + // promise.then + $q.reject: + + // $ExpectType IPromise + $q.resolve(true).then(result => Math.random() > 0.5 ? Math.random() : $q.reject()); + // $ExpectType IPromise + $q.resolve(true).then(result => Math.random() > 0.5 ? Math.random() : $q.reject('a')); + // $ExpectType IPromise + $q.resolve().then(() => $q.reject('a')); + // $ExpectType IPromise + $q.resolve().then(() => { + if (Math.random() > 0.5) $q.reject(); + }); // promise.catch - 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)); + // $ExpectType IPromise + promise.catch(err => err); + // $ExpectType IPromise + promise.catch(err => any); + // $ExpectType IPromise + promise.catch(err => tresult); + // $ExpectType IPromise + promise.catch(err => anyOf2(tresult, reject)); + // $ExpectType IPromise + promise.catch(err => anyOf3(tresult, tresultPromise, reject)); + // $ExpectType IPromise + promise.catch(err => tresultPromise); + // $ExpectType IPromise> + promise.catch(err => tresultHttpPromise); + // $ExpectType IPromise + promise.catch(err => tother); + // $ExpectType IPromise + promise.catch(err => totherPromise); + // $ExpectType IPromise> + promise.catch(err => totherHttpPromise); - assertPromiseType(promise.catch((err) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); + // $ExpectType IPromise + promise + .catch(err => tother) + .then( + ambiguous => (isTResult(ambiguous) ? ambiguous.c : ambiguous.f) + ); // promise.finally - assertPromiseType(promise.finally(() => any)); - assertPromiseType(promise.finally(() => tresult)); - assertPromiseType(promise.finally(() => tother)); + // $ExpectType IPromise + promise.finally(() => any); + // $ExpectType IPromise + promise.finally(() => tresult); + // $ExpectType IPromise + promise.finally(() => tother); } function test_angular_forEach() { @@ -1187,6 +1265,24 @@ function NgModelControllerTyping() { }; } +// FormController +angular.module('app').directive('formDebugChecker', () => { + return { + require: '^^form', + link: (scope, el, attrs, ctrl) => { + const form = ctrl as angular.IFormController; + el.on('click', () => { + const report = [] as string[]; + angular.forEach(form.$error, (controls, validationErrorKey) => { + const names = controls.map(control => control.$name); + report.push(`${validationErrorKey}: ${controls.length} control(s) (${names.join(', ')})`); + }); + console.log(`This form has ${report.length} error(s).\n${report.join('\n')}`); + }); + } + }; +}); + let $filter: angular.IFilterService; function testFilter() { diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index efbabaa302..32a5c74b52 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -357,9 +357,9 @@ declare namespace angular { $valid: boolean; $invalid: boolean; $submitted: boolean; - $error: any; - $name: string; - $pending: any; + $error: { [validationErrorKey: string]: Array }; + $name?: string; + $pending?: { [validationErrorKey: string]: Array }; $addControl(control: INgModelController | IFormController): void; $removeControl(control: INgModelController | IFormController): void; $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void; @@ -399,8 +399,8 @@ declare namespace angular { $parsers: IModelParser[]; $formatters: IModelFormatter[]; $viewChangeListeners: IModelViewChangeListener[]; - $error: any; - $name: string; + $error: { [validationErrorKey: string]: boolean }; + $name?: string; $touched: boolean; $untouched: boolean; @@ -408,7 +408,7 @@ declare namespace angular { $validators: IModelValidators; $asyncValidators: IAsyncModelValidators; - $pending: any; + $pending?: { [validationErrorKey: string]: boolean }; $pristine: boolean; $dirty: boolean; $valid: boolean; @@ -1103,28 +1103,43 @@ 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 - * 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. + * 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. + * 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?: null, notifyCallback?: (state: any) => any): IPromise; - then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback?: null, 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; + then( + successCallback?: + | ((value: T) => IPromise | IPromise | TResult1) + | null, + errorCallback?: + | ((reason: any) => IPromise | IPromise | TResult2) + | null, + notifyCallback?: (state: any) => any + ): IPromise; /** * Shorthand for promise.then(null, errorCallback) */ - catch(onRejected: (reason: any) => IPromise|TCatch): IPromise; - catch(onRejected: (reason: any) => IPromise|TCatch2): IPromise; + catch( + onRejected?: + | ((reason: any) => IPromise | IPromise | TResult) + | null + ): IPromise; /** * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. * * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. */ - finally(finallyCallback: () => any): IPromise; + finally(finallyCallback: () => void): IPromise; } interface IDeferred { diff --git a/types/aqb/aqb-tests.ts b/types/aqb/aqb-tests.ts new file mode 100644 index 0000000000..5e186126fe --- /dev/null +++ b/types/aqb/aqb-tests.ts @@ -0,0 +1,151 @@ +import QB = require("aqb"); + +/* + * Most of these tests are taken directly from the examples + * in the aqbjs Github documentation. + * + * https://github.com/arangodb/aqbjs + */ + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#auto-casting-raw-data + */ +const doc = { + aString: "hello", + aDate: new Date(), + aNumber: 23, + anArray: [1, 2, 3, "potato"] +}; + +QB(doc); +QB.for('x').in('1..5').return('x'); +QB.insert(QB(doc)).into('my_collection'); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-types + */ +QB.bool(true); +QB.num("12"); +QB.int("1"); +QB.str(23); +QB.list([ 1 , 2 , 3 , 4 , 5]); +QB.obj({'some.name': 'value'}); +QB.ref("users"); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-expressions + */ +QB.range(1 , 5); +QB.get("property"); +QB.ref("user").get("property"); +QB.expr(QB.for('x').in('1..5').return('x').toAQL()); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-operations + */ +QB.and("a", "b"); +QB.ref("a").and("b"); +QB.or("a" , "b"); +QB.ref("a").or("b"); +QB.add("a" , "b"); +QB.ref("a").add("b"); +QB.plus("a" , "b"); +QB.ref("a").plus("b"); +QB.sub("a" , "b"); +QB.ref("a").sub("b"); +QB.minus("a" , "b"); +QB.ref("a").minus("b"); +QB.mul("a" , "b"); +QB.ref("a").mul("b"); +QB.times("a" , "b"); +QB.ref("a").times("b"); +QB.div("a" , "b"); +QB.ref("a").div("b"); +QB.mod("a", "b"); +QB.ref("a").mod("b"); +QB.eq("a" , "b"); +QB.ref("a").eq("b"); +QB.neq("a", "b"); +QB.ref("a").neq("b"); +QB.gt("a" , "b"); +QB.ref("a").gt("b"); +QB.gte("a" , "b"); +QB.ref("a").gte("b"); +QB.lt("a" , "b"); +QB.ref("a").lt("b"); +QB.lte("a" , "b"); +QB.ref("a").lte("b"); +QB.in("a" , "b"); +QB.ref("a").in("b"); +QB.not("a"); +QB.ref("a").not(); +QB.notIn("a" , "b"); +QB.ref("a").notIn("b"); +QB.neg("a"); +QB.ref("a").neg(); +QB.if("x" , "y" , "z"); +QB.ref("x").then("y").else("z"); +QB.fn('MY::USER::FUNC')(1, 2, 3); +QB.fn('hello')(); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-statements + */ +QB.for('doc').in('my_collection'); +QB.for('doc').in('my_collection').let('foo' , 23); +QB.for('doc').in('my_collection').let('foo' , 23); +// QB.for('doc').in('my_collection').let({a: 1, b: 2, c: 3}); +QB.for('doc').in('my_collection').return('x'); +QB.for('doc').in('my_collection').return({x: 'x'}); +QB.for('doc').in('my_collection').returnDistinct('x'); +QB.for('doc').in('my_collection').filter(QB.eq('a', 'b')); +QB.for('doc').in('my_collection').collectWithCountInto('x'); +QB.for('doc').in('my_collection').collect('x', 'y'); +// QB.for('doc').in('my_collection').collect({x: 'a', y: 'b'}); +QB.for('doc').in('my_collection').collect('x' , 'y').withCountInto('z'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z').keep('a' , 'b'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z' , 'Z'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z').options('opts'); +QB.for('doc').in('my_collection').collect('x' , 'y').options('opts'); +QB.for('doc').in('my_collection').collect('x' , 'y').keep('a' , 'b'); +QB.for('doc').in('my_collection').collect('x' , 'y').sort('x', 'DESC', 'y', 'ASC'); +QB.for('doc').in('my_collection').collect('x' , 'y').limit(20); +QB.for('doc').in('my_collection').collect('x' , 'y').limit(20 , 20); +QB.for('doc').in('my_collection').remove('x'); +QB.for('doc').in('my_collection').remove('x').in('y'); +QB.for('doc').in('my_collection').remove('x').in('y').returnOld('a'); +QB.for('doc').in('my_collection').remove('x').in('y').options('opts'); +QB.upsert('x').insert('y').replace('z').in('c'); +QB.upsert('x').insert('y').replace('z').in('c').options('opts'); +QB.upsert('x').insert('y').update('z').in('c'); +QB.upsert('x').insert('y').update('z').in('c').options('opts'); +QB.insert('x').into('y'); +QB.insert('x').into('y').options('opts'); +QB.insert('x').into('y').returnNew('z'); +QB.update('x').in('y'); +QB.update('x').into('y'); +QB.update('x').with('y').in('z'); +QB.update('x').with('y').into('z'); +QB.update('x').with('y').into('z').options('opts'); +QB.update('x').in('y').options('opts'); +QB.update('x').with('y').into('z').returnNew('v'); +QB.update('x').with('y').into('z').returnOld('v'); +QB.update('x').in('y').options('opts').returnNew('v'); +QB.update('x').in('y').options('opts').returnOld('v'); + +QB.replace('x').in('y'); +QB.replace('x').into('y'); +QB.replace('x').with('y').in('z'); +QB.replace('x').with('y').into('z'); +QB.replace('x').with('y').into('z').options('opts'); +QB.replace('x').in('y').options('opts'); +QB.replace('x').with('y').into('z').returnNew('v'); +QB.replace('x').with('y').into('z').returnOld('v'); +QB.replace('x').in('y').options('opts').returnNew('v'); +QB.replace('x').in('y').options('opts').returnOld('v'); diff --git a/types/aqb/index.d.ts b/types/aqb/index.d.ts new file mode 100644 index 0000000000..eb529e9c97 --- /dev/null +++ b/types/aqb/index.d.ts @@ -0,0 +1,1105 @@ +// Type definitions for aqbjs 2.1 +// Project: https://github.com/arangodb/aqbjs +// Definitions by: Athenkosi Mase +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +interface AqlError extends Error { + new(message: string): Error; + name: string; +} +interface Operation extends Expression { + new(): Expression; +} +interface BinaryOperation extends Operation { + new(operator: string, value1: any, value2: any): Operation; + toAQL(): string; + _operator: string; +} +interface UnaryOperation extends Expression { + new(operator: string, value: any): Expression; + toAQL(): string; + _operator: string; +} +interface SimpleReference extends Expression { + new(value: string): Expression; + toAQL(): string; + re: RegExp; + _value: string; +} +interface RawExpression extends Expression { + new(value: any): Expression; + toAQL(): string; +} +interface BooleanLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: boolean; +} +interface NumberLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + re: RegExp; +} +interface IntegerLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: number; +} +interface StringLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; +} +interface ListLiteral extends Expression { + new(...value: any[]): Expression; + toAQL(): string; +} +interface ObjectLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: object; +} +interface NAryOperation extends Operation { + new(operator: string, values: any[]): Operation; + toAQL(): string; + _operator: string; + _values: Expression[]; +} +interface RangeExpression extends Expression { + new(start: any, end?: any): Expression; + toAQL(): string; + _start: number; + _end: number; + re: RegExp; +} +interface PropertyAccess extends Expression { + new(obj: any, keys: any[]): Expression; + toAQL(): string; + _obj: Expression; + _keys: Expression[]; +} +interface TernaryOperation extends Operation { + new(operator1: string, operator2: string, value1: Expression, value2: any, value3: any): Operation; + toAQL(): string; + _operator1: string; + _operator2: string; +} +interface NullLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; +} +interface Keyword extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: string; + re: RegExp; +} +interface Identifier extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: string; +} +interface FunctionCall extends Expression { + new(functionName: string, ...args: any[]): Expression; + toAQL(): string; + _re: RegExp; + _functionName: string; + _args: any[]; +} +interface ForExpression extends PartialStatement { + new(prev: PartialStatement, varname: any, expr: any): PartialStatement; + toAQL(): string; + _varname: Identifier; +} +interface FilterExpression extends PartialStatement { + new(prev: PartialStatement, expr: any): PartialStatement; + toAQL(): string; +} +interface Definitions { + new(...dfns: any[]): any; + toAQL(): string; + _dfns: any[]; +} +interface LetExpression extends PartialStatement { + new(prev: PartialStatement, ...dfns: any[]): PartialStatement; + toAQL(): string; + _prev: PartialStatement; + _dfns: Definitions; +} +interface CollectExpression extends PartialStatement { + new(prev: PartialStatement, dfns: any[], varname: any, intoExpr: any, keepNames: any[], options: any): PartialStatement; + toAQL(): string; + into(...newVarname: any[]): CollectExpression; + keep(...x: any[]): any; + _keep: Identifier[]; + options(newOpts: any): any; + _options: ObjectLiteral; + withCountInto(newVarname: any): CollectWithCountIntoExpression; +} +interface CollectWithCountIntoExpression extends PartialStatement { + new(prev: PartialStatement, dfns: any[], varname: any, options: any): PartialStatement; + toAQL(): string; + options(newOpts: any): any; +} +interface SortExpression extends PartialStatement { + new(prev: PartialStatement, ...args: any[]): PartialStatement; + toAQL(): string; + keywords: string[]; + _args: Keyword[]; +} +interface LimitExpression extends PartialStatement { + new(prev: PartialStatement, offset: any, count?: any): PartialStatement; + toAQL(): string; +} +interface ReturnExpression extends Expression { + new(prev: LetExpression, value: any, distinct: boolean): Expression; + toAQL(): string; + _prev: LetExpression; + _distinct: boolean; +} +interface RemoveExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, collection: any, options: any): PartialStatement; + returnOld(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): RemoveExpression; +} +interface UpsertExpression extends PartialStatement { + new(prev: PartialStatement, upsertExpr: any, insertExpr: any, replace: boolean, updateOrReplaceExpr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + returnOld(x: any): ReturnExpression; + toAQL(): string; + _updateOrReplace: string; + options(newOpts: any): UpsertExpression; +} +interface InsertExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): InsertExpression; +} +interface UpdateExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, withExpr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + returnOld(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): UpdateExpression; +} +interface ReplaceExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, withExpr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + returnOld(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): ReplaceExpression; +} +interface Expression extends PartialStatement { + /** + * Equality + * + * Creates an equality comparison from the given values. + * + * qb.eq(a, b): (a == b) + * OR: + * qbValue.eq(b): (a == b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').eq('y'): (x == y) + * + * + */ + eq(x: any, y?: any): BinaryOperation; + /** + * Inequality + * + * Creates an inequality comparison from the given values. + * + * qb.neq(a, b): (a != b) + * OR: + * qbValue.neq(b): (a != b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').neq('y'): (x != y) + * + */ + neq(x: any, y?: any): BinaryOperation; + /** + * Greater Than + * + * Creates a greater-than comparison from the given values. + * + * qb.gt(a, b): (a > b) + * OR + * qbValue.gt(b): (a > b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').gt('y'): (x > y) + * + * + */ + gt(x: any, y?: any): BinaryOperation; + /** + * Greater Than Or Equal To + * + * Creates a greater-than-or-equal-to comparison from the given values. + * + * qb.gte(a, b): (a >= b) + * OR + * qbValue.gte(b): (a >= b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').gte('y'): (x >= y) + * + * + */ + gte(x: any, y?: any): BinaryOperation; + /** + * Less Than + * + * Creates a less-than comparison from the given values. + * + * qb.lt(a, b): (a < b) + * OR + * qbValue.lt(b): (a < b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').lt('y'): (x < y) + * + */ + lt(x: any, y?: any): BinaryOperation; + /** + * Less Than Or Equal To + * + * Creates a less-than-or-equal-to comparison from the given values. + * + * qb.lte(a, b): (a <= b) + * OR + * qbValue.lte(b): (a <= b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').lte('y'): (x <= y) + * + */ + lte(x: any, y?: any): BinaryOperation; + /** + * Contains + * + * Creates an "in" comparison from the given values. + * + * qb.in(a, b): (a in b) + * OR: + * qbValue.in(b): (a in b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * qb.ref('x').in('y'): (x in y) + */ + in(...x: any[]): BinaryOperation; + /** + * Negation + * + * Creates a negation from the given value. + * + * qb.not(a) => !(a) + * OR: + * qbValue.not() => !(a) + * + * If the value is not already an value, it will be converted automatically. + * + * Examples + * + * qb.not('x') => !(x) + */ + not(x?: any): UnaryOperation; + /** + * Negative Value + * + * Creates a negative value expression from the given value. + * + * qb.neg(a) => -(a) + * OR: + * qbValue.neg() => -(a) + * + * If the value is not already an AQL value, it will be converted automatically. + * + * Examples + * + * qb.neg('x') => -(x) + */ + neg(x?: any): UnaryOperation; + /** + * Negated Contains + * + * Creates a "not in" comparison from the given values. + * + * qb.notIn(a, b): (a not in b) + * OR: + * qbValue.notIn(b): (a not in b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').notIn('y'): (x not in y) + */ + notIn(...x: any[]): BinaryOperation; + /** + * Boolean And + * + * Creates an "and" operation from the given values. + * + * qb.and(a, b) =>(a && b) + * OR: + * aqlValue.and(b) =>(a && b) + * + * If the values are not already AQL values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Examples + * + * qb.ref('x').and('y') =>(x && y) + */ + and(...x: any[]): NAryOperation; + /** + * Boolean Or + * + * Creates an "or" operation from the given values. + * + * qb.or(a, b): (a || b) + * OR: + * Value.or(b): (a || b) + * + * If the values are not already values, they will be converted automatically. + * + * This declare function can take any number of arguments. + */ + or(...x: any[]): NAryOperation; + /** + * Addition + * + * Creates an addition operation from the given values. + * + * qb.add(a, b): (a + b) + * OR: + * Value.add(b): (a + b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Alias: qb.plus(a, b) + * + * Examples + * + * qb.ref('x').plus('y'): (x + y) + */ + add(...x: any[]): NAryOperation; + plus(...x: any[]): NAryOperation; + /** + * Subtraction + * + * Creates a subtraction operation from the given values. + * + * qb.sub(a, b): (a - b) + * OR: + * Value.sub(b): (a - b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Alias: qb.minus(a, b) + * + * Examples + * + * qb.ref('x').minus('y'): (x - y) + */ + sub(...x: any[]): NAryOperation; + minus(...x: any[]): NAryOperation; + /** + * Multiplication + * + * Creates a multiplication operation from the given values. + * + * qb.mul(a, b): (a * b) + * OR: + * Value.mul(b): (a * b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Alias: qb.times(a, b) + * + * Examples + * + * qb.ref('x').times('y'): (x * y) + */ + mul(...x: any[]): NAryOperation; + times(...x: any[]): NAryOperation; + /** + * Division + * + * Creates a division operation from the given values. + * + * qb.div(a, b): (a / b) + * OR: + * Value.div(b): (a / b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Examples + * qb.ref('x').div('y'): (x / y) + */ + div(...x: any[]): NAryOperation; + /** + * Modulus + * + * Creates a modulus operation from the given values. + * + * qb.mod(a, b): (a % b) + * OR: + * Value.mod(b): (a % b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Examples + * qb.ref('x').mod('y'): (x % y) + */ + mod(...x: any[]): NAryOperation; + /** + * Range + * + * Creates a range expression from the given values. + * + * qb.range(value1, value2): value1..value2 + * + * OR: + * + * Value.range(value2): value1..value2 + * + * If the values are not already values, they will be converted automatically. + * Alias: qb.to(value1, value2) + * + * Examples + * + * qb(2).to(5): 2..5 + * + */ + range(...value: number[]): RangeExpression; + /** + * Property Access + * + * Creates a property access expression from the given values. + * + * qb.get(obj, key): obj[key] + * OR: + * Obj.get(key): obj[key] + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * qb.ref('x').get('y'): x[y]` + * + */ + get(value: any): PropertyAccess; + /** + * Ternary(if / else) + * + * Creates a ternary expression from the given values. + * + * qb.if(condition, thenDo, elseDo): (condition ? thenDo: elseDo) + * OR: + * qbValue.then(thenDo).else(elseDo): (condition ? thenDo: elseDo) + * + * If the values are not already values, they will be converted automatically. + * + * Alias: qbValue.then(thenDo).otherwise(elseDo) + * + * Examples + * qb.ref('x').then('y').else('z'): (x ? y: z) + * + */ + then(value: any): ThenRet; +} +interface ThenRet { + else(y: any): TernaryOperation; + else_: TernaryOperation; + otherwise(y: any): TernaryOperation; +} +interface ForRet { + in(expr: any): ForExpression; + in_: ForRet["in"]; +} +/** + * PartialStatement + * + * In addition to the methods documented above, the query builder provides all methods of PartialStatement objects. + * Statement objects have a method toAQL() which returns their representation as a JavaScript string. + * + * Examples + * + * qb.for('doc').in('my_collection').return('doc._key').toAQL() + * // => FOR doc IN my_collection RETURN doc._key + */ +interface PartialStatement { + /** + * FOR expression IN collection + * + * PartialStatement::for(expression).in(collection): PartialStatement + * + * Examples + * + * _.for('doc').in('my_collection'): FOR doc IN my_collection + * + */ + for(varname: any): ForRet; + /** + * FILTER expression + * + * PartialStatement::filter(expression): PartialStatement + * + * Examples + * + * _.filter(qb.eq('a', 'b')): FILTER a == b + * + */ + filter(varname: any): FilterExpression; + /** + * LET varname = expression + * + * PartialStatement::let(varname, expression): PartialStatement + * + * Examples + * + * _.let('foo', 23): LET foo = 23 + * + * LET var1 = expr1, var2 = expr2, …, varn = exprn + * + * PartialStatement::let(definitions): PartialStatement + * + */ + let(varname: {}, expr: any): LetExpression; + /** + * COLLECT + * + * COLLECT WITH COUNT INTO varname + * PartialStatement::collectWithCountInto(varname): CollectExpression + * + * Examples + * + * _.collectWithCountInto('x'): COLLECT WITH COUNT INTO x COLLECT varname = expression + * PartialStatement::collect(varname, expression): CollectExpression + * + * _.collect('x', 'y'): COLLECT x = y COLLECT var1 = expr1, var2 = expr2, …, varn = exprn + * PartialStatement::collect(definitions): CollectExpression + * + * _.collect({x: 'a', y: 'b'}): COLLECT x = a, y = b WITH COUNT INTO varname + * CollectExpression::withCountInto(varname): CollectExpression + * + * _.withCountInto('x'): WITH COUNT INTO x INTO varname + * CollectExpression::into(varname): CollectExpression + * + * _.into('z'): INTO z KEEP ...vars + * CollectExpression::keep(...vars): CollectExpression + * + * _.into('z').keep('a', 'b'): INTO z KEEP a, b INTO varname = expression + * CollectExpression::into(varname, expression): CollectExpression + * + * _.into('x', 'y'): INTO x = y OPTIONS options + * CollectExpression::options(options): CollectExpression + * + * _.options('opts'): OPTIONS opts + * + */ + collect(varname: any, expr: any): CollectExpression; + /** + * COLLECT + * + * COLLECT WITH COUNT INTO varname + * PartialStatement::collectWithCountInto(varname): CollectExpression + * + * Examples + * + * _.collectWithCountInto('x'): COLLECT WITH COUNT INTO x COLLECT varname = expression + * PartialStatement::collect(varname, expression): CollectExpression + * + * _.collect('x', 'y'): COLLECT x = y COLLECT var1 = expr1, var2 = expr2, …, varn = exprn + * PartialStatement::collect(definitions): CollectExpression + * + * _.collect({x: 'a', y: 'b'}): COLLECT x = a, y = b WITH COUNT INTO varname + * CollectExpression::withCountInto(varname): CollectExpression + * + * _.withCountInto('x'): WITH COUNT INTO x INTO varname + * CollectExpression::into(varname): CollectExpression + * + * _.into('z'): INTO z KEEP ...vars + * CollectExpression::keep(...vars): CollectExpression + * + * _.into('z').keep('a', 'b'): INTO z KEEP a, b INTO varname = expression + * CollectExpression::into(varname, expression): CollectExpression + * + * _.into('x', 'y'): INTO x = y OPTIONS options + * CollectExpression::options(options): CollectExpression + * + * _.options('opts'): OPTIONS opts + * + */ + collectWithCountInto(varname: any): CollectWithCountIntoExpression; + /** + * SORT ...args + * + * PartialStatement::sort(...args): PartialStatement + * + * Examples + * + * _.sort('x', 'DESC', 'y', 'ASC'): SORT x DESC, y ASC + * + */ + sort(...args: any[]): SortExpression; + /** + * LIMIT offset, count + * + * PartialStatement::limit([offset,] count): PartialStatement + * + * Examples + * + * _.limit(20): LIMIT 20 + * + * _.limit(20, 20): LIMIT 20, 20 + * + */ + limit(offset: any, count?: any): LimitExpression; + /** + * RETURN expression + * + * PartialStatement::return(expression): ReturnExpression + * + * Examples + * + * _.return('x'): RETURN x + * _.return({x: 'x'}): RETURN {x: x} + * + */ + return(x: any): ReturnExpression; + /** + * RETURN DISTINCT expression + * + * PartialStatement::returnDistinct(expression): ReturnExpression + * + * Examples + * + * _.returnDistinct('x'): RETURN DISTINCT x + * + */ + returnDistinct(x: any): ReturnExpression; + /** + * REMOVE + * + * REMOVE expression IN collection + * PartialStatement::remove(expression).in(collection): RemoveExpression + * + * Alias: remove(expression).into(collection) + * + * Examples + * + * _.remove('x').in('y'): REMOVE x IN y LET varname = OLD RETURN varname + * RemoveExpression::returnOld(varname): ReturnExpression + * + * _.returnOld('z'): LET z = OLD RETURN z OPTIONS options + * RemoveExpression::options(options): RemoveExpression + * + * _.options('opts'): OPTIONS opts + * + */ + remove(expr: any): RemoveRet; + /** + * UPSERT + * + * UPSERT expression1 INSERT expression2 REPLACE expression3 IN collection + * PartialStatement::upsert(expression1).insert(expression2).replace(expression3).in(collection): UpsertExpression + * + * Alias: ….into(collection) + * + * Examples + * + * _.upsert('x').insert('y').replace('z').in('c'): UPSERT x INSERT y REPLACE z IN c + * + * UPSERT expression1 INSERT expression2 UPDATE expression3 IN collection + * PartialStatement::upsert(expression1).insert(expression2).update(expression3).in(collection): UpsertExpression + * + * Alias: ….into(collection) + * + * _.upsert('x').insert('y').update('z').in('c'): UPSERT x INSERT y UPDATE z IN c OPTIONS options + * UpsertExpression::options(options): UpsertExpression + * + * _.options('opts'): OPTIONS opts + * + */ + upsert(expr: any): UpsertRet; + /** + * INSERT + * + * INSERT expression INTO collection + * PartialStatement::insert(expression).into(collection): InsertExpression + * + * Alias: insert(expression).in(collection) + * + * Examples + * + * _.insert('x').into('y'): INSERT x INTO y OPTIONS options + * InsertExpression::options(options): InsertExpression + * + * _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname + * InsertExpression::returnNew(varname): ReturnExpression + * + * _.returnNew('z'): LET z = NEW RETURN z + * + */ + insert(expr: any): InsertRet; + /** + * UPDATE + * + * UPDATE expression IN collection + * PartialStatement::update(expression).in(collection): UpdateExpression + * + * Alias: update(expression).into(collection) + * + * Examples + * + * _.update('x').in('y'): UPDATE x IN y + * + * UPDATE expression1 WITH expression2 IN collection + * PartialStatement::update(expression1).with(expression2).in(collection): UpdateExpression + * + * Alias: update(expression1).with(expression2).into(collection) + * + * _.update('x').with('y').in('z'): UPDATE x WITH y IN z OPTIONS options + * UpdateExpression::options(options): UpdateExpression + * + * _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname + * UpdateExpression::returnNew(varname): ReturnExpression + * + * _.returnNew('z'): LET z = NEW RETURN z LET varname = OLD RETURN varname + * UpdateExpression::returnOld(varname): ReturnExpression + * + * _.returnOld('z'): LET z = OLD RETURN z + * + */ + update(expr: any): UpdateRetWithRet; + /** + * REPLACE + * + * REPLACE expression IN collection + * PartialStatement::replace(expression).in(collection): ReplaceExpression + * + * Alias: replace(expression).into(collection) + * + * Examples + * + * _.replace('x').in('y'): REPLACE x IN y REPLACE expression1 WITH expression2 IN collection + * PartialStatement::replace(expression1).with(expression2).in(collection): ReplaceExpression + * + * Alias: replace(expression1).with(expression2).into(collection) + * + * _.replace('x').with('y').in('z'): REPLACE x WITH y IN z OPTIONS options + * ReplaceExpression::options(options): ReplaceExpression + * + * _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname + * ReplaceExpression::returnOld(varname): ReturnExpression + * + * _.returnNew('z'): LET z = NEW RETURN z LET varname = OLD RETURN varname + * ReplaceExpression::returnNew(varname): ReturnExpression + * + * _.returnOld('z'): LET z = OLD RETURN z + * + */ + replace(expr: any): ReplaceRetWithRet; +} +interface RemoveRet { + into(collection: any): RemoveExpression; + in: RemoveRet["into"]; + in_: RemoveRet["into"]; +} +interface UpsertRet { + insert(insertExpr: any): UpsertRetInsertRet; +} +interface UpsertRetInsertRet { + update(updateOrReplaceExpr: any): UpsertRetInsertRetUpdateRet; + replace: UpsertRetInsertRet["update"]; +} +interface UpsertRetInsertRetUpdateRet { + into(inCollection: any): UpsertExpression; + in: UpsertRetInsertRetUpdateRet["into"]; + in_: UpsertRetInsertRetUpdateRet["into"]; +} +interface InsertRet { + into(collection: any): InsertExpression; + in: InsertRet["into"]; + in_: InsertRet["into"]; +} +interface UpdateRetWithRet { + into(collection: any): UpdateExpression; + in: UpdateRetWithRet["into"]; + in_: UpdateRetWithRet["into"]; +} +interface ReplaceRetWithRet { + into(collection: any): ReplaceExpression; + in: ReplaceRetWithRet["into"]; + in_: ReplaceRetWithRet["into"]; +} +interface RemoveRet { + into(collection: any): RemoveExpression; + in: RemoveRet["into"]; + in_: RemoveRet["into"]; +} +interface UpsertRet { + insert(insertExpr: any): UpsertRetInsertRet; +} +interface UpsertRetInsertRet { + update(updateOrReplaceExpr: any): UpsertRetInsertRetUpdateRet; + replace: UpsertRetInsertRet["update"]; +} +interface UpsertRetInsertRetUpdateRet { + into(inCollection: any): UpsertExpression; + in: UpsertRetInsertRetUpdateRet["into"]; + in_: UpsertRetInsertRetUpdateRet["into"]; +} +interface InsertRet { + into(collection: any): InsertExpression; + in: InsertRet["into"]; + in_: InsertRet["into"]; +} +interface UpdateRetWithRet { + into(collection: any): UpdateExpression; + with(collection: any): UpdateRetWithRet; + in: UpdateRetWithRet["into"]; + in_: UpdateRetWithRet["into"]; +} +interface ReplaceRetWithRet { + into(collection: any): ReplaceExpression; + with(collection: any): ReplaceRetWithRet; + in: ReplaceRetWithRet["into"]; + in_: ReplaceRetWithRet["into"]; +} +declare function toArray(self: Expression, ...args: any[]): any[]; +declare function isQuotedString(str: string): boolean; +declare function wrapAQL(expr: Keyword): string; +declare function isValidNumber(number: number): boolean; +declare function castNumber(number: any): NumberLiteral; +declare function castBoolean(bool: any): BooleanLiteral; +declare function castString(str: any): SimpleReference | Identifier | RangeExpression | StringLiteral | Expression | PartialStatement | NullLiteral; +declare function castObject(obj: any): ObjectLiteral | ListLiteral | Identifier; +declare function autoCastToken(token: any): Expression | PartialStatement | NullLiteral; +/** + * AQLfunctions + * + * If raw JavaScript values are passed to statements, they will be wrapped in a matching declare function automatically. + * JavaScript strings wrapped in quotation marks will be wrapped in strings, all other JavaScript strings will be wrapped as simple references(see ref) + * and throw an Error if they are not well-formed. + */ +interface AQLfunctions extends Expression { + /** + * Boolean + * + * Wraps the given value as an Boolean literal. + * + * qb.bool(value) + * + * If the value is truthy, it will be converted to the Boolean true, otherwise it will be converted to the Boolean false. + * If the value is already an Boolean, its own value will be wrapped instead. + * + */ + bool(value: any): BooleanLiteral; + /** + * Number + * + * Wraps the given value as an Number literal. + * + * qb.num(value) + * + * If the value is not a JavaScript Number, it will be converted first. + * If the value does not represent a finite number, an Error will be thrown. + * If the value is already an Number or Integer, its own value will be wrapped instead. + * + */ + num(value: any): NumberLiteral; + /** + * Integer + * + * Wraps the given value as an Integer literal. + * + * qb.int(value) + * + * If the value is not a JavaScript Number, it will be converted first. + * If the value does not represent a finite integer, an Error will be thrown. + * If the value is already an Number or Integer, its own value will be wrapped instead. + * + */ + int(value: any): IntegerLiteral; + /** + * String + * + * Wraps the given value as an String literal. + * + * qb.str(value) + * + * If the value is not a JavaScript String, it will be converted first. + * If the value is a quoted string, it will be treated as a string literal. + * If the value is an object with a toAQL method, the result of calling that method will be wrapped instead. + * + * Examples + * + * 23 => "23" + * + * "some string" => "some string" + * + * '"some string"' => "\"some string\"" + * + */ + str(value: any): StringLiteral; + /** + * List + * + * Wraps the given value as an List(Array) literal. + * + * qb.list(value) + * + * If the value is not a JavaScript Array, an Error will be thrown. + * If the value is already an List, its own value will be wrapped instead. + * Any list elements that are not already values will be converted automatically. + * + */ + list(value: any[]): ListLiteral; + /** + * Object + * + * Wraps the given value as an Object literal. + * + * qb.obj(value) + * + * If the value is not a JavaScript Object, an Error will be thrown. + * If the value is already an Object, its own value will be wrapped instead. + * Any property values that are not already values will be converted automatically. + * Any keys that are quoted strings will be treated as string literals. + * Any keys that start with the character ":" will be treated as dynamic properties and must be well-formed simple references. + * Any other keys that need escaping will be quoted if necessary. + * If you need to pass in raw JavaScript objects that shouldn't be converted according to these rules, you can use the qb declare function directly instead. + * + * Examples + * + * qb.obj({'some.name': 'value'}): {"some.name": value} + * + * qb.obj({hello: world}): {hello: world} + * + * qb.obj({'"hello"': world}): {"hello": world} + * + * qb.obj({':dynamic': 'props'}): {[dynamic]: props} + * + * qb.obj({': invalid': 'key'}): throws an error(invalid is not a well-formed reference) + * + */ + obj(obj: object): ObjectLiteral; + /** + * Simple Reference + * + * Wraps a given value in an Simple Reference. + * + * qb.ref(value) + * + * If the value is not a JavaScript string or not a well-formed simple reference, an Error will be thrown. + * If the value is an ArangoCollection, its name property will be used instead. + * If the value is already an Simple Reference, its value is wrapped instead. + * + * Examples + * + * Valid values: + * + * foo + * + * foo.bar + * + * foo[*].bar + * + * foo.bar.QUX + * + * _foo._bar._qux + * + * foo1.bar2 + * + * `foo`.bar + * + * foo.`bar` + * + * Invalid values: + * + * 1foo + * + * föö + * + * foo bar + * + * foo[bar] + * + */ + ref(value: string): SimpleReference; + expr(value: any): RawExpression; + /** + * Ternary(if / else) + * + * Creates a ternary expression from the given values. + * + * qb.if(condition, thenDo, elseDo): (condition ? thenDo: elseDo) + * OR: + * qbValue.then(thenDo).else(elseDo): (condition ? thenDo: elseDo) + * + * If the values are not already values, they will be converted automatically. + * + * Alias: qbValue.then(thenDo).otherwise(elseDo) + * + * Examples + * qb.ref('x').then('y').else('z'): (x ? y: z) + * + */ + if(cond: any, then: any, otherwise: any): Expression | number; + /** + * declare Function Call + * + * Creates a functon call for the given name and arguments. + * + * qb.fn(name)(...args) + * + * If the values are not already values, they will be converted automatically. + * For built-in AQLfunctions, methods with the relevant declare function name are already provided by the query builder. + * + * Examples + * + * qb.fn('MY::USER::FUNC')(1, 2, 3): MY::USER::FUNC(1, 2, 3) + * + * qb.fn('hello')(): hello() + * + * qb.RANDOM(): RANDOM() + * + * qb.FLOOR(qb.div(5, 2)): FLOOR((5 / 2)) + * + */ + fn(functionName: string): (...arity: any[]) => FunctionCall; +} +type QBfunc = (obj: any) => AQLfunctions; +declare const QB: AQLfunctions & QBfunc; +export = QB; diff --git a/types/aqb/tsconfig.json b/types/aqb/tsconfig.json new file mode 100644 index 0000000000..44cb0d912f --- /dev/null +++ b/types/aqb/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "lib": [ + "es2015" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aqb-tests.ts" + ] +} \ No newline at end of file diff --git a/types/aqb/tslint.json b/types/aqb/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/aqb/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/async-lock/async-lock-tests.ts b/types/async-lock/async-lock-tests.ts index 259749d4f0..c6866d270b 100644 --- a/types/async-lock/async-lock-tests.ts +++ b/types/async-lock/async-lock-tests.ts @@ -10,6 +10,14 @@ lock.acquire("key", (done) => { done(); }).then(() => { /* ... */ }); +lock.acquire("key", () => "stringValue") +// Check returned value's type is inherited properly + .then((str) => str.replace("s", "S")); + +lock.acquire("key", async () => "stringValue") +// Check returned value's type is inherited properly + .then((str) => str.replace("s", "S")); + lock.acquire([ "key1", "key2" ], (done) => { done(); }, (err, ret) => { /* ... */ }); diff --git a/types/async-lock/index.d.ts b/types/async-lock/index.d.ts index 4a19590d73..5527482748 100644 --- a/types/async-lock/index.d.ts +++ b/types/async-lock/index.d.ts @@ -1,11 +1,12 @@ // Type definitions for async-lock // Project: https://github.com/rain1017/async-lock -// Definitions by: Elisée MAURER +// Definitions by: Elisée MAURER , Alejandro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -interface AsyncLockDoneCallback { - (err?: Error, ret?: any): void; +interface AsyncLockDoneCallback { + (err?: Error, ret?: T): void; } interface AsyncLockOptions { @@ -18,8 +19,13 @@ interface AsyncLockOptions { declare class AsyncLock { constructor(options?: AsyncLockOptions); - acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, cb: AsyncLockDoneCallback, opts?: AsyncLockOptions): void; - acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, opts?: AsyncLockOptions): PromiseLike; + acquire(key: string | string[], + fn: (() => T | PromiseLike) | ((done: AsyncLockDoneCallback) => any), + opts?: AsyncLockOptions): PromiseLike; + acquire(key: string | string[], + fn: (done: AsyncLockDoneCallback) => any, + cb: AsyncLockDoneCallback, + opts?: AsyncLockOptions): void; isBusy(): boolean; } diff --git a/types/async-lock/tslint.json b/types/async-lock/tslint.json index a41bf5d19a..35039ba334 100644 --- a/types/async-lock/tslint.json +++ b/types/async-lock/tslint.json @@ -8,13 +8,11 @@ "callable-types": false, "comment-format": false, "dt-header": false, - "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, - "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, diff --git a/types/async-retry/async-retry-tests.ts b/types/async-retry/async-retry-tests.ts new file mode 100644 index 0000000000..29c90b36c8 --- /dev/null +++ b/types/async-retry/async-retry-tests.ts @@ -0,0 +1,20 @@ +import { Options, RetryFunction, retry } from 'async-retry'; + +const o: Options = { + retries: 1, + factor: 2, + minTimeout: 3, + maxTimeout: 4, + randomize: true, + onRetry: (e: Error) => 42 +}; + +retry( + bail => 'hello', + { retries: 3 } +); + +retry( + bail => Promise.resolve(42), + { retries: 3 } +); diff --git a/types/async-retry/index.d.ts b/types/async-retry/index.d.ts new file mode 100644 index 0000000000..38d0d8aeec --- /dev/null +++ b/types/async-retry/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for async-retry 1.1 +// Project: https://github.com/zeit/async-retry#readme +// Definitions by: Albert Wu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function retry(fn: RetryFunction, opts: Options): Promise; + +export interface Options { + retries?: number; + factor?: number; + minTimeout?: number; + maxTimeout?: number; + randomize?: boolean; + onRetry?: (e: Error) => any; +} + +export type RetryFunction = (bail: (e: Error) => A, attempt: number) => A|Promise; diff --git a/types/async-retry/tsconfig.json b/types/async-retry/tsconfig.json new file mode 100644 index 0000000000..8bdf98656d --- /dev/null +++ b/types/async-retry/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "async-retry-tests.ts" + ] +} diff --git a/types/async-retry/tslint.json b/types/async-retry/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/async-retry/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/atom/atom-tests.ts b/types/atom/atom-tests.ts index 5fc92880f4..fbd5f6d0d8 100644 --- a/types/atom/atom-tests.ts +++ b/types/atom/atom-tests.ts @@ -1459,6 +1459,14 @@ function testPackageManager() { bool = atom.packages.isPackageDisabled("Test"); + // Activating and deactivating packages + atom.packages.activatePackage("Test").then((activePack) => { + pack = activePack; + }); + atom.packages.deactivatePackage("Test", true).then(() => { + // package is deactivated + }); + // Accessing active packages packs = atom.packages.getActivePackages(); diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index a261661144..f83f751657 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -4111,6 +4111,9 @@ export interface PackageManager { /** Activate a single package by name or path. */ activatePackage(nameOrPath: string): Promise; + /** Deactivate a single package by name or path. */ + deactivatePackage(nameOrPath: string, suppressSerialization?: boolean): Promise; + /** Triggers the given package activation hook. */ triggerActivationHook(hook: string): void; diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index c2107b11e4..119bbb3c37 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -204,6 +204,19 @@ const selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptionsWithCallbacks); +// test checkbox-field additional sign up field + +const checkboxFieldOptions : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + type: "checkbox", + name: "remember", + placeholder: "Remember Me", + prefill: "false" + }] + }; + + new Auth0Lock(CLIENT_ID, DOMAIN, checkboxFieldOptions); + // test Avatar options const avatarOptions : Auth0LockConstructorOptions = { diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 8ed6b50c87..352d9c71a9 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -2,6 +2,7 @@ // Project: http://auth0.com // Definitions by: Brian Caruso // Dan Caddigan +// Larry Faudree // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -23,16 +24,37 @@ type Auth0LockAdditionalSignUpFieldPrefillCallback = type Auth0LockAdditionalSignUpFieldPrefillFunction = (callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void; -interface Auth0LockAdditionalSignUpField { +interface Auth0LockAdditionalTextSignUpField { + type?: "text"; icon?: string; name: string; options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction; placeholder: string; prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction; - type?: "select" | "text"; validator?: (input: string) => { valid: boolean; hint?: string }; } +interface Auth0LockAdditionalSelectSignUpField { + type?: "select"; + icon?: string; + name: string; + options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction; + placeholder: string; + prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction; + validator?: (input: string) => { valid: boolean; hint?: string }; +} + +interface Auth0LockAdditionalCheckboxSignUpField { + type?: "checkbox"; + icon?: string; + name: string; + placeholder: string; + prefill: "true" | "false"; + validator?: (input: string) => { valid: boolean, hint?: string }; +} + +type Auth0LockAdditionalSignUpField = Auth0LockAdditionalSelectSignUpField |Auth0LockAdditionalTextSignUpField |Auth0LockAdditionalCheckboxSignUpField; + type Auth0LockAvatarUrlCallback = (error: auth0.Auth0Error, url: string) => void; type Auth0LockAvatarDisplayNameCallback = (error: auth0.Auth0Error, displayName: string) => void; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index e9e347cc69..0572c2b0e7 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -131,3 +131,13 @@ const retryableManagementClient = new auth0.ManagementClient({ enabled : true } }); + +management.createPasswordChangeTicket({ + connection_id: 'con_id', + email: 'test@me.co', + new_password: 'password', + result_url: 'https://www.google.com/', + ttl_sec: 86400, +}, (err: Error, data) => { + console.log(data.ticket); +}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 609c1ecf0d..58013848f8 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -488,10 +488,16 @@ export interface UserIdParams { } export interface PasswordChangeTicketParams { - result_url: string; - user_id: string; - email: string; - new_password: string; + result_url?: string; + user_id?: string; + new_password?: string; + connection_id?: string; + email?: string; + ttl_sec?: number; +} + +export interface PasswordChangeTicketResponse { + ticket: string; } export interface EmailVerificationTicketOptions { @@ -711,8 +717,8 @@ export class ManagementClient { sendEmailVerification(data: UserIdParams, cb?: (err: Error, data: any) => void): void; // Tickets - createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise; - createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: any) => void): void; + createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise; + createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: PasswordChangeTicketResponse) => void): void; createEmailVerificationTicket(data: EmailVerificationTicketOptions): Promise; createEmailVerificationTicket(data: EmailVerificationTicketOptions, cb?: (err: Error, data: any) => void): void; diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 06f3fdb40c..6d0d83b210 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1,29 +1,29 @@ -var str: string = "any string"; -var date: Date = new Date(); -var anyObj: any = { abc: 123 }; -var num: number = 5; -var error: Error = new Error(); -var b: boolean = true; -var apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; -var apiGwEvt: AWSLambda.APIGatewayEvent; -var customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; -var clientCtx: AWSLambda.ClientContext; -var clientContextEnv: AWSLambda.ClientContextEnv; -var clientContextClient: AWSLambda.ClientContextClient; -var context: AWSLambda.Context; -var identity: AWSLambda.CognitoIdentity; -var proxyResult: AWSLambda.ProxyResult; -var authResponse: AWSLambda.AuthResponse; -var policyDocument: AWSLambda.PolicyDocument; -var statement: AWSLambda.Statement; -var authResponseContext: AWSLambda.AuthResponseContext; -var snsEvt: AWSLambda.SNSEvent; -var snsEvtRecs: AWSLambda.SNSEventRecord[]; -var snsEvtRec: AWSLambda.SNSEventRecord; -var snsMsg: AWSLambda.SNSMessage; -var snsMsgAttr: AWSLambda.SNSMessageAttribute; -var snsMsgAttrs: AWSLambda.SNSMessageAttributes; -var S3EvtRec: AWSLambda.S3EventRecord = { +let str: string; +let date: Date; +let anyObj: any; +let num: number; +let error: Error; +let b: boolean; +let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; +let apiGwEvt: AWSLambda.APIGatewayEvent; +let customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; +let clientCtx: AWSLambda.ClientContext; +let clientContextEnv: AWSLambda.ClientContextEnv; +let clientContextClient: AWSLambda.ClientContextClient; +let context: AWSLambda.Context; +let identity: AWSLambda.CognitoIdentity; +let proxyResult: AWSLambda.ProxyResult; +let authResponse: AWSLambda.AuthResponse; +let policyDocument: AWSLambda.PolicyDocument; +let statement: AWSLambda.Statement; +let authResponseContext: AWSLambda.AuthResponseContext; +let snsEvt: AWSLambda.SNSEvent; +let snsEvtRecs: AWSLambda.SNSEventRecord[]; +let snsEvtRec: AWSLambda.SNSEventRecord; +let snsMsg: AWSLambda.SNSMessage; +let snsMsgAttr: AWSLambda.SNSMessageAttribute; +let snsMsgAttrs: AWSLambda.SNSMessageAttributes; +const S3EvtRec: AWSLambda.S3EventRecord = { eventVersion: '2.0', eventSource: 'aws:s3', awsRegion: 'us-east-1', @@ -32,7 +32,7 @@ var S3EvtRec: AWSLambda.S3EventRecord = { userIdentity: { principalId: 'AIDAJDPLRKLG7UEXAMPLE' }, - requestParameters:{ + requestParameters: { sourceIPAddress: '127.0.0.1' }, responseElements: { @@ -59,15 +59,15 @@ var S3EvtRec: AWSLambda.S3EventRecord = { } }; -var S3CreateEvent: AWSLambda.S3CreateEvent = { +const S3CreateEvent: AWSLambda.S3CreateEvent = { Records: [S3EvtRec] }; -var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; -var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; -var cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse; -var cloudwatchLogsEvent: AWSLambda.CloudWatchLogsEvent; -var cloudwatchLogsDecodedData: AWSLambda.CloudWatchLogsDecodedData; -var scheduledEvent: AWSLambda.ScheduledEvent; +declare const cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; +declare const cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; +declare const cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse; +declare const cloudwatchLogsEvent: AWSLambda.CloudWatchLogsEvent; +declare const cloudwatchLogsDecodedData: AWSLambda.CloudWatchLogsDecodedData; +declare const scheduledEvent: AWSLambda.ScheduledEvent; /* API Gateway Event request context */ str = apiGwEvtReqCtx.accountId; @@ -113,7 +113,7 @@ str = apiGwEvt.stageVariables["example"]; apiGwEvtReqCtx = apiGwEvt.requestContext; /* DynamoDB Stream Event */ -var dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { +const dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { Records: [ { eventID: '1', @@ -266,13 +266,13 @@ policyDocument = { authResponse = { principalId: str, - policyDocument: policyDocument, + policyDocument, context: authResponseContext }; authResponse = { principalId: str, - policyDocument: policyDocument + policyDocument, }; // CognitoUserPoolEvent @@ -442,67 +442,67 @@ function customAuthorizerCallback(cb: AWSLambda.CustomAuthorizerCallback) { } /* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */ -var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { - "Records": [ +const CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { + Records: [ { - "cf": { - "config": { - "distributionId": "EDFDVBD6EXAMPLE", - "requestId": "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" + cf: { + config: { + distributionId: "EDFDVBD6EXAMPLE", + requestId: "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" }, - "request": { - "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", - "method": "GET", - "uri": "/picture.jpg", - "querystring": "size=large", - "headers": { - "host": [ + request: { + clientIp: "2001:0db8:85a3:0:0:8a2e:0370:7334", + method: "GET", + uri: "/picture.jpg", + querystring: "size=large", + headers: { + host: [ { - "key": "Host", - "value": "d111111abcdef8.cloudfront.net" + key: "Host", + value: "d111111abcdef8.cloudfront.net" } ], "user-agent": [ { - "key": "User-Agent", - "value": "curl/7.51.0" + key: "User-Agent", + value: "curl/7.51.0" } ] }, - "origin": { - "custom": { - "customHeaders": { + origin: { + custom: { + customHeaders: { "my-origin-custom-header": [ { - "key": "My-Origin-Custom-Header", - "value": "Test" + key: "My-Origin-Custom-Header", + value: "Test" } ] }, - "domainName": "example.com", - "keepaliveTimeout": 5, - "path": "/custom_path", - "port": 443, - "protocol": "https", - "readTimeout": 5, - "sslProtocols": [ + domainName: "example.com", + keepaliveTimeout: 5, + path: "/custom_path", + port: 443, + protocol: "https", + readTimeout: 5, + sslProtocols: [ "TLSv1", "TLSv1.1" ] }, - "s3": { - "authMethod": "origin-access-identity", - "customHeaders": { + s3: { + authMethod: "origin-access-identity", + customHeaders: { "my-origin-custom-header": [ { - "key": "My-Origin-Custom-Header", - "value": "Test" + key: "My-Origin-Custom-Header", + value: "Test" } ] }, - "domainName": "my-bucket.s3.amazonaws.com", - "path": "/s3_path", - "region": "us-east-1" + domainName: "my-bucket.s3.amazonaws.com", + path: "/s3_path", + region: "us-east-1" } } } @@ -511,52 +511,52 @@ var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { ] }; -var CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { - "Records": [ +const CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { + Records: [ { - "cf": { - "config": { - "distributionId": "EDFDVBD6EXAMPLE", - "requestId": "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" + cf: { + config: { + distributionId: "EDFDVBD6EXAMPLE", + requestId: "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" }, - "request": { - "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", - "method": "GET", - "uri": "/picture.jpg", - "querystring": "size=large", - "headers": { - "host": [ + request: { + clientIp: "2001:0db8:85a3:0:0:8a2e:0370:7334", + method: "GET", + uri: "/picture.jpg", + querystring: "size=large", + headers: { + host: [ { - "key": "Host", - "value": "d111111abcdef8.cloudfront.net" + key: "Host", + value: "d111111abcdef8.cloudfront.net" } ], "user-agent": [ { - "key": "User-Agent", - "value": "curl/7.18.1" + key: "User-Agent", + value: "curl/7.18.1" } ] } }, - "response": { - "status": "200", - "statusDescription": "OK", - "headers": { - "server": [ + response: { + status: "200", + statusDescription: "OK", + headers: { + server: [ { - "key": "Server", - "value": "MyCustomOrigin" + key: "Server", + value: "MyCustomOrigin" } ], "set-cookie": [ { - "key": "Set-Cookie", - "value": "theme=light" + key: "Set-Cookie", + value: "theme=light" }, { - "key": "Set-Cookie", - "value": "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT" + key: "Set-Cookie", + value: "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT" } ] } diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 1e153228c0..09070fb13c 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -18,10 +18,10 @@ // TypeScript Version: 2.2 // API Gateway "event" request context -interface APIGatewayEventRequestContext { +export interface APIGatewayEventRequestContext { accountId: string; apiId: string; - authorizer?: AuthResponseContext | null | undefined; + authorizer?: AuthResponseContext | null; httpMethod: string; identity: { accessKey: string | null; @@ -36,7 +36,7 @@ interface APIGatewayEventRequestContext { user: string | null; userAgent: string | null; userArn: string | null; - }, + }; stage: string; requestId: string; requestTimeEpoch: number; @@ -45,7 +45,7 @@ interface APIGatewayEventRequestContext { } // API Gateway "event" -interface APIGatewayEvent { +export interface APIGatewayEvent { body: string | null; headers: { [name: string]: string }; httpMethod: string; @@ -59,7 +59,7 @@ interface APIGatewayEvent { } // API Gateway CustomAuthorizer "event" -interface CustomAuthorizerEvent { +export interface CustomAuthorizerEvent { type: string; methodArn: string; authorizationToken?: string; @@ -71,22 +71,22 @@ interface CustomAuthorizerEvent { // Context // http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_AttributeValue.html -interface AttributeValue { +export interface AttributeValue { B?: string; - BS?: Array; + BS?: string[]; BOOL?: boolean; - L?: Array; + L?: AttributeValue[]; M?: { [id: string]: AttributeValue }; N?: string; - NS?: Array; + NS?: string[]; NULL?: boolean; S?: string; - SS?: Array; + SS?: string[]; } // Context // http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_StreamRecord.html -interface StreamRecord { +export interface StreamRecord { ApproximateCreationTime?: number; Keys?: { [key: string]: AttributeValue }; NewImage?: { [key: string]: AttributeValue }; @@ -98,7 +98,7 @@ interface StreamRecord { // Context // http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html -interface DynamoDBRecord { +export interface DynamoDBRecord { awsRegion?: string; dynamodb?: StreamRecord; eventID?: string; @@ -112,21 +112,21 @@ interface DynamoDBRecord { // AWS Lambda Stream event // Context // http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update -interface DynamoDBStreamEvent { - Records: Array; +export interface DynamoDBStreamEvent { + Records: DynamoDBRecord[]; } // SNS "event" -interface SNSMessageAttribute { +export interface SNSMessageAttribute { Type: string; Value: string; } -interface SNSMessageAttributes { +export interface SNSMessageAttributes { [name: string]: SNSMessageAttribute; } -interface SNSMessage { +export interface SNSMessage { SignatureVersion: string; Timestamp: string; Signature: string; @@ -140,37 +140,37 @@ interface SNSMessage { Subject: string; } -interface SNSEventRecord { +export interface SNSEventRecord { EventVersion: string; EventSubscriptionArn: string; EventSource: string; Sns: SNSMessage; } -interface SNSEvent { - Records: Array; +export interface SNSEvent { + Records: SNSEventRecord[]; } /** * S3Create event * https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html */ -interface S3EventRecord { +export interface S3EventRecord { eventVersion: string; eventSource: string; - awsRegion: string + awsRegion: string; eventTime: string; eventName: string; userIdentity: { principalId: string; - }, + }; requestParameters: { sourceIPAddress: string; - }, + }; responseElements: { 'x-amz-request-id': string; 'x-amz-id-2': string; - }, + }; s3: { s3SchemaVersion: string; configurationId: string; @@ -188,20 +188,41 @@ interface S3EventRecord { versionId: string; sequencer: string; } - } + }; } -interface S3CreateEvent { - Records: Array; +export interface S3CreateEvent { + Records: S3EventRecord[]; } /** * Cognito User Pool event * http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html */ -interface CognitoUserPoolEvent { +export interface CognitoUserPoolEvent { version: number; - triggerSource: "PreSignUp_SignUp" | "PostConfirmation_ConfirmSignUp" | "PreAuthentication_Authentication" | "PostAuthentication_Authentication" | "CustomMessage_SignUp" | "CustomMessage_AdminCreateUser" | "CustomMessage_ResendCode" | "CustomMessage_ForgotPassword" | "CustomMessage_UpdateUserAttribute" | "CustomMessage_VerifyUserAttribute" | "CustomMessage_Authentication" | "DefineAuthChallenge_Authentication" | "CreateAuthChallenge_Authentication" | "VerifyAuthChallengeResponse_Authentication" | "PreSignUp_AdminCreateUser" | "PostConfirmation_ConfirmForgotPassword" | "TokenGeneration_HostedAuth" | "TokenGeneration_Authentication" | "TokenGeneration_NewPasswordChallenge" | "TokenGeneration_AuthenticateDevice" | "TokenGeneration_RefreshTokens"; + triggerSource: + | "PreSignUp_SignUp" + | "PostConfirmation_ConfirmSignUp" + | "PreAuthentication_Authentication" + | "PostAuthentication_Authentication" + | "CustomMessage_SignUp" + | "CustomMessage_AdminCreateUser" + | "CustomMessage_ResendCode" + | "CustomMessage_ForgotPassword" + | "CustomMessage_UpdateUserAttribute" + | "CustomMessage_VerifyUserAttribute" + | "CustomMessage_Authentication" + | "DefineAuthChallenge_Authentication" + | "CreateAuthChallenge_Authentication" + | "VerifyAuthChallengeResponse_Authentication" + | "PreSignUp_AdminCreateUser" + | "PostConfirmation_ConfirmForgotPassword" + | "TokenGeneration_HostedAuth" + | "TokenGeneration_Authentication" + | "TokenGeneration_NewPasswordChallenge" + | "TokenGeneration_AuthenticateDevice" + | "TokenGeneration_RefreshTokens"; region: string; userPoolId: string; userName?: string; @@ -215,11 +236,11 @@ interface CognitoUserPoolEvent { codeParameter?: string; usernameParameter?: string; newDeviceUsed?: boolean; - session?: { + session?: Array<{ challengeName: "CUSTOM_CHALLENGE" | "PASSWORD_VERIFIER" | "SMS_MFA" | "DEVICE_SRP_AUTH" | "DEVICE_PASSWORD_VERIFIER" | "ADMIN_NO_SRP_AUTH"; challengeResult: boolean; challengeMetaData?: string; - }[]; + }>; challengeName?: string; privateChallengeParameters?: {[key: string]: string}; challengeAnswer?: {[key: string]: string}; @@ -243,7 +264,7 @@ interface CognitoUserPoolEvent { * CloudFormation Custom Resource event and response * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref.html */ -type CloudFormationCustomResourceEventCommon = { +export interface CloudFormationCustomResourceEventCommon { ServiceToken: string; ResponseURL: string; StackId: string; @@ -253,14 +274,14 @@ type CloudFormationCustomResourceEventCommon = { ResourceProperties: { ServiceToken: string; [Key: string]: any; - } + }; } -type CloudFormationCustomResourceCreateEvent = CloudFormationCustomResourceEventCommon & { +export interface CloudFormationCustomResourceCreateEvent extends CloudFormationCustomResourceEventCommon { RequestType: "Create"; } -type CloudFormationCustomResourceUpdateEvent = CloudFormationCustomResourceEventCommon & { +export interface CloudFormationCustomResourceUpdateEvent extends CloudFormationCustomResourceEventCommon { RequestType: "Update"; PhysicalResourceId: string; OldResourceProperties: { @@ -268,29 +289,29 @@ type CloudFormationCustomResourceUpdateEvent = CloudFormationCustomResourceEvent }; } -type CloudFormationCustomResourceDeleteEvent = CloudFormationCustomResourceEventCommon & { +export interface CloudFormationCustomResourceDeleteEvent extends CloudFormationCustomResourceEventCommon { RequestType: "Delete"; PhysicalResourceId: string; } export type CloudFormationCustomResourceEvent = CloudFormationCustomResourceCreateEvent | CloudFormationCustomResourceUpdateEvent | CloudFormationCustomResourceDeleteEvent; -type CloudFormationCustomResourceResponseCommon = { +export interface CloudFormationCustomResourceResponseCommon { PhysicalResourceId: string; StackId: string; RequestId: string; LogicalResourceId: string; Data?: { [Key: string]: any; - } + }; } -type CloudFormationCustomResourceSuccessResponse = CloudFormationCustomResourceResponseCommon & { +export interface CloudFormationCustomResourceSuccessResponse extends CloudFormationCustomResourceResponseCommon { Status: "SUCCESS"; Reason?: string; } -type CloudFormationCustomResourceFailedResponse = CloudFormationCustomResourceResponseCommon & { +export interface CloudFormationCustomResourceFailedResponse extends CloudFormationCustomResourceResponseCommon { Status: "FAILED"; Reason: string; } @@ -300,7 +321,7 @@ export type CloudFormationCustomResourceResponse = CloudFormationCustomResourceS /** * See https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-scheduled-event */ -interface ScheduledEvent { +export interface ScheduledEvent { account: string; region: string; detail: any; @@ -308,21 +329,21 @@ interface ScheduledEvent { source: string; time: string; id: string; - resources: string[] + resources: string[]; } /** * See http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-cloudwatch-logs */ -interface CloudWatchLogsEvent { +export interface CloudWatchLogsEvent { awslogs: CloudWatchLogsEventData; } -interface CloudWatchLogsEventData { +export interface CloudWatchLogsEventData { data: string; } -interface CloudWatchLogsDecodedData { +export interface CloudWatchLogsDecodedData { owner: string; logGroup: string; logStream: string; @@ -334,17 +355,15 @@ interface CloudWatchLogsDecodedData { /** * See http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html#LambdaFunctionExample */ -interface CloudWatchLogsLogEvent { +export interface CloudWatchLogsLogEvent { id: string; timestamp: number; message: string; } - - // Context // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html -interface Context { +export interface Context { // Properties callbackWaitsForEmptyEventLoop: boolean; functionName: string; @@ -363,25 +382,23 @@ interface Context { // Functions for compatibility with earlier Node.js Runtime v0.10.42 // For more details see http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-using-old-runtime.html#nodejs-prog-model-oldruntime-context-methods done(error?: Error, result?: any): void; - fail(error: Error): void; - fail(message: string): void; - succeed(message: string): void; - succeed(object: any): void; + fail(error: Error | string): void; + succeed(messageOrObject: any): void; succeed(message: string, object: any): void; } -interface CognitoIdentity { +export interface CognitoIdentity { cognitoIdentityId: string; cognitoIdentityPoolId: string; } -interface ClientContext { +export interface ClientContext { client: ClientContextClient; Custom?: any; env: ClientContextEnv; } -interface ClientContextClient { +export interface ClientContextClient { installationId: string; appTitle: string; appVersionName: string; @@ -389,7 +406,7 @@ interface ClientContextClient { appPackageName: string; } -interface ClientContextEnv { +export interface ClientContextEnv { platformVersion: string; platform: string; make: string; @@ -397,11 +414,11 @@ interface ClientContextEnv { locale: string; } -interface ProxyResult { +export interface ProxyResult { statusCode: number; headers?: { [header: string]: boolean | number | string; - }, + }; body: string; isBase64Encoded?: boolean; } @@ -410,7 +427,7 @@ interface ProxyResult { * API Gateway CustomAuthorizer AuthResponse. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface AuthResponse { +export interface AuthResponse { principalId: string; policyDocument: PolicyDocument; context?: AuthResponseContext; @@ -420,7 +437,7 @@ interface AuthResponse { * API Gateway CustomAuthorizer AuthResponse.PolicyDocument. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface PolicyDocument { +export interface PolicyDocument { Version: string; Statement: [Statement]; } @@ -429,7 +446,7 @@ interface PolicyDocument { * API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface Statement { +export interface Statement { Action: string | string[]; Effect: string; Resource: string | string[]; @@ -439,58 +456,58 @@ interface Statement { * API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface AuthResponseContext { - [name: string]: string | number | boolean; +export interface AuthResponseContext { + [name: string]: any; } /** * CloudFront events * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */ -type CloudFrontHeaders = { - [name: string]: { - key: string; - value: string; - }[] -}; +export interface CloudFrontHeaders { + [name: string]: Array<{ + key: string; + value: string; + }>; +} -type CloudFrontResponse = { +export interface CloudFrontResponse { status: string; statusDescription: string; headers: CloudFrontHeaders; -}; +} -type CloudFrontRequest = { +export interface CloudFrontRequest { clientIp: string; method: string; uri: string; querystring: string; headers: CloudFrontHeaders; -}; +} -type CloudFrontEvent = { +export interface CloudFrontEvent { config: { distributionId: string; requestId: string; - } + }; } -export type CloudFrontResponseEvent = { - Records: { +export interface CloudFrontResponseEvent { + Records: Array<{ cf: CloudFrontEvent & { request: CloudFrontRequest; response: CloudFrontResponse; } - }[] -}; + }>; +} -export type CloudFrontRequestEvent = { - Records: { +export interface CloudFrontRequestEvent { + Records: Array<{ cf: CloudFrontEvent & { request: CloudFrontRequest; } - }[] -}; + }>; +} /** * AWS Lambda handler function. diff --git a/types/aws-lambda/tslint.json b/types/aws-lambda/tslint.json index a41bf5d19a..bafaae7817 100644 --- a/types/aws-lambda/tslint.json +++ b/types/aws-lambda/tslint.json @@ -1,79 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + // TODO + "dt-header": false } } diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index 9098648240..eff4b72d24 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -516,7 +516,7 @@ export namespace Widgets { * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when * pressing F12. It will display all log and debug messages. */ - debug?(...msg: string[]): void; + debug?: boolean; /** * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful @@ -963,7 +963,7 @@ export namespace Widgets { /** * Spawn a process in the foreground, return to blessed app after exit. */ - spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + spawn(file: string, args?: string[], options?: NodeChildProcessExecOptions): child_process.ChildProcess; /** * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index b28f821e12..8ad57050f6 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -47,7 +47,7 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { /** * Promises/A+ `.then()`. Returns a new promise chained from this promise. * - * The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + * The new promise will be rejected or resolved depending on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. */ // Based on PromiseLike.then, but returns a Bluebird instance. then(onFulfill?: (value: R) => U | PromiseLike, onReject?: (error: any) => U | PromiseLike): Bluebird; // For simpler signature help. @@ -192,34 +192,34 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { */ tapCatch(onReject: (error?: any) => U | PromiseLike): Bluebird; - tapCatch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | object, - filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | object, + tapCatch( + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, + filter4: CatchFilter, + filter5: CatchFilter, onReject: (error: E1 | E2 | E3 | E4 | E5) => U | PromiseLike, ): Bluebird; - tapCatch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | object, + tapCatch( + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, + filter4: CatchFilter, onReject: (error: E1 | E2 | E3 | E4) => U | PromiseLike, ): Bluebird; - tapCatch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | object, + tapCatch( + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, onReject: (error: E1 | E2 | E3) => U | PromiseLike, ): Bluebird; - tapCatch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | object, + tapCatch( + filter1: CatchFilter, + filter2: CatchFilter, onReject: (error: E1 | E2) => U | PromiseLike, ): Bluebird; - tapCatch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | object, + tapCatch( + filter1: CatchFilter, onReject: (error: E1) => U | PromiseLike, ): Bluebird; @@ -364,34 +364,35 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { */ catchReturn(value: U): Bluebird; + // No need to be specific about Error types in these overrides, since there's no handler function catchReturn( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter4: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter5: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, + filter4: CatchFilter, + filter5: CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter4: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, + filter4: CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, value: U, ): Bluebird; @@ -407,34 +408,35 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { */ catchThrow(reason: Error): Bluebird; + // No need to be specific about Error types in these overrides, since there's no handler function catchThrow( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter4: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter5: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, + filter4: CatchFilter, + filter5: CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter4: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, + filter4: CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter3: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, + filter3: CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, - filter2: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, + filter2: CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: (new (...args: any[]) => Error) | ((error: any) => boolean) | object, + filter1: CatchFilter, reason: Error, ): Bluebird; @@ -761,7 +763,7 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static race(values: PromiseLike | R>> | Iterable | R>): Bluebird; /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). + * Initiate a competitive race between multiple promises or values (values will become immediately fulfilled promises). * When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. * * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. @@ -835,7 +837,7 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { * * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. + * *The original array is not modified. If no `initialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. * If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* */ static reduce( @@ -1053,7 +1055,7 @@ declare namespace Bluebird { * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. * The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. * - * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. + * If the the callback is called with multiple success values, the resolver fulfills its promise with an array of the values. */ // TODO specify resolver callback callback(err: any, value: R, ...values: R[]): void; diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 28070ad44f..6cc4f5ed1d 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -228,11 +228,11 @@ declare namespace Bull { } interface JobCounts { - wait: number; active: number; completed: number; failed: number; delayed: number; + waiting: number; } interface JobInformation { @@ -384,21 +384,27 @@ declare namespace Bull { /** * Returns a promise that resolves when the queue is paused. - * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. - * A paused queue will not process new jobs until resumed, - * but current jobs being processed will continue until they are finalized. + * + * A paused queue will not process new jobs until resumed, but current jobs being processed will continue until + * they are finalized. The pause can be either global or local. If global, all workers in all queue instances + * for a given queue will be paused. If local, just this worker will stop processing new jobs after the current + * lock expires. This can be useful to stop a worker from taking new jobs prior to shutting down. * * Pausing a queue that is already paused does nothing. */ - pause(): Promise; + pause(isLocal?: boolean): Promise; /** * Returns a promise that resolves when the queue is resumed after being paused. - * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. + * + * The resume can be either local or global. If global, all workers in all queue instances for a given queue + * will be resumed. If local, only this worker will be resumed. Note that resuming a queue globally will not + * resume workers that have been paused locally; for those, resume(true) must be called directly on their + * instances. * * Resuming a queue that is not paused does nothing. */ - resume(): Promise; + resume(isLocal?: boolean): Promise; /** * Returns a promise that returns the number of jobs in the queue, waiting or paused. @@ -445,6 +451,11 @@ declare namespace Bull { */ getFailed(start?: number, end?: number): Promise; + /** + * Returns a promise that will return an array with the waiting jobs between start and end. + */ + getWaiting(start?: number, end?: number): Promise; + /** * Returns JobInformation of repeatable jobs (ordered descending). Provide a start and/or an end * index to limit the number of results. Start defaults to 0, end to -1 and asc to false. diff --git a/types/c3/c3-tests.ts b/types/c3/c3-tests.ts index 3675c6cadf..7ac2f0ccd8 100644 --- a/types/c3/c3-tests.ts +++ b/types/c3/c3-tests.ts @@ -152,7 +152,8 @@ function axis_examples() { fit: true, values: [1, 2, 4, 8, 16, 32], rotate: 60, - outer: false + outer: false, + width: 100 }, max: 100, min: -100, @@ -940,6 +941,26 @@ function axes_x_tick_fit() { }); } +function axes_x_tick_width() { + const chart = c3.generate({ + data: { + x: "x", + columns: [ + ["x", "2013-10-31", "2013-12-31", "2014-01-31", "2014-02-28"], + ["sample", 30, 100, 400, 150], + ] + }, + axis: { + x: { + type: "bar", + tick: { + width: 100 + } + } + } + }); +} + function axes_x_localtime() { const chart = c3.generate({ data: { @@ -1861,6 +1882,23 @@ function tooltip_order() { }); } +function tooltip_order_function() { + const chart = c3.generate({ + data: { + columns: [ + ["data1", 30, 200, 100, 400, 150, 250], + ["data2", 50, 20, 10, 40, 15, 25] + ] + }, + tooltip: { + order: (data1, data2) => { + return data1.id - data2.id; + // return data2.id - data2.id in case we want desc order + } + } + }); +} + //////////////////////// // Chart options Tests //////////////////////// diff --git a/types/c3/index.d.ts b/types/c3/index.d.ts index 1b0adce9a1..d68027f7d5 100644 --- a/types/c3/index.d.ts +++ b/types/c3/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Marc Climent // Gerin Jacob // Bernd Hacker +// Dzmitry Shyndzin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -585,6 +586,10 @@ export interface XTickConfiguration { * Show x axis outer tick. */ outer?: boolean; + /** + * Set width of x axis tick. + */ + width?: number; multiline?: boolean; // Undocumented } @@ -739,8 +744,9 @@ export interface TooltipOptions { contents?(data: any, defaultTitleFormat: string, defaultValueFormat: string, color: any): string; /** * Set tooltip values order + * Available Values: desc, asc, any[], function (data1, data2) { ... }, null */ - order?: string | any[] | ((data: Data) => boolean); + order?: string | any[] | ((data1: any, data2: any) => number) | null; } export interface SubchartOptions { diff --git a/types/chai-string/chai-string-tests.ts b/types/chai-string/chai-string-tests.ts index 615a6c1f95..dc798c102a 100644 --- a/types/chai-string/chai-string-tests.ts +++ b/types/chai-string/chai-string-tests.ts @@ -51,6 +51,90 @@ describe('chai-string', function() { }); + + describe('#containIgnoreSpaces', function () { + + it('should return true', function () { + var str1 = '1234abcdef56', + str2 = '1234a\nb\tc\r d ef56'; + str1.should.containIgnoreSpaces(str2); + }); + + it('should return true (2)', function () { + var str1 = 'abcdef', + str2 = 'a\nb\tc\r d ef'; + str1.should.containIgnoreSpaces(str2); + }); + + it('should return false', function () { + var str1 = 'abdef', + str2 = 'a\nb\tc\r d ef'; + str1.should.not.containIgnoreSpaces(str2); + }); + }); + + describe('#containIgnoreCase', function () { + + it('should return true', function () { + var str1 = 'abcdef', + str2 = 'cDe'; + str1.should.containIgnoreCase(str2); + }); + + it('should return true (2)', function () { + 'abcdef'.should.containIgnoreCase('cDe'); + }); + + it('should return true (3)', function () { + var str1 = 'abcdef', + str2 = 'AbCdeF'; + str1.should.containIgnoreCase(str2); + }); + + it('should return false', function () { + var str1 = 'abcdef', + str2 = 'efg'; + str1.should.not.containIgnoreCase(str2); + }); + + it('should return false (3)', function () { + var str1 = 'abcdef', + str2 = 'zabcd'; + str1.should.not.containIgnoreCase(str2); + }); + }); + + describe('#indexOf', function () { + + it('should return true', function () { + var str = 'abcabd', + substr = 'ab', + index = 0; + str.indexOf(substr, index).should.be.true; + }); + + it('should return true (2)', function () { + var str = 'abcabd', + substr = 'ca', + index = 2; + str.indexOf(substr, index).should.be.true; + }); + + it('should return true (3)', function () { + var str = 'ababab', + substr = 'ba', + index = 1; + str.indexOf(substr, index).should.be.true; + }); + + it('should return false', function () { + var str = 'abcaab', + substr = 'da', + index = 1; + str.indexOf(substr, index).should.be.false; + }); + }); + describe('tdd alias', function() { let str: string; let str2: string; @@ -92,6 +176,14 @@ describe('chai-string', function() { assert.notEqualIgnoreSpaces(str, str2 + 'g'); }); + it('.containIgnoreSpaces', function () { + assert.containIgnoreSpaces(str, str2); + }); + + it('.notContainIgnoreSpaces', function () { + assert.notContainIgnoreSpaces(str, str2 + 'g'); + }); + it('.singleLine', function() { assert.singleLine(str); }); @@ -125,5 +217,13 @@ describe('chai-string', function() { assert.entriesCount('', 'ab', 0); }); + it('.indexOf', function () { + assert.indexOf('abcabd', 'ab', 0); + assert.indexOf('abcabd', 'ca', 2); + assert.indexOf('ababab', 'ba', 1); + assert.indexOf('ababab', 'ba', 1); + 'ababab'.indexOf('ba', 1).should.be.true; + }); + }); }); diff --git a/types/chai-string/index.d.ts b/types/chai-string/index.d.ts index fad380cf07..bc990104be 100644 --- a/types/chai-string/index.d.ts +++ b/types/chai-string/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chai-string 1.1.4 +// Type definitions for chai-string 1.4.0 // Project: https://github.com/onechiporenko/chai-string // Definitions by: Nick Malaguti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,10 +14,13 @@ declare global { endWith(expected: string, message?: string): Assertion; equalIgnoreCase(expected: string, message?: string): Assertion; equalIgnoreSpaces(expected: string, message?: string): Assertion; + containIgnoreCase(expected: string, msg?: string): Assertion; + containIgnoreSpaces(expected: string, msg?: string): Assertion; singleLine(message?: string): Assertion; reverseOf(message?: string): Assertion; palindrome(message?: string): Assertion; entriesCount(substr: string, expected: number, message?: string): Assertion; + indexOf(str: string, substr: string, index: number, msg?: string): Assertion; } interface Assert { @@ -29,6 +32,10 @@ declare global { notEqualIgnoreCase(val: string, exp: string, msg?: string): void; equalIgnoreSpaces(val: string, exp: string, msg?: string): void; notEqualIgnoreSpaces(val: string, exp: string, msg?: string): void; + containIgnoreCase(val: string, exp: string, msg?: string): void; + notContainIgnoreCase(val: string, exp: string, msg?: string): void; + containIgnoreSpaces(val: string, exp: string, msg?: string): void; + notContainIgnoreSpaces(val: string, exp: string, msg?: string): void; singleLine(val: string, msg?: string): void; notSingleLine(val: string, msg?: string): void; reverseOf(val: string, exp: string, msg?: string): void; @@ -36,6 +43,7 @@ declare global { palindrome(val: string, msg?: string): void; notPalindrome(val: string, msg?: string): void; entriesCount(str: string, substr: string, count: number, msg?: string): void; + indexOf(str: string, substr: string, index: number, msg?: string): void; } } } diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index d1e86fd317..8d2190478f 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -45,7 +45,14 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), { } }] }, - plugins: { arbitraryPlugin: {option: "value"} } + plugins: { arbitraryPlugin: {option: "value"} }, + legend: { + display: true, + labels: { + usePointStyle: true, + padding: 40 + } + }, } }); chart.update(); diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 2c28be539d..db20617c2d 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -8,6 +8,7 @@ // Joseph Page // Dan Manastireanu // Guillaume Rodriguez +// Sergey Rubanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -119,6 +120,7 @@ declare namespace Chart { lineJoin?: string; lineWidth?: number; strokeStyle?: string; + pointStyle?: PointStyle; } interface ChartTooltipItem { @@ -231,6 +233,8 @@ declare namespace Chart { fontFamily?: string; padding?: number; generateLabels?(chart: any): any; + filter?(item: ChartLegendItem, data: ChartData): any; + usePointStyle?: boolean; } interface ChartTooltipOptions { diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 3d85d3be14..cd12179213 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -6050,6 +6050,12 @@ declare namespace chrome.tabs { * @since Chrome 39. */ matchAboutBlank?: boolean; + /** + * Optional. The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to "author". + * One of: "author", or "user" + * @since Chrome 66. + */ + cssOrigin?: string; } export interface CreateProperties { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 20882269fd..cf7cd0cc27 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -24,6 +24,8 @@ declare namespace CKEDITOR { var DIALOG_RESIZE_HEIGHT: number; var DIALOG_RESIZE_NONE: number; var DIALOG_RESIZE_WIDTH: number; + var DIALOG_STATE_IDLE: number; + var DIALOG_STATE_BUSY: number; var ELEMENT_MODE_APPENDTO: number; var ELEMENT_MODE_INLINE: number; var ELEMENT_MODE_NONE: number; @@ -42,6 +44,10 @@ declare namespace CKEDITOR { var NODE_DOCUMENT_FRAGMENT: number; var NODE_ELEMENT: number; var NODE_TEXT: number; + var POSITION_BEFORE_START: number; + var POSITION_BEFORE_END: number; + var POSITION_AFTER_START: number; + var POSITION_AFTER_END: number; var SELECTION_ELEMENT: number; var SELECTION_NONE: number; var SELECTION_TEXT: number; @@ -49,6 +55,9 @@ declare namespace CKEDITOR { var SHRINK_ELEMENT: number; var SHRINK_TEXT: number; var START: number; + var STYLE_BLOCK: string; + var STYLE_INLINE: string; + var STYLE_OBJECT: string; var TRISTATE_DISABLED: number; var TRISTATE_OFF: number; var TRISTATE_ON: number; @@ -62,7 +71,7 @@ declare namespace CKEDITOR { var currentInstance: editor; var document: dom.document; var env: environmentConfig; - var instances: editor[]; + var instances: { [id: string]: editor | undefined }; var loadFullCoreTimeout: number; var revision: string; var rnd: number; @@ -92,9 +101,19 @@ declare namespace CKEDITOR { function replaceAll(className?: string): void; function replaceAll(assertionFunction: (textarea: HTMLTextAreaElement, config: config) => boolean): void; + type listenerRegistration = { + removeListener: () => void; + } namespace dom { + interface bookmark { + startNode: dom.node | string; + endNode: dom.node | string; + serializable: boolean; + collapsed: boolean; + } + class comment { // Properties @@ -269,16 +288,17 @@ declare namespace CKEDITOR { class elementPath { constructor(startNode: element, root: element); + constructor(startNode: element); block: element; blockLimit: element; root: element; elements: element[]; compare(otherPath: elementPath): boolean; - contains(query: string, excludeRoot: boolean, fromTop: boolean): element; - contains(query: string[], excludeRoot: boolean, fromTop: boolean): element; - contains(query: (element: element) => boolean, excludeRoot: boolean, fromTop: boolean): element; - contains(query: Object, excludeRoot: boolean, fromTop: boolean): element; - contains(query: element, excludeRoot: boolean, fromTop: boolean): element; + contains(query: string, excludeRoot?: boolean, fromTop?: boolean): element; + contains(query: string[], excludeRoot?: boolean, fromTop?: boolean): element; + contains(query: (element: element) => boolean, excludeRoot?: boolean, fromTop?: boolean): element; + contains(query: Object, excludeRoot?: boolean, fromTop?: boolean): element; + contains(query: element, excludeRoot?: boolean, fromTop?: boolean): element; isContextFor(tag: string): boolean; direction(): string; } @@ -300,7 +320,7 @@ declare namespace CKEDITOR { cloneContents(): documentFragment; deleteContents(mergeThen?: boolean): void; extractContents(mergeThen?: boolean): documentFragment; - createBookmark(serializable: boolean): Object; + createBookmark(serializable?: boolean): bookmark; createBookmark2(normalized: boolean): Object; createIterator(): iterator; moveToBookmark(bookmark: Object): void; @@ -322,6 +342,7 @@ declare namespace CKEDITOR { setStartAt(node: node, position: number): void; setEndAt(node: node, position: number): void; fixBlock(isStart: boolean, blockTag: Object): Object; + select(): selection; splitBlock(blockTag: Object): Object; splitElement(toSplit: element): element; removeEmptyBlocksAtEnd(atEnd: boolean): void; @@ -815,7 +836,7 @@ declare namespace CKEDITOR { templates_files?: Object; templates_replaceContent?: boolean; title?: string | boolean; - toolbar?: string | (string | string[])[]; + toolbar?: string | (string | string[] | { name: string, items?: string[], groups?: string[] })[] | null; toolbarCanCollapse?: boolean; toolbarGroupCycling?: boolean; toolbarGroups?: (toolbarGroups | string)[]; @@ -847,14 +868,20 @@ declare namespace CKEDITOR { bottom?: string | HTMLElement; } + module skin { + var icons: { [name: string]: { path: string } }; + function addIcon(name: string, path: string, offset?: number, bgsize?: string): void; + } - interface style { - - } - - - interface editable { + class style { + constructor(something: { element: string, attributes: { [att: string]: string } }); + applyToRange(range: Range, editor: editor): void; + } + interface editable extends dom.element { + hasFocus: boolean; + attachListener(obj: event | editable, eventName: string, listenerFunction: (ei: eventInfo) => void, + scopeobj?: {}, listenerData?: any, priority?: number): listenerRegistration; } @@ -951,11 +978,14 @@ declare namespace CKEDITOR { destroy(widget: CKEDITOR.plugins.widget, offline?: boolean): void; destroyAll(offline?: boolean): void; finalizeCreation(container: any): void; + focused: widget; fire(eventName: string, data: Object, editor: editor): any; // should be boolean | Object getByElement(element: any, checkWrapperOnly: boolean): CKEDITOR.plugins.widget; hasListeners(eventName: string): boolean; - initOn(element: any, widgetDef?: CKEDITOR.plugins.widget.definition, startupData?: Object): CKEDITOR.plugins.widget; - initOnAll(container?: any): CKEDITOR.plugins.widget[]; + initOn(element: dom.element, widgetDef?: CKEDITOR.plugins.widget.definition, startupData?: Object): CKEDITOR.plugins.widget; + initOn(element: dom.element, widgetDef?: string, startupData?: Object): CKEDITOR.plugins.widget; + initOnAll(container?: dom.element): CKEDITOR.plugins.widget[]; + instances: { [id: string]: widget }; on(eventName: string, listenerFunction: Function, scopeObj?: Object, listenerData?: Object, priority?: number): any; once(): void; parseElementClasses(classes: string): any; @@ -1040,12 +1070,13 @@ declare namespace CKEDITOR { requires?: string | string[]; afterInit?(editor: editor): any; beforeInit?(editor: editor): any; - init?(editor: editor): any; + init?(editor: editor): void; onLoad?(): any; icons?: string; } - function add(name: string, definition?: IPluginDefinition): void; + function add(name: string, definition: IPluginDefinition): void; + function add(name: string): void; function addExternal(name: string, path: string, fileName: string): void; function get(name: string): any; function getFilePath(name: string): string; @@ -1058,6 +1089,7 @@ declare namespace CKEDITOR { interface IMenuItemDefinition { label:string, command:string, + icon: string group:string, order:number } @@ -1110,6 +1142,7 @@ declare namespace CKEDITOR { createFakeParserElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void; createRange(): dom.range; destroy(noUpdate?: boolean): void; + editable(): editable | null; editable(elementOrEditable: dom.element): void; editable(elementOrEditable: editable): void; elementPath(startNode?: dom.node): dom.elementPath; @@ -1267,8 +1300,14 @@ declare namespace CKEDITOR { stop(): void; } + module filter { + interface allowedContentRules { + + } + } class filter { + allow(newRules: CKEDITOR.filter.allowedContentRules, featureName?: string, overrideCustom?: boolean): boolean; } @@ -1309,8 +1348,8 @@ declare namespace CKEDITOR { fire(eventName: string, data?: Object, editor?: editor): any; fireOnce(eventName: string, data?: Object, editor?: editor): any; hasListeners(eventName: string): boolean; - on(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): void; - once(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): void; + on(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object | null, listenerData?: Object | null, priority?: number): listenerRegistration; + once(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object | null, listenerData?: Object | null, priority?: number): listenerRegistration; removeAllListeners(): void; removeListener(eventName: string, listenerFunction: (eventInfo: eventInfo) => void): void; static implementOn(targetObject: Object): void; @@ -1768,6 +1807,7 @@ declare namespace CKEDITOR { constructor(value: string); type: number; filter(filter: filter): boolean; + value: string; writeHtml(writer: basicWriter, filter: filter): void; } @@ -1779,6 +1819,7 @@ declare namespace CKEDITOR { children: any[]; type: number; add(node: node): number; + add(node: node, index: number): void; clone(): element; filter(filter: filter): boolean; filterChildren(filter: filter): void; @@ -1803,10 +1844,12 @@ declare namespace CKEDITOR { children: any[]; parent: any; type: number; - fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: string): void; - fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: string): void; - fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: boolean): void; - fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: boolean): void; + static fromHtml(fragmentHtml: string): fragment; + static fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: string): fragment | element; + static fromHtml(fragmentHtml: string, parent: null, fixingBlock?: string): fragment; + static fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: string): fragment | element; + static fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: boolean): fragment | element; + static fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: boolean): fragment | element; add(node: node, index?: number): void; filter(filter: filter): void; filterChildren(filter: filter, filterRoot?: boolean): void; @@ -1847,7 +1890,9 @@ declare namespace CKEDITOR { namespace tools { var callFunction: Function; - function enableHtml5Elements(doc: Object, withAppend? : Boolean) : void; + function enableHtml5Elements(doc: Object, withAppend?: Boolean): void; + function parseCssText(styleText: string, normalize?: Boolean, nativeNormalize?: Boolean): { [key: string]: string } + function writeCssText(style: { [key: string]: string }, sort?: Boolean): string; } diff --git a/types/color/color-tests.ts b/types/color/color-tests.ts index 4e475a0ce0..ac79ea42e9 100644 --- a/types/color/color-tests.ts +++ b/types/color/color-tests.ts @@ -25,8 +25,8 @@ const yellow: number = color.yellow(); const black: number = color.black(); const luminosity: number = color.luminosity(); const contrast: number = color.contrast(colorOther); -const dark: boolean = color.dark(); -const light: boolean = color.light(); +const isDark: boolean = color.isDark(); +const isLight: boolean = color.isLight(); const level: string = color.level(colorOther); const x: number = color.x(); diff --git a/types/color/index.d.ts b/types/color/index.d.ts index 8290b78129..716b8a9dcf 100644 --- a/types/color/index.d.ts +++ b/types/color/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for color 2.0 +// Type definitions for color 3.0 // Project: https://github.com/qix-/color#readme -// Definitions by: Junyoung Clare Jang +// Definitions by: Junyoung Clare Jang , James W. Lane // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -72,8 +72,8 @@ interface Color { luminosity(): number; contrast(color2: Color): number; level(color2: Color): 'AAA' | 'AA' | ''; - dark(): boolean; - light(): boolean; + isDark(): boolean; + isLight(): boolean; negate(): Color; lighten(ratio: number): Color; darken(ratio: number): Color; diff --git a/types/color/v2/color-tests.ts b/types/color/v2/color-tests.ts new file mode 100644 index 0000000000..4e475a0ce0 --- /dev/null +++ b/types/color/v2/color-tests.ts @@ -0,0 +1,65 @@ +import Color = require('color'); + +const color: Color = new Color("white"); +const colorOther: Color = new Color("black"); +const colorRGB: Color = new Color({ r: 0, g: 0, b: 0 }, "rgb"); +const colorInt: Color = new Color(0x000000); +const colorWithoutNew: Color = Color(0x000000); +const colorByStaticMethod: Color = Color.rgb({ r: 0, g: 0, b: 0 }); + +const hex: string = color.hex(); +const percent: string = color.percentString(); +const keyword: string = color.keyword(); +const alpha: number = color.alpha(); +const red: number = color.red(); +const green: number = color.green(); +const blue: number = color.blue(); +const hue: number = color.hue(); +const saturationl: number = color.saturationl(); +const lightness: number = color.lightness(); +const saturationv: number = color.saturationv(); +const value: number = color.value(); +const cyan: number = color.cyan(); +const magenta: number = color.magenta(); +const yellow: number = color.yellow(); +const black: number = color.black(); +const luminosity: number = color.luminosity(); +const contrast: number = color.contrast(colorOther); +const dark: boolean = color.dark(); +const light: boolean = color.light(); +const level: string = color.level(colorOther); + +const x: number = color.x(); +const y: number = color.y(); +const z: number = color.z(); +const l: number = color.l(); +const a: number = color.a(); +const b: number = color.b(); +const rgbNumber: number = color.rgbNumber(); + +const chain: Color = color + .alpha(0) + .red(0) + .green(0) + .blue(0) + .hue(0) + .saturationl(0) + .lightness(0) + .saturationv(0) + .value(0) + .cyan(0) + .magenta(0) + .yellow(0) + .black(0) + .negate() + .lighten(0) + .darken(0) + .saturate(0) + .desaturate(0) + .grayscale() + .whiten(0) + .blacken(0) + .opaquer(0) + .rotate(0) + .mix(colorOther, 0) + .hsl(); diff --git a/types/color/v2/index.d.ts b/types/color/v2/index.d.ts new file mode 100644 index 0000000000..8290b78129 --- /dev/null +++ b/types/color/v2/index.d.ts @@ -0,0 +1,135 @@ +// Type definitions for color 2.0 +// Project: https://github.com/qix-/color#readme +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import convert = require('color-convert'); + +type ColorParam = Color | string | ArrayLike | number | { [key: string]: any }; + +interface Color { + toString(): string; + toJSON(): Color; + string(places?: number): string; + percentString(places?: number): string; + array(): number[]; + object(): { alpha?: number } & { [key: string]: number }; + unitArray(): number[]; + unitObject(): { r: number, g: number, b: number, alpha?: number }; + round(places?: number): Color; + alpha(): number; + alpha(val: number): Color; + red(): number; + red(val: number): Color; + green(): number; + green(val: number): Color; + blue(): number; + blue(val: number): Color; + hue(): number; + hue(val: number): Color; + saturationl(): number; + saturationl(val: number): Color; + lightness(): number; + lightness(val: number): Color; + saturationv(): number; + saturationv(val: number): Color; + value(): number; + value(val: number): Color; + chroma(): number; + chroma(val: number): Color; + gray(): number; + gray(val: number): Color; + white(): number; + white(val: number): Color; + wblack(): number; + wblack(val: number): Color; + cyan(): number; + cyan(val: number): Color; + magenta(): number; + magenta(val: number): Color; + yellow(): number; + yellow(val: number): Color; + black(): number; + black(val: number): Color; + x(): number; + x(val: number): Color; + y(): number; + y(val: number): Color; + z(): number; + z(val: number): Color; + l(): number; + l(val: number): Color; + a(): number; + a(val: number): Color; + b(): number; + b(val: number): Color; + keyword(): string; + keyword(val: string): Color; + hex(): string; + hex(val: string): Color; + rgbNumber(): number; + luminosity(): number; + contrast(color2: Color): number; + level(color2: Color): 'AAA' | 'AA' | ''; + dark(): boolean; + light(): boolean; + negate(): Color; + lighten(ratio: number): Color; + darken(ratio: number): Color; + saturate(ratio: number): Color; + desaturate(ratio: number): Color; + whiten(ratio: number): Color; + blacken(ratio: number): Color; + grayscale(): Color; + fade(ratio: number): Color; + opaquer(ratio: number): Color; + rotate(degrees: number): Color; + mix(mixinColor: Color, weight?: number): Color; + + rgb(...args: number[]): Color; + hsl(...args: number[]): Color; + hsv(...args: number[]): Color; + hwb(...args: number[]): Color; + cmyk(...args: number[]): Color; + xyz(...args: number[]): Color; + lab(...args: number[]): Color; + lch(...args: number[]): Color; + ansi16(...args: number[]): Color; + ansi256(...args: number[]): Color; + hcg(...args: number[]): Color; + apple(...args: number[]): Color; +} + +interface ColorConstructor { + (obj?: ColorParam, model?: keyof (typeof convert)): Color; + new(obj?: ColorParam, model?: keyof (typeof convert)): Color; + rgb(...val: number[]): Color; + rgb(color: ColorParam): Color; + hsl(...val: number[]): Color; + hsl(color: ColorParam): Color; + hsv(...val: number[]): Color; + hsv(color: ColorParam): Color; + hwb(...val: number[]): Color; + hwb(color: ColorParam): Color; + cmyk(...val: number[]): Color; + cmyk(color: ColorParam): Color; + xyz(...val: number[]): Color; + xyz(color: ColorParam): Color; + lab(...val: number[]): Color; + lab(color: ColorParam): Color; + lch(...val: number[]): Color; + lch(color: ColorParam): Color; + ansi16(...val: number[]): Color; + ansi16(color: ColorParam): Color; + ansi256(...val: number[]): Color; + ansi256(color: ColorParam): Color; + hcg(...val: number[]): Color; + hcg(color: ColorParam): Color; + apple(...val: number[]): Color; + apple(color: ColorParam): Color; +} + +declare const Color: ColorConstructor; + +export = Color; diff --git a/types/color/v2/tsconfig.json b/types/color/v2/tsconfig.json new file mode 100644 index 0000000000..8216dc0b05 --- /dev/null +++ b/types/color/v2/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "color": [ + "color/v2" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-tests.ts" + ] +} diff --git a/types/color/v2/tslint.json b/types/color/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/conf/index.d.ts b/types/conf/index.d.ts index 9f88a88355..e58dc3ede7 100644 --- a/types/conf/index.d.ts +++ b/types/conf/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for conf 1.1 +// Type definitions for conf 1.4 // Project: https://github.com/sindresorhus/conf // Definitions by: Sam Verschueren // BendingBender @@ -24,6 +24,7 @@ declare class Conf implements Iterable<[string, T]> { has(key: string): boolean; delete(key: string): void; clear(): void; + onDidChange(key: string, callback: (oldVal: any, newVal: any) => void): void; [Symbol.iterator](): Iterator<[string, T]>; } diff --git a/types/create-react-class/create-react-class-tests.ts b/types/create-react-class/create-react-class-tests.ts index c3f7c620ef..ae62233135 100644 --- a/types/create-react-class/create-react-class-tests.ts +++ b/types/create-react-class/create-react-class-tests.ts @@ -73,6 +73,12 @@ const ClassicComponent: React.ClassicComponentClass = createReactClass = React.createFactory(ClassicComponent); @@ -81,6 +87,7 @@ const classicFactoryElement: React.ClassicElement = // React.createElement const classicElement: React.ClassicElement = React.createElement(ClassicComponent, props); +const classicElementNullProps: React.ClassicElement<{}> = React.createElement(ClassicComponentNoProps, null); // React.cloneElement const clonedClassicElement: React.ClassicElement = diff --git a/types/cropperjs/index.d.ts b/types/cropperjs/index.d.ts index cca1d6a39b..60b508dd8f 100644 --- a/types/cropperjs/index.d.ts +++ b/types/cropperjs/index.d.ts @@ -488,6 +488,21 @@ declare class cropperjs { */ rotateTo(degree: number): void; + /** + * Scale the image. + */ + scale(scaleX: number, scaleY?: number): void; + + /** + * Scale the abscissa of the image. + */ + scaleX(scaleX: number): void; + + /** + * Scale the ordinate of the image. + */ + scaleY(scaleY: number): void; + /** * Clear the crop box. */ diff --git a/types/cross-spawn/cross-spawn-tests.ts b/types/cross-spawn/cross-spawn-tests.ts new file mode 100644 index 0000000000..2f2fe11cd5 --- /dev/null +++ b/types/cross-spawn/cross-spawn-tests.ts @@ -0,0 +1,20 @@ +import * as spawn from 'cross-spawn'; +import * as cp from 'child_process'; + +const p1: cp.ChildProcess = spawn('my-cmd', ['foo', 'bar']); +const pw: cp.ChildProcess = spawn('my-cmd', ['foo', 'bar'], {env: process.env}); + +pw.on('error', (err: Error) => { + console.log(err); +}); + +const r1: Error = spawn.sync('foo').error; +const r2: string[] = spawn.sync('foo').output; +const r3: Buffer = spawn.sync('foo').stdout; +const r4: Buffer = spawn.sync('foo').stderr; +const r5: number = spawn.sync('foo').status; +const r6: string = spawn.sync('foo').signal; +const r7: string = spawn.sync('foo', {encoding: 'utf8'}).stdout; + +spawn.sync('foo', ['bar']); +spawn.sync('foo', ['bar'], {stdio: 'inherit'}); diff --git a/types/cross-spawn/index.d.ts b/types/cross-spawn/index.d.ts new file mode 100644 index 0000000000..8544b37528 --- /dev/null +++ b/types/cross-spawn/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for cross-spawn 6.0 +// Project: https://github.com/moxystudio/node-cross-spawn +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as child_process from 'child_process'; + +declare function spawn(command: string, args?: string[], options?: child_process.SpawnOptions): child_process.ChildProcess; + +declare namespace spawn { + const sync: typeof child_process.spawnSync; +} + +export = spawn; diff --git a/types/cross-spawn/tsconfig.json b/types/cross-spawn/tsconfig.json new file mode 100644 index 0000000000..12426c3479 --- /dev/null +++ b/types/cross-spawn/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cross-spawn-tests.ts" + ] +} diff --git a/types/cross-spawn/tslint.json b/types/cross-spawn/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cross-spawn/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index f2aed9aec4..b7fa675095 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -1,6 +1,12 @@ import * as assert from "power-assert"; +import { setWorldConstructor, defineParameterType, After, AfterAll, Before, BeforeAll, Given, When, Then } from "cucumber"; import cucumber = require("cucumber"); +type Callback = cucumber.CallbackStepDefinition; +type Table = cucumber.TableDefinition; +type HookScenarioResult = cucumber.HookScenarioResult; +const Status = cucumber.Status; + // You can optionally declare your own world properties declare module "cucumber" { interface World { @@ -8,190 +14,166 @@ declare module "cucumber" { } } -function StepSample() { - type Callback = cucumber.CallbackStepDefinition; - type Table = cucumber.TableDefinition; - type HookScenarioResult = cucumber.HookScenarioResult; - const Status = cucumber.Status; - - cucumber.defineSupportCode(({setWorldConstructor, defineParameterType, After, AfterAll, Around, Before, BeforeAll, registerHandler, Given, When, Then}) => { - setWorldConstructor(function({attach, parameters}) { - this.attach = attach; - this.parameters = parameters; - this.visit = (url: string, callback: Callback) => { - callback(null, 'pending'); - }; - }); - - Before((scenarioResult: HookScenarioResult, callback: Callback) => { - console.log(scenarioResult.result.status === Status.FAILED); - callback(); - }); - - Before({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { - console.log(scenarioResult.result.status === Status.FAILED); - callback(); - }); - - Before('@tag', (scenarioResult: HookScenarioResult, callback: Callback) => { - console.log(scenarioResult.result.status === Status.FAILED); - callback(); - }); - - BeforeAll((callback: Callback) => { - console.log("Before all"); - callback(); - }); - - BeforeAll({ timeout: 1000 }, (callback: Callback) => { - console.log("Before all"); - callback(); - }); - - BeforeAll('@tag', (callback: Callback) => { - console.log("Before all"); - callback(); - }); - - Around((scenarioResult: HookScenarioResult, runScenario: (error: string | null, callback?: () => void) => void) => { - if (scenarioResult.result.status === Status.FAILED) { - runScenario(null, () => { - console.log('finish tasks'); - }); - } - }); - - After((scenarioResult: HookScenarioResult, callback: Callback) => { - console.log("After"); - callback(); - }); - - After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { - console.log("After"); - callback(); - }); - - After('@tag', (scenarioResult: HookScenarioResult, callback: Callback) => { - console.log("After"); - callback(); - }); - - AfterAll((callback: Callback) => { - console.log("After all"); - callback(); - }); - - AfterAll({ timeout: 1000 }, (callback: Callback) => { - console.log("After all"); - callback(); - }); - - AfterAll('@tag', (callback: Callback) => { - console.log("After all"); - callback(); - }); - - registerHandler('AfterFeatures', (event: any, callback: () => void) => { - callback(); - }); - - Given(/^a variable set to (\d+)$/, (x: string) => { - console.log("the number is: " + x); - }); - - Given(/^a variable set to (\d+)$/, (x: number) => { - console.log(typeof x); - }); - - Given(/^I am on the Cucumber.js GitHub repository$/, function(callback: Callback) { - this.visit('https://github.com/cucumber/cucumber-js', callback); - }); - - When(/^I go to the README file$/, (title: string, callback: Callback) => { +function StepSampleWithoutDefineSupportCode() { + setWorldConstructor(function({attach, parameters}) { + this.attach = attach; + this.parameters = parameters; + this.visit = (url: string, callback: Callback) => { callback(null, 'pending'); - }); - - Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function(title: string, callback: Callback) { - const pageTitle = this.browser.text('title'); - - if (title === pageTitle) { - callback(); - } else { - callback(new Error("Expected to be on page with title " + title)); - } - }); - - // Type for data_table.js on - // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js - - Given(/^a table step with Table raw$/, (table: Table) => { - const expected = [ - ['Cucumber', 'Cucumis sativus'], - ['Burr Gherkin', 'Cucumis anguria'] - ]; - const actual: string[][] = table.raw(); - assert.deepEqual(actual, expected); - }); - - Given(/^a table step with Table rows$/, (table: Table) => { - const expected = [ - ['Apricot', '5'], - ['Brocolli', '2'], - ['Cucumber', '10'] - ]; - const actual: string[][] = table.rows(); - assert.deepEqual(actual, expected); - }); - - Given(/^a table step with Table rowHash$/, (table: Table) => { - const expected = { - Cucumber: 'Cucumis sativus', - 'Burr Gherkin': 'Cucumis anguria' - }; - const actual: { [firstCol: string]: string } = table.rowsHash(); - assert.deepEqual(actual, expected); - }); - - Given(/^a table step$/, (table: Table) => { - const expected = [ - {Vegetable: 'Apricot', Rating: '5'}, - {Vegetable: 'Brocolli', Rating: '2'}, - {Vegetable: 'Cucumber', Rating: '10'} - ]; - const actual: Array<{ [colName: string]: string }> = table.hashes(); - assert.deepEqual(actual, expected); - }); - - defineParameterType({ - regexp: /particular/, - transformer: s => s.toUpperCase(), - typeName: 'param' // deprecated but still supported - }); - - defineParameterType({ - regexp: /particularly/, - transformer: s => s.toUpperCase(), - name: 'param' - }); - - Given('a {param} step', param => { - assert.equal(param, 'PARTICULAR'); - }); + }; }); - const fns: cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns(); + Before((scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.result.status === Status.FAILED); + callback(); + }); - cucumber.clearSupportCodeFns(); -} + Before({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.result.status === Status.FAILED); + callback(); + }); -function registerListener(): cucumber.EventListener { - const listener = Object.assign(cucumber.Listener(), { - handleBeforeScenarioEvent: (scenario: cucumber.events.ScenarioPayload, callback: () => void) => { - // do some interesting stuff ... + Before('@tag', (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.result.status === Status.FAILED); + callback(); + }); + BeforeAll((callback: Callback) => { + console.log("Before all"); + callback(); + }); + + BeforeAll({ timeout: 1000 }, (callback: Callback) => { + console.log("Before all"); + callback(); + }); + + BeforeAll('@tag', (callback: Callback) => { + console.log("Before all"); + callback(); + }); + + After((scenarioResult: HookScenarioResult, callback: Callback) => { + console.log("After"); + callback(); + }); + + After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log("After"); + callback(); + }); + + After('@tag', (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log("After"); + callback(); + }); + + AfterAll((callback: Callback) => { + console.log("After all"); + callback(); + }); + + AfterAll({ timeout: 1000 }, (callback: Callback) => { + console.log("After all"); + callback(); + }); + + AfterAll('@tag', (callback: Callback) => { + console.log("After all"); + callback(); + }); + + Given(/^a variable set to (\d+)$/, (x: string) => { + console.log("the number is: " + x); + }); + + Given(/^a variable set to (\d+)$/, (x: number) => { + console.log(typeof x); + }); + + Given(/^I am on the Cucumber.js GitHub repository$/, function(callback: Callback) { + this.visit('https://github.com/cucumber/cucumber-js', callback); + }); + + When(/^I go to the README file$/, (title: string, callback: Callback) => { + callback(null, 'pending'); + }); + + Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function(title: string, callback: Callback) { + const pageTitle = this.browser.text('title'); + + if (title === pageTitle) { callback(); + } else { + callback(new Error("Expected to be on page with title " + title)); } }); - return listener; + // Type for data_table.js on + // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js + + Given(/^a table step with Table raw$/, (table: Table) => { + const expected = [ + ['Cucumber', 'Cucumis sativus'], + ['Burr Gherkin', 'Cucumis anguria'] + ]; + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); + }); + + Given(/^a table step with Table rows$/, (table: Table) => { + const expected = [ + ['Apricot', '5'], + ['Brocolli', '2'], + ['Cucumber', '10'] + ]; + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); + }); + + Given(/^a table step with Table rowHash$/, (table: Table) => { + const expected = { + Cucumber: 'Cucumis sativus', + 'Burr Gherkin': 'Cucumis anguria' + }; + const actual: { [firstCol: string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); + }); + + Given(/^a table step$/, (table: Table) => { + const expected = [ + {Vegetable: 'Apricot', Rating: '5'}, + {Vegetable: 'Brocolli', Rating: '2'}, + {Vegetable: 'Cucumber', Rating: '10'} + ]; + const actual: Array<{ [colName: string]: string }> = table.hashes(); + assert.deepEqual(actual, expected); + }); + + defineParameterType({ + regexp: /particular/, + transformer: s => s.toUpperCase(), + typeName: 'param' // deprecated but still supported + }); + + defineParameterType({ + regexp: /particularly/, + transformer: s => s.toUpperCase(), + name: 'param', + preferForRegexpMatch: false, + useForSnippets: false + }); + + Given('a {param} step', param => { + assert.equal(param, 'PARTICULAR'); + }); } + +// syntax defineSupportCode deprecated +function StepSample() { + cucumber.defineSupportCode((l) => { + }); +} + +const fns: cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns(); +cucumber.clearSupportCodeFns(); diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index 8c2ad7020e..c222ad567a 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cucumber-js 3.2 +// Type definitions for cucumber-js 4.0 // Project: https://github.com/cucumber/cucumber-js // Definitions by: Abraão Alves // Jan Molak @@ -49,6 +49,29 @@ export interface StepDefinitions { setDefaultTimeout(time: number): void; } +export function After(code: HookCode): void; +export function After(options: HookOptions | string, code: HookCode): void; +export function AfterAll(code: GlobalHookCode): void; +export function AfterAll(options: HookOptions | string, code: GlobalHookCode): void; +export function Before(code: HookCode): void; +export function Before(options: HookOptions | string, code: HookCode): void; +export function BeforeAll(code: GlobalHookCode): void; +export function BeforeAll(options: HookOptions | string, code: GlobalHookCode): void; + +export function defineParameterType(transform: Transform): void; +export function defineStep(pattern: RegExp | string, code: StepDefinitionCode): void; + +export function Given(pattern: RegExp | string, code: StepDefinitionCode): void; +export function Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; +export function setDefaultTimeout(time: number): void; +export function setDefinitionFunctionWrapper(fn: () => void, options?: {[key: string]: any}): void; +// tslint:disable-next-line ban-types +export function setWorldConstructor(world: ((this: World, init: {attach: Function, parameters: {[key: string]: any}}) => void) | {}): void; +export function Then(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; +export function Then(pattern: RegExp | string, code: StepDefinitionCode): void; +export function When(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; +export function When(pattern: RegExp | string, code: StepDefinitionCode): void; + export interface HookScenarioResult { sourceLocation: SourceLocation; result: ScenarioResult; @@ -98,12 +121,11 @@ export namespace pickle { export type HookCode = (this: World, scenario: HookScenarioResult, callback?: CallbackStepDefinition) => void; export type GlobalHookCode = (callback?: CallbackStepDefinition) => void; -// tslint:disable-next-line ban-types -export type AroundCode = (scenario: HookScenarioResult, runScenario?: (error: string, callback?: Function) => void) => void; - export interface Transform { regexp: RegExp; transformer(arg: string): any; + useForSnippets?: boolean; + preferForRegexpMatch?: boolean; name?: string; typeName?: string; // deprecated } @@ -122,12 +144,9 @@ export interface Hooks { After(options: HookOptions | string, code: HookCode): void; AfterAll(code: GlobalHookCode): void; AfterAll(options: HookOptions | string, code: GlobalHookCode): void; - Around(code: AroundCode): void; setDefaultTimeout(time: number): void; // tslint:disable-next-line ban-types setWorldConstructor(world: ((this: World, init: {attach: Function, parameters: {[key: string]: any}}) => void) | {}): void; - registerHandler(handlerOption: string, code: (event: any, callback: CallbackStepDefinition) => void): void; - registerListener(listener: EventListener): void; defineParameterType(transform: Transform): void; } diff --git a/types/cucumber/v3/cucumber-tests.ts b/types/cucumber/v3/cucumber-tests.ts new file mode 100644 index 0000000000..f2aed9aec4 --- /dev/null +++ b/types/cucumber/v3/cucumber-tests.ts @@ -0,0 +1,197 @@ +import * as assert from "power-assert"; +import cucumber = require("cucumber"); + +// You can optionally declare your own world properties +declare module "cucumber" { + interface World { + visit(url: string, callback: CallbackStepDefinition): void; + } +} + +function StepSample() { + type Callback = cucumber.CallbackStepDefinition; + type Table = cucumber.TableDefinition; + type HookScenarioResult = cucumber.HookScenarioResult; + const Status = cucumber.Status; + + cucumber.defineSupportCode(({setWorldConstructor, defineParameterType, After, AfterAll, Around, Before, BeforeAll, registerHandler, Given, When, Then}) => { + setWorldConstructor(function({attach, parameters}) { + this.attach = attach; + this.parameters = parameters; + this.visit = (url: string, callback: Callback) => { + callback(null, 'pending'); + }; + }); + + Before((scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.result.status === Status.FAILED); + callback(); + }); + + Before({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.result.status === Status.FAILED); + callback(); + }); + + Before('@tag', (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.result.status === Status.FAILED); + callback(); + }); + + BeforeAll((callback: Callback) => { + console.log("Before all"); + callback(); + }); + + BeforeAll({ timeout: 1000 }, (callback: Callback) => { + console.log("Before all"); + callback(); + }); + + BeforeAll('@tag', (callback: Callback) => { + console.log("Before all"); + callback(); + }); + + Around((scenarioResult: HookScenarioResult, runScenario: (error: string | null, callback?: () => void) => void) => { + if (scenarioResult.result.status === Status.FAILED) { + runScenario(null, () => { + console.log('finish tasks'); + }); + } + }); + + After((scenarioResult: HookScenarioResult, callback: Callback) => { + console.log("After"); + callback(); + }); + + After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log("After"); + callback(); + }); + + After('@tag', (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log("After"); + callback(); + }); + + AfterAll((callback: Callback) => { + console.log("After all"); + callback(); + }); + + AfterAll({ timeout: 1000 }, (callback: Callback) => { + console.log("After all"); + callback(); + }); + + AfterAll('@tag', (callback: Callback) => { + console.log("After all"); + callback(); + }); + + registerHandler('AfterFeatures', (event: any, callback: () => void) => { + callback(); + }); + + Given(/^a variable set to (\d+)$/, (x: string) => { + console.log("the number is: " + x); + }); + + Given(/^a variable set to (\d+)$/, (x: number) => { + console.log(typeof x); + }); + + Given(/^I am on the Cucumber.js GitHub repository$/, function(callback: Callback) { + this.visit('https://github.com/cucumber/cucumber-js', callback); + }); + + When(/^I go to the README file$/, (title: string, callback: Callback) => { + callback(null, 'pending'); + }); + + Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function(title: string, callback: Callback) { + const pageTitle = this.browser.text('title'); + + if (title === pageTitle) { + callback(); + } else { + callback(new Error("Expected to be on page with title " + title)); + } + }); + + // Type for data_table.js on + // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js + + Given(/^a table step with Table raw$/, (table: Table) => { + const expected = [ + ['Cucumber', 'Cucumis sativus'], + ['Burr Gherkin', 'Cucumis anguria'] + ]; + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); + }); + + Given(/^a table step with Table rows$/, (table: Table) => { + const expected = [ + ['Apricot', '5'], + ['Brocolli', '2'], + ['Cucumber', '10'] + ]; + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); + }); + + Given(/^a table step with Table rowHash$/, (table: Table) => { + const expected = { + Cucumber: 'Cucumis sativus', + 'Burr Gherkin': 'Cucumis anguria' + }; + const actual: { [firstCol: string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); + }); + + Given(/^a table step$/, (table: Table) => { + const expected = [ + {Vegetable: 'Apricot', Rating: '5'}, + {Vegetable: 'Brocolli', Rating: '2'}, + {Vegetable: 'Cucumber', Rating: '10'} + ]; + const actual: Array<{ [colName: string]: string }> = table.hashes(); + assert.deepEqual(actual, expected); + }); + + defineParameterType({ + regexp: /particular/, + transformer: s => s.toUpperCase(), + typeName: 'param' // deprecated but still supported + }); + + defineParameterType({ + regexp: /particularly/, + transformer: s => s.toUpperCase(), + name: 'param' + }); + + Given('a {param} step', param => { + assert.equal(param, 'PARTICULAR'); + }); + }); + + const fns: cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns(); + + cucumber.clearSupportCodeFns(); +} + +function registerListener(): cucumber.EventListener { + const listener = Object.assign(cucumber.Listener(), { + handleBeforeScenarioEvent: (scenario: cucumber.events.ScenarioPayload, callback: () => void) => { + // do some interesting stuff ... + + callback(); + } + }); + + return listener; +} diff --git a/types/cucumber/v3/index.d.ts b/types/cucumber/v3/index.d.ts new file mode 100644 index 0000000000..8c2ad7020e --- /dev/null +++ b/types/cucumber/v3/index.d.ts @@ -0,0 +1,311 @@ +// Type definitions for cucumber-js 3.2 +// Project: https://github.com/cucumber/cucumber-js +// Definitions by: Abraão Alves +// Jan Molak +// Isaiah Soung +// BendingBender +// ErikSchierboom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export enum Status { + AMBIGUOUS = "ambiguous", + FAILED = "failed", + PASSED = "passed", + PENDING = "pending", + SKIPPED = "skipped", + UNDEFINED = "undefined" +} + +export interface World { + [key: string]: any; +} + +export interface CallbackStepDefinition { + pending(): PromiseLike; + (error?: any, pending?: string): void; +} + +export interface TableDefinition { + raw(): string[][]; + rows(): string[][]; + rowsHash(): { [firstCol: string]: string }; + hashes(): Array<{ [colName: string]: string }>; +} + +export type StepDefinitionCode = (this: World, ...stepArgs: any[]) => any; + +export interface StepDefinitionOptions { + timeout?: number; +} + +export interface StepDefinitions { + Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Given(pattern: RegExp | string, code: StepDefinitionCode): void; + When(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + When(pattern: RegExp | string, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, code: StepDefinitionCode): void; + setDefaultTimeout(time: number): void; +} + +export interface HookScenarioResult { + sourceLocation: SourceLocation; + result: ScenarioResult; + pickle: pickle.Pickle; +} + +export interface SourceLocation { + line: number; + url: string; +} + +export interface ScenarioResult { + duration: number; + status: Status; +} + +export namespace pickle { + interface Pickle { + language: string; + locations: Location[]; + name: string; + steps: Step[]; + tags: string[]; + } + + interface Location { + column: number; + line: number; + } + + interface Step { + arguments: Argument[]; + locations: Location[]; + text: string; + } + + interface Argument { + rows: Cell[]; + } + + interface Cell { + location: Location; + value: string; + } +} + +export type HookCode = (this: World, scenario: HookScenarioResult, callback?: CallbackStepDefinition) => void; +export type GlobalHookCode = (callback?: CallbackStepDefinition) => void; + +// tslint:disable-next-line ban-types +export type AroundCode = (scenario: HookScenarioResult, runScenario?: (error: string, callback?: Function) => void) => void; + +export interface Transform { + regexp: RegExp; + transformer(arg: string): any; + name?: string; + typeName?: string; // deprecated +} + +export interface HookOptions { + timeout?: number; + tags?: any; +} + +export interface Hooks { + Before(code: HookCode): void; + Before(options: HookOptions | string, code: HookCode): void; + BeforeAll(code: GlobalHookCode): void; + BeforeAll(options: HookOptions | string, code: GlobalHookCode): void; + After(code: HookCode): void; + After(options: HookOptions | string, code: HookCode): void; + AfterAll(code: GlobalHookCode): void; + AfterAll(options: HookOptions | string, code: GlobalHookCode): void; + Around(code: AroundCode): void; + setDefaultTimeout(time: number): void; + // tslint:disable-next-line ban-types + setWorldConstructor(world: ((this: World, init: {attach: Function, parameters: {[key: string]: any}}) => void) | {}): void; + registerHandler(handlerOption: string, code: (event: any, callback: CallbackStepDefinition) => void): void; + registerListener(listener: EventListener): void; + defineParameterType(transform: Transform): void; +} + +export class EventListener { + hear(event: events.Event, callback: () => void): void; + hasHandlerForEvent(event: events.Event): boolean; + buildHandlerNameForEvent(event: events.Event): string; + getHandlerForEvent(event: events.Event): EventHook; + buildHandlerName(shortName: string): string; + setHandlerForEvent(shortName: string, handler: EventListener): void; +} + +export function Listener(): EventListener; + +export namespace events { + interface Event { + name: string; + data: any; + } + + // tslint:disable-next-line no-empty-interface + interface EventPayload { + } + + interface FeaturesPayload extends EventPayload { + getFeatures(): any[]; // https://github.com/cucumber/cucumber-js/blob/dc698bf5bc10d591fa7adeec5fa21b2d90dc9679/lib/cucumber/runtime.js#L34 + } + + interface FeaturesResultPayload extends EventPayload { + duration: number; + scenarioResults: any[]; + success: boolean; + stepsResults: any[]; + strict: boolean; + } + + interface FeaturePayload extends EventPayload { + description: string; + keyword: string; + line: number; + name: string; + tags: Tag[]; + uri: string; + scenarios: Scenario[]; + } + + interface ScenarioPayload extends EventPayload { + feature: Feature; + exception: Error; + keyword: string; + lines: number[]; + name: string; + tags: Tag[]; + uri: string; + line: number; + description: string; + steps: Step[]; + } + + interface ScenarioResultPayload extends EventPayload { + duration: any; + failureException: Error; + scenario: Scenario; + status: Status; + stepResults: any[]; + } + + interface StepPayload extends EventPayload { + arguments: any; + line: number; + name: string; + scenario: Scenario; + uri: string; + isBackground: boolean; + keyword: string; + keywordType: string; + } + + interface StepResultPayload extends EventPayload { + ambiguousStepDefinitions: any; + attachments: any[]; + duration: any; + failureException: Error; + step: Step; + stepDefinition: StepDefinition; + status: Status; + } +} + +export interface StepDefinition { + // tslint:disable-next-line ban-types + code: Function; + line: number; + options: {}; + pattern: any; + uri: string; +} + +export interface Tag { + name: string; + line: number; +} + +export interface Step { + arguments: any; + line: number; + name: string; + scenario: Scenario; + uri: string; + isBackground: boolean; + keyword: string; + keywordType: string; +} + +export interface Scenario { + feature: Feature; + exception: Error; + keyword: string; + lines: number[]; + name: string; + tags: Tag[]; + uri: string; + line: number; + description: string; + steps: Step[]; +} + +export interface Feature { + description: string; + keyword: string; + line: number; + name: string; + tags: Tag[]; + uri: string; + scenarios: Scenario[]; +} + +export type EventHook = (event: events.Event, callback?: () => void) => void; + +export type SupportCodeConsumer = (stepDefinitions: StepDefinitions & Hooks) => void; + +export function defineSupportCode(consumer: SupportCodeConsumer): void; + +export function getSupportCodeFns(): SupportCodeConsumer[]; + +export function clearSupportCodeFns(): void; + +// https://github.com/cucumber/cucumber-js/commit/231183a8a11c985ef7ced1155b7a75f5120a34b6 +export class Formatter { + constructor(options?: any); + + log(data: any): void; +} + +export class SummaryFormatter extends Formatter { + indent(text: string, numberOfSpaces: number): any; +} + +export class PrettyFormatter extends SummaryFormatter { + formatTags(tags: Tag[]): any; + logIndented(text: string, level: number): void; + logStepResult(stepResult: any): void; +} + +export class ProgressFormatter extends SummaryFormatter { +} + +export class RerunFormatter extends Formatter { +} + +export class SnippetsFormatter extends Formatter { +} + +export class UsageFormatter extends Formatter { +} + +export class UsageJsonFormatter extends Formatter { +} + +export class JsonFormatter extends Formatter { +} diff --git a/types/cucumber/v3/tsconfig.json b/types/cucumber/v3/tsconfig.json new file mode 100644 index 0000000000..badf9c82ed --- /dev/null +++ b/types/cucumber/v3/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "cucumber": [ + "cucumber/v3" + ], + "cucumber/*": [ + "cucumber/v3/*" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cucumber-tests.ts" + ] +} \ No newline at end of file diff --git a/types/cucumber/v3/tslint.json b/types/cucumber/v3/tslint.json new file mode 100644 index 0000000000..215db37b37 --- /dev/null +++ b/types/cucumber/v3/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "no-any-union": false, + "rules": { + "no-any-union": false, + "no-unnecessary-generics": false + } +} diff --git a/types/datatables.net-rowgroup/datatables.net-rowgroup-tests.ts b/types/datatables.net-rowgroup/datatables.net-rowgroup-tests.ts new file mode 100644 index 0000000000..d0149faba2 --- /dev/null +++ b/types/datatables.net-rowgroup/datatables.net-rowgroup-tests.ts @@ -0,0 +1,40 @@ +let config_1: DataTables.Settings = { + // RowGroup extension options + rowGroup: { + className: 'className', + enable: true, + dataSrc: 'data', + endClassName: 'endClassName', + endRender: (rows, group) => { + return `${ group } (${ rows.count() } rows)`; + }, + startRender: (rows, group) => { + return `${ group } (${ rows.count() } rows)`; + } + } +}; + +let dt: DataTables.Api = $("selector").DataTable({ + rowGroup: true +}); + +// Statics +let fixed_1 = new $.fn.dataTable.RowGroup(dt, { + enable: true, +}); + +let fixed_2 = new $.fn.dataTable.RowGroup(dt, true); + +let version = $.fn.dataTable.RowGroup.version; + +$.fn.dataTable.RowGroup.defaults.className = 'row-group-class'; + +// API +dt.rowGroup().dataSrc(); +dt.rowGroup().disable(); +dt.rowGroup().enable(true); + +// Chaining +dt.rowGroup().dataSrc(12) + .rowGroup().disable() + .rowGroup().enable(); diff --git a/types/datatables.net-rowgroup/index.d.ts b/types/datatables.net-rowgroup/index.d.ts new file mode 100644 index 0000000000..e2697c7fac --- /dev/null +++ b/types/datatables.net-rowgroup/index.d.ts @@ -0,0 +1,88 @@ +// Type definitions for datatables.net-rowgroup 1.0 +// Project: https://datatables.net/extensions/rowgroup/ +// Definitions by: Matthieu Tabuteau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// +/// + +declare namespace DataTables { + interface Settings { + /** + * RowGroup extension options + */ + rowGroup?: boolean | RowGroupSettings; + } + + interface StaticFunctions { + RowGroup: RowGroupStaticFunctions; + } + + interface RowGroupStaticFunctions { + new (dt: Api, settings: boolean | RowGroupSettings): undefined; + version: string; + defaults: RowGroupSettings; + } + + interface Api { + rowGroup(): RowGroupApi; + } + + interface RowGroupApi { + /** + * Get the data source for the row grouping + */ + dataSrc(): number|string; + + /** + * Set the data source for the row grouping + */ + dataSrc(prop: number|string): Api; + + /** + * Disable RowGroup's interaction with the table + */ + disable(): Api; + + /** + * Enable or disable RowGroup's interaction with the table + */ + enable(enable?: boolean): Api; + } + + /** + * RowGroup extension options + */ + interface RowGroupSettings { + /** + * Set the class name to be used for the grouping rows + */ + className?: string; + + /** + * Set the data point to use as the grouping data source + */ + dataSrc?: number|string; + + /** + * Provides the ability to disable row grouping at initialisation + */ + enable?: boolean; + + /** + * Set the class name to be used for the grouping end rows + */ + endClassName?: string; + + /** + * Provide a function that can be used to control the data shown in the end grouping row + */ + endRender?: (rows: Api, group: string) => string|HTMLElement|JQuery; + + /** + * Provide a function that can be used to control the data shown in the start grouping row + */ + startRender?: (rows: Api, group: string) => string|HTMLElement|JQuery; + } +} diff --git a/types/datatables.net-rowgroup/tsconfig.json b/types/datatables.net-rowgroup/tsconfig.json new file mode 100644 index 0000000000..c4550cded1 --- /dev/null +++ b/types/datatables.net-rowgroup/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "datatables.net-rowgroup-tests.ts" + ] +} \ No newline at end of file diff --git a/types/datatables.net-rowgroup/tslint.json b/types/datatables.net-rowgroup/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/datatables.net-rowgroup/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dom4/dom4-tests.ts b/types/dom4/dom4-tests.ts index 35867f2e43..7dbf8e12f0 100644 --- a/types/dom4/dom4-tests.ts +++ b/types/dom4/dom4-tests.ts @@ -1,7 +1,7 @@ function testDocument() { - document.query(".container-a").classList; - document.queryAll(".container-b")[0].className; - document.queryAll(".container-c").childElementCount; + document.querySelector(".container-a").classList; + document.querySelectorAll(".container-b")[0].className; + document.querySelector(".container-c").append("foo", document.createElement("button")); } function testElement(el: Element) { diff --git a/types/dom4/index.d.ts b/types/dom4/index.d.ts index 95cabbd4d3..90c9c29966 100644 --- a/types/dom4/index.d.ts +++ b/types/dom4/index.d.ts @@ -1,8 +1,11 @@ -// Type definitions for dom4 v1.5 +// Type definitions for dom4 v2.0 // Project: https://github.com/WebReflection/dom4 // Definitions by: Adi Dahiya , Gilad Gray // Definitions: https://github.com/borisyankov/DefinitelyTyped +/** + * https://dom.spec.whatwg.org/#parentnode + */ interface ParentNode { /** * Returns the child elements. @@ -10,21 +13,46 @@ interface ParentNode { readonly children: HTMLCollection; /** - * Returns the first element that is a descendant of node that matches relativeSelectors. + * Inserts `nodes` after the last child of this node, while replacing strings with equivalent `Text` nodes. */ - query(relativeSelectors: string): Element; + append(...nodes: Array): void; /** - * Returns all element descendants of node that match relativeSelectors. + * Inserts `nodes` before the first child of this node, while replacing strings with equivalent `Text` nodes. */ - queryAll(relativeSelectors: string): Elements; + prepend(...nodes: Array): void; +} + +/** + * https://dom.spec.whatwg.org/#childnode + */ +interface ChildNode { + /** + * Inserts `nodes` just after this node, while replacing strings with equivalent `Text` nodes. + */ + after(...nodes: Array): void; + + /** + * Inserts `nodes` just before this node, while replacing strings with equivalent `Text` nodes. + */ + before(...nodes: Array): void; + + /** + * Replaces this node with `nodes`, while replacing strings in nodes with equivalent Text nodes. + */ + replaceWith(...nodes: Array): void; + + /** + * Removes this node. + */ + remove(): void; } interface Element extends ParentNode { /** * Returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise. */ - closest(selectors: string): Element; + closest(selectors: string): Element | null; /** * Returns true if matching selectors against element’s root yields element, and false otherwise. diff --git a/types/echarts/index.d.ts b/types/echarts/index.d.ts index 0ea8aa0c6a..1f42f8030c 100644 --- a/types/echarts/index.d.ts +++ b/types/echarts/index.d.ts @@ -2,6 +2,7 @@ // Project: http://echarts.baidu.com/ // Definitions by: Xie Jingyang , AntiMoron // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace echarts { function init(dom: HTMLDivElement | HTMLCanvasElement, theme?: Object | string, opts?: { @@ -9,13 +10,13 @@ declare namespace echarts { renderer?: string }): ECharts; - const graphic: { + const graphic: Graphic; + + interface Graphic { clipPointsByRect(points: number[][], rect: ERectangle): number[][]; clipRectByRect(targetRect: ERectangle, rect: ERectangle): ERectangle; - LinearGradient: { new (x: number, y: number, x2: number, y2: number, colorStops: Array, globalCoord?: boolean): LinearGradient } - - }; - + LinearGradient: { new(x: number, y: number, x2: number, y2: number, colorStops: Array, globalCoord?: boolean): LinearGradient } + } function connect(group: string | Array): void; @@ -29,6 +30,15 @@ declare namespace echarts { function registerTheme(themeName: string, theme: Object): void; + interface MapObj { + /** geoJson data for map */ + geoJson: object, + /** special areas fro map */ + specialAreas: object + } + + function getMap(mapName: string): MapObj; + interface LinearGradient { colorStops: Array; global: boolean; @@ -39,9 +49,8 @@ declare namespace echarts { y2: number } - interface ECharts { - group: string; + group: string setOption(option: EChartOption, notMerge?: boolean, notRefreshImmediately?: boolean): void @@ -66,20 +75,20 @@ declare namespace echarts { hideLoading(): void getDataURL(opts: { - // 导出的格式,可选 png, jpeg + /** 导出的格式,可选 png, jpeg */ type?: string, - // 导出的图片分辨率比例,默认为 1。 + /** 导出的图片分辨率比例,默认为 1。*/ pixelRatio?: number, - // 导出的图片背景色,默认使用 option 里的 backgroundColor + /** 导出的图片背景色,默认使用 option 里的 backgroundColor */ backgroundColor?: string }): string getConnectedDataURL(opts: { - // 导出的格式,可选 png, jpeg + /** 导出的格式,可选 png, jpeg */ type: string, - // 导出的图片分辨率比例,默认为 1。 + /** 导出的图片分辨率比例,默认为 1。 */ pixelRatio: number, - // 导出的图片背景色,默认使用 option 里的 backgroundColor + /** 导出的图片背景色,默认使用 option 里的 backgroundColor */ backgroundColor: string }): string @@ -89,42 +98,32 @@ declare namespace echarts { dispose(): void - // 转换逻辑点到像素 - convertToPixel(finder: { - seriesIndex?: number, - seriesId?: string, - seriesName?: string, - geoIndex?: number, - geoId?: string, - geoName?: string, - xAxisIndex?: number, - xAxisId?: string, - xAxisName?: string, - yAxisIndex?: number, - yAxisId?: string, - yAxisName?: string, - gridIndex?: number, - gridId?: string - gridName?: string - } | string, value: string | Array): string | Array + /** 转换逻辑点到像素 */ + convertToPixel(finder: ConvertFinder | string, value: string | Array): string | Array - convertFromPixel(finder: { - seriesIndex?: number, - seriesId?: string, - seriesName?: string, - geoIndex?: number, - geoId?: string, - geoName?: string, - xAxisIndex?: number, - xAxisId?: string, - xAxisName?: string, - yAxisIndex?: number, - yAxisId?: string, - yAxisName?: string, - gridIndex?: number, - gridId?: string - gridName?: string - } | string, value: Array | string): Array | string + convertFromPixel(finder: ConvertFinder | string, value: Array | string): Array | string + + containPixel(finder: ConvertFinder | string, + /** 要被判断的点,为像素坐标值,以 echarts 实例的 dom 节点的左上角为坐标 [0, 0] 点。*/ + value: any[]): boolean + } + + interface ConvertFinder { + seriesIndex?: number, + seriesId?: string, + seriesName?: string, + geoIndex?: number, + geoId?: string, + geoName?: string, + xAxisIndex?: number, + xAxisId?: string, + xAxisName?: string, + yAxisIndex?: number, + yAxisId?: string, + yAxisName?: string, + gridIndex?: number, + gridId?: string + gridName?: string } interface ERectangle { @@ -194,3 +193,7 @@ declare namespace echarts { declare module 'echarts' { export = echarts; } + +declare module 'echarts/lib/echarts' { + export = echarts; +} diff --git a/types/electron-packager/electron-packager-tests.ts b/types/electron-packager/electron-packager-tests.ts index 482c49bbff..4b87704a38 100644 --- a/types/electron-packager/electron-packager-tests.ts +++ b/types/electron-packager/electron-packager-tests.ts @@ -1,8 +1,16 @@ import * as packager from "electron-packager"; -function callback(err: Error, appPath: string) { +function callback(err: Error, appPaths: string[]) { const msg = err.message; - const index = appPath.indexOf("test"); + const index = appPaths.indexOf("test"); +} + +function completeFunction(buildPath: string, electronVersion: string, platform: string, arch: string, callbackFn: () => void) { + callbackFn(); +} + +function ignoreFunction(path: string) { + return true; } packager({ @@ -10,20 +18,38 @@ packager({ name: "myapplication", platform: "win32", arch: "all", - electronVersion: "0.34.0" + electronVersion: "0.34.0", + win32metadata: { + CompanyName: "Acme CO", + FileDescription: "My application", + OriginalFilename: "myapp.exe", + ProductName: "Application", + InternalName: "roadrunner", + "requested-execution-level": "highestAvailable", + "application-manifest": "manifest.xml" + } }, callback); packager({ dir: ".", name: "myapplication", electronVersion: "0.34.0", - all: true + all: true, + win32metadata: { + CompanyName: "Acme CO", + FileDescription: "My application", + OriginalFilename: "myapp.exe", + ProductName: "Application", + InternalName: "roadrunner", + "requested-execution-level": "requireAdministrator", + "application-manifest": "manifest.xml" + } }, callback); packager({ dir: ".", name: "myapplication", - platform: "win32", + platform: "all", arch: "all", electronVersion: "0.34.0" }, callback); @@ -34,3 +60,136 @@ packager({ electronVersion: "0.34.0", all: true }, callback); + +packager({ + dir: ".", + name: "myapplication", + electronVersion: "0.34.0", + arch: "arm64", + executableName: "myapp" +}, callback); + +packager({ + dir: ".", + afterCopy: [ + completeFunction + ], + afterExtract: [ + completeFunction + ], + afterPrune: [ + completeFunction + ], + appCopyright: "Copyright", + appVersion: "1.0", + arch: "ia32", + asar: false, + buildVersion: "1.2.3", + derefSymlinks: true, + download: { + cache: "./zips", + mirror: "https://10.1.2.105/", + quiet: true, + strictSSL: true + }, + extraResource: "foo.js", + icon: "foo.ico", + ignore: /ab+c/, + out: "out", + overwrite: true, + packageManager: false, + prune: true, + quiet: true, + tmpdir: "/tmp", + win32metadata: { + CompanyName: "Acme CO", + FileDescription: "My application", + OriginalFilename: "myapp.exe", + ProductName: "Application", + InternalName: "roadrunner", + "requested-execution-level": "asInvoker", + "application-manifest": "manifest.xml" + } +}, callback); + +packager({ + dir: ".", + arch: "x64", + asar: true, + derefSymlinks: false, + download: { + cache: "./zips", + mirror: "https://10.1.2.105/", + quiet: false, + strictSSL: true + }, + extraResource: [ + "foo.js", + "bar.js" + ], + ignore: [ + /ab+c/, + new RegExp('abc') + ], + overwrite: false, + packageManager: "npm", + platform: "darwin", + prune: false, + quiet: false, + tmpdir: "false", + appBundleId: "123456", + appCategoryType: "public.app-category.developer-tools", + extendInfo: "plist.txt", + helperBundleId: "23223f", + osxSign: true +}, callback); + +packager({ + dir: ".", + arch: "armv7l", + asar: { + ordering: "order.txt", + unpack: "*.js", + unpackDir: "sub_dir" + }, + download: { + cache: "./zips", + mirror: "https://10.1.2.105/", + quiet: false, + strictSSL: false + }, + ignore: ignoreFunction, + packageManager: "cnpm", + platform: "linux" +}, callback); + +packager({ + dir: ".", + arch: [ + "ia32", + "x64" + ], + download: { + cache: "./zips", + mirror: "https://10.1.2.105/", + quiet: true, + strictSSL: false + }, + packageManager: "yarn", + platform: "mas", + extendInfo: { + foo: "bar" + }, + osxSign: { + identity: "myidentity", + entitlements: "path/to/my.entitlements", + "entitlements-inherit": "path/to/inherit.entitlements" + }, + protocols: [{ + name: "myappproto", + schemes: [ + "myapp", + "myapp2" + ] + }] +}, callback); diff --git a/types/electron-packager/index.d.ts b/types/electron-packager/index.d.ts index de33fa3499..6e430ecdb2 100644 --- a/types/electron-packager/index.d.ts +++ b/types/electron-packager/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for electron-packager 8.7 +// Type definitions for electron-packager 10.1 // Project: https://github.com/electron-userland/electron-packager // Definitions by: Maxime LUCE // Juan Jimenez-Anca +// John Kleinschmidt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -31,8 +32,8 @@ declare namespace electronPackager { type ignoreFunction = (path: string) => boolean; type onCompleteFn = (buildPath: string, electronVersion: string, platform: string, arch: string, callbackFn: () => void) => void; - type arch = "ia32" | "x64" | "armv7l" | "all"; - type packageManager = "npm" | "cnpm" | "yarn"; + type arch = "ia32" | "x64" | "armv7l" | "arm64" |"all"; + type packageManager = "npm" | "cnpm" | "yarn" | false; type platform = "linux" | "win32" | "darwin" | "mas" | "all"; interface AsarOptions { @@ -94,7 +95,7 @@ declare namespace electronPackager { * Arbitrary combinations of individual architectures are also supported via a comma-delimited string or array of strings. * The non-all values correspond to the architecture names used by Electron releases. This value is not restricted to the official set if download.mirror is set. */ - arch?: arch; + arch?: arch | arch[]; /** * Whether to package the application's source code into an archive, using Electron's archive format */ @@ -120,6 +121,10 @@ declare namespace electronPackager { * One or more files to be copied directly into the app's Contents/Resources directory for OS X target platforms, and the resources directory for other target platforms. */ extraResource?: string | string[]; + /** + * The name of the executable file, sans file extension. Defaults to the value for the name parameter + */ + executableName?: string; /** * The local path to the icon file, if the target platform supports setting embedding an icon. */ diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 61bdcb9828..22ff839774 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1111,7 +1111,7 @@ declare module 'ember' { * item. This method corresponds to the `forEach()` method defined in * JavaScript 1.6. */ - forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + forEach: GlobalArray['forEach']; /** * Alias for `mapBy` */ @@ -1127,7 +1127,7 @@ declare module 'ember' { * Maps all of the items in the enumeration to another value, returning * a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ - map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + map: GlobalArray['map']; /** * Similar to map, this specialized function returns the value of the named * property on all items in the enumeration. @@ -1138,11 +1138,7 @@ declare module 'ember' { * function returns true for. This method corresponds to `filter()` defined in * JavaScript 1.6. */ - filter( - callbackfn: (value: T, index: number, array: T[]) => value is S, - thisArg?: any - ): S[]; - filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): NativeArray; + filter: GlobalArray['filter']; /** * Returns an array with all of the items in the enumeration where the passed * function returns false. This method is the inverse of filter(). @@ -1165,10 +1161,7 @@ declare module 'ember' { * This method works similar to the `filter()` method defined in JavaScript 1.6 * except that it will stop working on the array once a match is found. */ - find( - predicate: (value: T, index: number, obj: T[]) => boolean, - thisArg?: any - ): T | undefined; + find: GlobalArray['find']; /** * Returns the first item with a property matching the passed value. You * can pass an optional second argument with the target value. Otherwise @@ -1179,10 +1172,7 @@ declare module 'ember' { * Returns `true` if the passed function returns true for every item in the * enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ - every( - callbackfn: (value: T, index: number, array: T[]) => boolean, - thisArg?: any - ): boolean; + every: GlobalArray['every']; /** * Returns `true` if the passed property resolves to the value of the second * argument for all items in the enumerable. This method is often simpler/faster @@ -1205,8 +1195,7 @@ declare module 'ember' { * is a useful way to collect a summary value from an enumeration. This * corresponds to the `reduce()` method defined in JavaScript 1.8. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + reduce: GlobalArray['reduce']; /** * Invokes the named method on every object in the receiver that * implements it. This method corresponds to the implementation in @@ -1616,32 +1605,6 @@ declare module 'ember' { * __Required.__ You must implement this method to apply this mixin. */ length: number; - - // NOTE: some array polyfill methods are re-declared here because their signatures - // differ between typescript versions 2.4 and 2.6. Since we need to compile against - // both, pick the more recent signature and re-declare it here as a tie-breaker. - - /** - * Returns the first item in the array for which the callback returns true. - * This method works similar to the `filter()` method defined in JavaScript 1.6 - * except that it will stop working on the array once a match is found. - */ - find( - predicate: (value: T, index: number, obj: T[]) => boolean, - thisArg?: any - ): T | undefined; - /** - * This will combine the values of the enumerator into a single value. It - * is a useful way to collect a summary value from an enumeration. This - * corresponds to the `reduce()` method defined in JavaScript 1.8. - */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - filter( - callbackfn: (value: T, index: number, array: T[]) => value is S, - thisArg?: any - ): S[]; - filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): Enumerable; } const NativeArray: Mixin>; /** @@ -3321,7 +3284,7 @@ declare module 'ember' { declare module '@ember/application' { import Ember from 'ember'; - export default Ember.Application; + export default class Application extends Ember.Application { } export const getOwner: typeof Ember.getOwner; export const onLoad: typeof Ember.onLoad; export const runLoadHooks: typeof Ember.runLoadHooks; @@ -3336,22 +3299,23 @@ declare module '@ember/application/deprecations' { declare module '@ember/application/globals-resolver' { import Ember from 'ember'; - export default Ember.DefaultResolver; + export default class GlobalsResolver extends Ember.DefaultResolver { } } declare module '@ember/application/instance' { import Ember from 'ember'; - export default Ember.ApplicationInstance; + export default class ApplicationInstance extends Ember.ApplicationInstance { } } declare module '@ember/application/resolver' { import Ember from 'ember'; - export default Ember.Resolver; + export default class Resolver extends Ember.Resolver { } } declare module '@ember/array' { import Ember from 'ember'; - export default Ember.Array; + const EmberArray: typeof Ember.Array; + export default EmberArray; export const A: typeof Ember.A; export const isArray: typeof Ember.isArray; export const makeArray: typeof Ember.makeArray; @@ -3359,43 +3323,44 @@ declare module '@ember/array' { declare module '@ember/array/mutable' { import Ember from 'ember'; - export default Ember.MutableArray; + const MutableArray: typeof Ember.MutableArray; + export default MutableArray; } declare module '@ember/array/proxy' { import Ember from 'ember'; - export default Ember.ArrayProxy; + export default class ArrayProxy extends Ember.ArrayProxy { } } declare module '@ember/component' { import Ember from 'ember'; - export default Ember.Component; + export default class Component extends Ember.Component { } } declare module '@ember/component/checkbox' { import Ember from 'ember'; - export default Ember.Checkbox; + export default class Checkbox extends Ember.Checkbox { } } declare module '@ember/component/helper' { import Ember from 'ember'; - export default Ember.Helper; + export default class Helper extends Ember.Helper { } export const helper: typeof Ember.Helper.helper; } declare module '@ember/component/text-area' { import Ember from 'ember'; - export default Ember.TextArea; + export default class TextArea extends Ember.TextArea { } } declare module '@ember/component/text-field' { import Ember from 'ember'; - export default Ember.TextField; + export default class TextField extends Ember.TextField { } } declare module '@ember/controller' { import Ember from 'ember'; - export default Ember.Controller; + export default class Controller extends Ember.Controller { } export const inject: typeof Ember.inject.controller; } @@ -3412,28 +3377,29 @@ declare module '@ember/debug' { declare module '@ember/debug/container-debug-adapter' { import Ember from 'ember'; - export default Ember.ContainerDebugAdapter; + export default class ContainerDebugAdapter extends Ember.ContainerDebugAdapter { } } declare module '@ember/debug/data-adapter' { import Ember from 'ember'; - export default Ember.DataAdapter; + export default class DataAdapter extends Ember.DataAdapter { } } declare module '@ember/engine' { import Ember from 'ember'; - export default Ember.Engine; + export default class Engine extends Ember.Engine { } export const getEngineParent: typeof Ember.getEngineParent; } declare module '@ember/engine/instance' { import Ember from 'ember'; - export default Ember.EngineInstance; + export default class EngineInstance extends Ember.EngineInstance { } } declare module '@ember/enumerable' { import Ember from 'ember'; - export default Ember.Enumerable; + const Enumerable: typeof Ember.Enumerable; + export default Enumerable; } declare module '@ember/instrumentation' { @@ -3446,17 +3412,17 @@ declare module '@ember/instrumentation' { declare module '@ember/map' { import Ember from 'ember'; - export default Ember.Map; + export default class EmberMap extends Ember.Map { } } declare module '@ember/map/with-default' { import Ember from 'ember'; - export default Ember.MapWithDefault; + export default class MapWithDefault extends Ember.MapWithDefault { } } declare module '@ember/object' { import Ember from 'ember'; - export default Ember.Object; + export default class EmberObject extends Ember.Object { } export const aliasMethod: typeof Ember.aliasMethod; export const computed: typeof Ember.computed; export const defineProperty: typeof Ember.defineProperty; @@ -3471,7 +3437,7 @@ declare module '@ember/object' { declare module '@ember/object/computed' { import Ember from 'ember'; - export default Ember.ComputedProperty; + export default class ComputedProperty extends Ember.ComputedProperty { } export const alias: typeof Ember.computed.alias; export const and: typeof Ember.computed.and; export const bool: typeof Ember.computed.bool; @@ -3509,12 +3475,13 @@ declare module '@ember/object/computed' { declare module '@ember/object/core' { import Ember from 'ember'; - export default Ember.CoreObject; + export default class CoreObject extends Ember.CoreObject { } } declare module '@ember/object/evented' { import Ember from 'ember'; - export default Ember.Evented; + const Evented: typeof Ember.Evented; + export default Evented; export const on: typeof Ember.on; } @@ -3534,12 +3501,14 @@ declare module '@ember/object/internals' { declare module '@ember/object/mixin' { import Ember from 'ember'; - export default Ember.Mixin; + const Mixin: typeof Ember.Mixin; + export default Mixin; } declare module '@ember/object/observable' { import Ember from 'ember'; - export default Ember.Observable; + const Observable: typeof Ember.Observable; + export default Observable; } declare module '@ember/object/observers' { @@ -3550,12 +3519,13 @@ declare module '@ember/object/observers' { declare module '@ember/object/promise-proxy-mixin' { import Ember from 'ember'; - export default Ember.PromiseProxyMixin; + const PromiseProxyMixin: typeof Ember.PromiseProxyMixin; + export default PromiseProxyMixin; } declare module '@ember/object/proxy' { import Ember from 'ember'; - export default Ember.ObjectProxy; + export default class ObjectProxy extends Ember.ObjectProxy { } } declare module '@ember/polyfills' { @@ -3569,42 +3539,43 @@ declare module '@ember/polyfills' { declare module '@ember/routing/auto-location' { import Ember from 'ember'; - export default Ember.AutoLocation; + export default class AutoLocation extends Ember.AutoLocation { } } declare module '@ember/routing/hash-location' { import Ember from 'ember'; - export default Ember.HashLocation; + export default class HashLocation extends Ember.HashLocation { } } declare module '@ember/routing/history-location' { import Ember from 'ember'; - export default Ember.HistoryLocation; + export default class HistoryLocation extends Ember.HistoryLocation { } } declare module '@ember/routing/link-component' { import Ember from 'ember'; - export default Ember.LinkComponent; + export default class LinkComponent extends Ember.LinkComponent { } } declare module '@ember/routing/location' { import Ember from 'ember'; - export default Ember.Location; + const Location: typeof Ember.Location; + export default Location; } declare module '@ember/routing/none-location' { import Ember from 'ember'; - export default Ember.NoneLocation; + export default class NoneLocation extends Ember.NoneLocation { } } declare module '@ember/routing/route' { import Ember from 'ember'; - export default Ember.Route; + export default class Route extends Ember.Route { } } declare module '@ember/routing/router' { import Ember from 'ember'; - export default Ember.Router; + export default class EmberRouter extends Ember.Router { } } declare module '@ember/runloop' { @@ -3626,7 +3597,7 @@ declare module '@ember/runloop' { declare module '@ember/service' { import Ember from 'ember'; - export default Ember.Service; + export default class Service extends Ember.Service { } export const inject: typeof Ember.inject.service; } @@ -3656,7 +3627,7 @@ declare module '@ember/test' { declare module '@ember/test/adapter' { import Ember from 'ember'; - export default Ember.Test.Adapter; + export default class TestAdapter extends Ember.Test.Adapter { } } declare module '@ember/utils' { diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index deecbc23aa..65d6248e3b 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Konstantin Kai // Martynas Kadiša // Jan Aagaard +// Sergio Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -1631,7 +1632,7 @@ declare namespace Notifications { type LocalNotificationId = string | number; function addListener(listener: (notification: Notification) => any): EventSubscription; - function getExponentPushTokenAsync(): Promise; + function getExpoPushTokenAsync(): Promise; function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; function scheduleLocalNotificationAsync( localNotification: LocalNotification, diff --git a/types/express-to-koa/express-to-koa-tests.ts b/types/express-to-koa/express-to-koa-tests.ts new file mode 100644 index 0000000000..73b6ae480a --- /dev/null +++ b/types/express-to-koa/express-to-koa-tests.ts @@ -0,0 +1,12 @@ +import * as Koa from 'koa'; +import * as connect from 'connect'; +import expressToKoa = require('express-to-koa'); + +const app = new Koa(); +const middleware: connect.NextHandleFunction = (req, res, next) => { + // 'express middleware' + next(); +}; + +app.use(expressToKoa(middleware)); +app.listen(3000); diff --git a/types/express-to-koa/index.d.ts b/types/express-to-koa/index.d.ts new file mode 100644 index 0000000000..9a23108943 --- /dev/null +++ b/types/express-to-koa/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for express-to-koa 1.0 +// Project: https://github.com/kaelzhang/express-to-koa +// Definitions by: Xiaohan Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as Koa from "koa"; +import { IncomingMessage, ServerResponse } from "http"; + +export = expressToKoa; + +declare function expressToKoa( + middleware: ( + req: IncomingMessage, + res: ServerResponse, + next: (err?: any) => void, + ) => void +): Koa.Middleware; diff --git a/types/express-to-koa/tsconfig.json b/types/express-to-koa/tsconfig.json new file mode 100644 index 0000000000..9c27ef439f --- /dev/null +++ b/types/express-to-koa/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-to-koa-tests.ts" + ] +} diff --git a/types/express-to-koa/tslint.json b/types/express-to-koa/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-to-koa/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fabric/fabric-tests.ts b/types/fabric/fabric-tests.ts index 2f7d1a7d37..0f51499c0b 100644 --- a/types/fabric/fabric-tests.ts +++ b/types/fabric/fabric-tests.ts @@ -331,10 +331,10 @@ function sample6() { canvas.centerObject(obj); canvas.add(obj); - canvas.add(obj.clone(() => { }).set({ left: 100, top: 100, angle: -15 })); - canvas.add(obj.clone(() => { }).set({ left: 480, top: 100, angle: 15 })); - canvas.add(obj.clone(() => { }).set({ left: 100, top: 400, angle: -15 })); - canvas.add(obj.clone(() => { }).set({ left: 480, top: 400, angle: 15 })); + obj.clone(clone => canvas.add(clone.set({ left: 100, top: 100, angle: -15 }))); + obj.clone(clone => canvas.add(clone.set({ left: 480, top: 100, angle: 15 }))); + obj.clone(clone => canvas.add(clone.set({ left: 100, top: 400, angle: -15 }))); + obj.clone(clone => canvas.add(clone.set({ left: 480, top: 400, angle: 15 }))); canvas.on('mouse:move', options => { const p = canvas.getPointer(options.e); @@ -481,7 +481,7 @@ function sample8() { top, angle, padding: 10, - cornersize: 10 + cornerSize: 10 }); image.scale(getRandomNum(0.1, 0.25)).setCoords(); canvas.add(image); @@ -495,7 +495,7 @@ function sample8() { top, angle, padding: 10, - cornersize: 10 + cornerSize: 10 }); image.scale(getRandomNum(0.1, 1)).setCoords(); canvas.add(image); @@ -515,7 +515,7 @@ function sample8() { top, angle, padding: 10, - cornersize: 10 + cornerSize: 10 }); loadedObject/*.scaleToWidth(300)*/.setCoords(); diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index ac6104d419..2163faecef 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -1,7 +1,11 @@ // Type definitions for FabricJS 1.5 // Project: http://fabricjs.com/ -// Definitions by: Oliver Klemencic , Joseph Livecchi , Michael Randolph +// Definitions by: Oliver Klemencic +// Joseph Livecchi +// Michael Randolph +// Tiger Oakes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 export as namespace fabric; @@ -61,7 +65,7 @@ export function parseStyleAttribute(element: SVGElement): any; * @param [options] Options object * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ -export function parseElements(elements: any[], callback: Function, options?: any, reviver?: Function): void; +export function parseElements(elements: SVGElement[], callback: Function, options?: any, reviver?: Function): void; /** * Returns an object of attributes' name/value, given element and an array of attribute names; * Parses parent "g" nodes recursively upwards. @@ -232,7 +236,7 @@ interface ICollection { * @param context Context (aka thisObject) * @return thisArg */ - forEachObject(callback: (element: Object, index: number, array: Object[]) => any, context?: any): T; + forEachObject(callback: (element: Object, index: number, array: Object[]) => void, context?: any): T; /** * Returns an array of children objects of this instance @@ -279,13 +283,13 @@ interface IObservable { * @param eventName Event name (eg. 'after:render') * @param handler Function that receives a notification when an event of the specified type occurs */ - on(eventName: string, handler: (e: IEvent) => any): T; + on(eventName: string, handler: (e: IEvent) => void): T; /** * Observes specified event * @param eventName Object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) */ - on(eventName: {[key: string]: Function}): T; + on(events: {[eventName: string]: (e: IEvent) => void}): T; /** * Fires event with an optional options object * @param eventName Event name to fire @@ -298,7 +302,7 @@ interface IObservable { * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) * @param handler Function to be deleted from EventListeners */ - off(eventName?: string|any, handler?: (e: IEvent) => any): T; + off(eventName?: string|any, handler?: (e: IEvent) => void): T; } interface Callbacks { @@ -799,14 +803,14 @@ interface IShadowOptions { */ offsetY: number; } -export interface IShadow extends IShadowOptions {} -export class IShadow { +export interface Shadow extends IShadowOptions {} +export class Shadow { constructor(options?: IShadowOptions); - initialize(options?: IShadowOptions|string): IShadow; + initialize(options?: IShadowOptions|string): Shadow; /** * Returns object representation of a shadow */ - toObject(): Object; + toObject(): any; /** * Returns a string representation of an instance, CSS3 text-shadow declaration */ @@ -953,7 +957,7 @@ export class StaticCanvas { * @param callback Callback to invoke when image is loaded and set as background * @param [options] Optional options to set for the {@link fabric.Image|background image}. */ - setBackgroundImage(image: Image|string, callback: Function, options?: IObjectOptions): StaticCanvas; + setBackgroundImage(image: Image|string, callback?: Function, options?: IObjectOptions): StaticCanvas; /** * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas @@ -1112,19 +1116,19 @@ export class StaticCanvas { * Returs dataless JSON representation of canvas * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - toDatalessJSON(propertiesToInclude?: any[]): string; + toDatalessJSON(propertiesToInclude?: string[]): string; /** * Returns object representation of canvas * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns dataless object representation of canvas * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - toDatalessObject(propertiesToInclude?: any[]): any; + toDatalessObject(propertiesToInclude?: string[]): any; /** * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, @@ -1198,7 +1202,7 @@ export class StaticCanvas { * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" * @return `true` if method is supported (or at least exists), null` if canvas element or context can not be initialized */ - supports(methodName: string): boolean; + supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; /** * Populates canvas with data from the specified JSON. @@ -1215,7 +1219,7 @@ export class StaticCanvas { * @param [callback] Receives cloned instance as a first argument * @param [properties] Array of properties to include in the cloned canvas and children */ - clone(callback: (canvas: StaticCanvas) => any, properties?: any[]): void; + clone(callback: (canvas: StaticCanvas) => void, properties?: any[]): void; /** * Clones canvas instance without cloning existing data. @@ -1223,7 +1227,7 @@ export class StaticCanvas { * but leaves data empty (so that you can populate it with your own) * @param [callback] Receives cloned instance as a first argument */ - cloneWithoutData(callback: (canvas: StaticCanvas) => any): void; + cloneWithoutData(callback: (canvas: StaticCanvas) => void): void; /** * Callback; invoked right before object is about to be scaled/rotated @@ -1251,12 +1255,12 @@ export class StaticCanvas { * (either those of HTMLCanvasElement itself, or rendering context) * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" */ - static supports(methodName: string): boolean; + static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; /** * Returns JSON representation of canvas * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - static toJSON(propertiesToInclude?: any[]): string; + static toJSON(propertiesToInclude?: string[]): string; } interface ICanvasOptions extends IStaticCanvasOptions { @@ -1473,12 +1477,12 @@ export class Canvas { * (either those of HTMLCanvasElement itself, or rendering context) * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" */ - static supports(methodName: string): boolean; + static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; /** * Returns JSON representation of canvas * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - static toJSON(propertiesToInclude?: any[]): string; + static toJSON(propertiesToInclude?: string[]): string; } /////////////////////////////////////////////////////////////////////////////// @@ -1527,7 +1531,7 @@ export class Circle { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns svg representation of an instance * @param [reviver] Method for further parsing of svg representation. @@ -1580,7 +1584,7 @@ export class Ellipse { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns svg representation of an instance * @param [reviver] Method for further parsing of svg representation. @@ -1681,7 +1685,7 @@ export class Group { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns string represenation of a group */ @@ -1751,7 +1755,7 @@ export class Image { * @param callback Callback is invoked with a clone as a first argument * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - clone(callback?: Function, propertiesToInclude?: any[]): Object; + clone(callback?: Function, propertiesToInclude?: string[]): void; /** * Returns complexity of an instance * @return complexity of this instance @@ -1791,7 +1795,7 @@ export class Image { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return Object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns string representation of an instance * @return String representation of an instance @@ -1817,20 +1821,20 @@ export class Image { * @param [callback] Callback to invoke when image is created (newly created image is passed as a first argument) * @param [imgOptions] Options object */ - static fromURL(url: string, callback?: (image: Image) => any, objObjects?: IObjectOptions): Image; + static fromURL(url: string, callback?: (image: Image) => void, objObjects?: IObjectOptions): Image; /** * Creates an instance of fabric.Image from its object representation * @param object Object to create an instance from * @param [callback] Callback to invoke when an image instance is created */ - static fromObject(object: any, callback: (image: Image) => {}): void; + static fromObject(object: any, callback: (image: Image) => void): void; /** * Returns Image instance from an SVG element * @param element Element to parse * @param callback Callback to execute when fabric.Image object is created * @param [options] Options object */ - static fromElement(element: SVGElement, callback: Function, options?: IImageOptions): void; + static fromElement(element: SVGElement, callback: (image: Image) => void, options?: IImageOptions): void; /** * Default CSS class name for canvas */ @@ -1877,7 +1881,7 @@ export class Line { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude: any[]): any; + toObject(propertiesToInclude: string[]): any; /** * Returns SVG representation of an instance * @param [reviver] Method for further parsing of svg representation. @@ -1997,6 +2001,11 @@ interface IObjectOptions { */ cornerColor?: string; + /** + * Specify style of control, 'rect' or 'circle' + */ + cornerStrokeColor?: "rect" | "circle"; + /** * When true, this object will use center point as the origin of transformation * when being scaled via the controls. @@ -2066,7 +2075,7 @@ interface IObjectOptions { /** * Shadow object representing shadow of this shape */ - shadow?: IShadow|string; + shadow?: Shadow|string; /** * Opacity of object's controlling borders when object is active and moving @@ -2245,7 +2254,7 @@ export class Object { /* * Sets object's properties from options * @param {Object} [options] Options object */ - setOptions(options: any): void; + setOptions(options: IObjectOptions): void; /** * Transforms context when rendering an object @@ -2258,13 +2267,13 @@ export class Object { * Returns an object representation of an instance * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns (dataless) object representation of an instance * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - toDatalessObject(propertiesToInclude?: any[]): any; + toDatalessObject(propertiesToInclude?: string[]): any; /** * Returns a string representation of an instance @@ -2275,7 +2284,7 @@ export class Object { * Basic getter * @param property Property name */ - get(property: string): any; + get(property: K): this[K]; /** * Sets property to a given value. @@ -2284,26 +2293,26 @@ export class Object { * @param key Property name * @param value Property value (if function, the value is passed into it and its return value is used as a new one) */ - set(key: string, value: any|Function): Object; + set(key: K, value: this[K] | ((value: this[K]) => this[K])): this; /** * Sets property to a given value. * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. * If you need to update those, call `setCoords()`. - * @param Object key Property object, iterate over the object properties + * @param options Property object, iterate over the object properties */ - set(key: any): Object; + set(options: Partial): this; /** * Toggles specified property from `true` to `false` or from `false` to `true` * @param property Property to toggle */ - toggle(property: string): Object; + toggle(property: keyof this): this; /** * Sets sourcePath of an object * @param value Value to set sourcePath to */ - setSourcePath(value: string): Object; + setSourcePath(value: string): this; /** * Retrieves viewportTransform from Object's canvas if possible @@ -2318,17 +2327,17 @@ export class Object { render(ctx: CanvasRenderingContext2D, noTransform?: boolean): void; /** - * Clones an instance + * Clones an instance, using a callback method will work for every object. * @param callback Callback is invoked with a clone as a first argument * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - clone(callback: Function, propertiesToInclude?: any[]): Object; + clone(callback: (clone: Object) => void, propertiesToInclude?: string[]): void; /** * Creates an instance of fabric.Image out of an object * @param callback callback, invoked with an instance as a first argument */ - cloneAsImage(callback: (image: Image) => any): Object; + cloneAsImage(callback: (image: Image) => void): this; /** * Converts an object into a data-url-like string @@ -2351,67 +2360,62 @@ export class Object { * Returns a JSON representation of an instance * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - toJSON(propertiesToInclude?: any[]): any; + toJSON(propertiesToInclude?: string[]): any; /** * Sets gradient (fill or stroke) of an object - * Backwards incompatibility note: This method was named "setGradientFill" until v1.1.0 + * **Backwards incompatibility note:** This method was named "setGradientFill" until v1.1.0 * @param property Property name 'stroke' or 'fill' * @param [options] Options object */ - setGradient(property: string, options: IGradientOptions): Object; + setGradient(property: "stroke" | "fill", options: IGradientOptions): this; /** * Sets pattern fill of an object * @param options Options object */ - setPatternFill(options: IFillOptions): Object; + setPatternFill(options: IFillOptions): this; /** * Sets shadow of an object * @param [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") */ - setShadow(options?: string): Object; - /** - * Sets shadow of an object - * @param [options] Options object - */ - setShadow(options: IShadow): Object; + setShadow(options?: string | Shadow): this; /** * Sets "color" of an instance (alias of `set('fill', …)`) * @param color Color value */ - setColor(color: string): Object; + setColor(color: string): this; /** * Sets "angle" of an instance * @param angle Angle value */ - setAngle(angle: number): Object; + setAngle(angle: number): this; /** * Sets "angle" of an instance * @param angle Angle value */ - rotate(angle: number): Object; + rotate(angle: number): this; /** * Centers object horizontally on canvas to which it was added last. * You might need to call `setCoords` on an object after centering, to update controls area. */ - centerH(): void; + centerH(): this; /** * Centers object vertically on canvas to which it was added last. * You might need to call `setCoords` on an object after centering, to update controls area. */ - centerV(): void; + centerV(): this; /** * Centers object vertically and horizontally on canvas to which is was added last * You might need to call `setCoords` on an object after centering, to update controls area. */ - center(): void; + center(): this; /** * Removes object from canvas to which it was added last @@ -2423,7 +2427,7 @@ export class Object { * @param e Event to operate upon * @param [pointer] Pointer to operate upon (instead of event) */ - getLocalPointer(e: Event, pointer: any): any; + getLocalPointer(e: Event, pointer?: { x: number, y: number }): { x: number, y: number }; /** * Sets object's properties from options @@ -2461,21 +2465,21 @@ export class Object { * @param [options] Object with additional `stateProperties` array to include when saving state * @return thisArg */ - saveState(options?: { stateProperties: any[] }): Object; + saveState(options?: { stateProperties: any[] }): this; /** * Setups state of an object */ - setupState(): Object; + setupState(): this; // functions from object straightening mixin // ----------------------------------------------------------------------------------------------------------------------------------- /** * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer) */ - straighten(): Object; + straighten(): this; /** * Same as straighten but with animation */ - fxStraighten(callbacks: Callbacks): Object; + fxStraighten(callbacks: Callbacks): this; // functions from object stacking mixin // ----------------------------------------------------------------------------------------------------------------------------------- @@ -2483,25 +2487,25 @@ export class Object { * Moves an object up in stack of drawn objects * @param [intersecting] If `true`, send object in front of next upper intersecting object */ - bringForward(intersecting?: boolean): Object; + bringForward(intersecting?: boolean): this; /** * Moves an object to the top of the stack of drawn objects */ - bringToFront(): Object; + bringToFront(): this; /** * Moves an object down in stack of drawn objects * @param [intersecting] If `true`, send object behind next lower intersecting object */ - sendBackwards(intersecting?: boolean): Object; + sendBackwards(intersecting?: boolean): this; /** * Moves an object to the bottom of the stack of drawn objects */ - sendToBack(): Object; + sendToBack(): this; /** * Moves an object to specified level in stack of drawn objects * @param index New position of object */ - moveTo(index: number): Object; + moveTo(index: number): this; // functions from object origin mixin // ----------------------------------------------------------------------------------------------------------------------------------- @@ -2561,7 +2565,7 @@ export class Object { * Requires public options: padding, borderColor * @param ctx Context to draw on */ - drawBorders(context: CanvasRenderingContext2D): Object; + drawBorders(context: CanvasRenderingContext2D): this; /** * Draws corners of an object's bounding box. @@ -2581,7 +2585,7 @@ export class Object { * @param controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. * @param visible true to set the specified control visible, false otherwise */ - setControlVisible(controlName: string, visible: boolean): Object; + setControlVisible(controlName: string, visible: boolean): this; /** * Sets the visibility state of object controls. @@ -2596,7 +2600,7 @@ export class Object { mt?: boolean; tl?: boolean; tr?: boolean; - mtr?: boolean; }): Object; + mtr?: boolean; }): this; // functions from geometry mixin // ------------------------------------------------------------------------------------------------------------------------------- @@ -2604,7 +2608,7 @@ export class Object { * Sets corner position coordinates based on current angle, width and height * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords */ - setCoords(): Object; + setCoords(): this; /** * Returns coordinates of object's bounding rectangle (left, top, width, height) * @return Object with left, top, width, height properties @@ -2631,17 +2635,17 @@ export class Object { * @param value Scale factor * @return thisArg */ - scale(value: number): Object; + scale(value: number): this; /** * Scales an object to a given height, with respect to bounding box (scaling by x/y equally) * @param value New height value */ - scaleToHeight(value: number): Object; + scaleToHeight(value: number): this; /** * Scales an object to a given width, with respect to bounding box (scaling by x/y equally) * @param value New width value */ - scaleToWidth(value: number): Object; + scaleToWidth(value: number): this; /** * Checks if object intersects with another object * @param other Object to test @@ -2671,8 +2675,8 @@ interface IPathOptions extends IObjectOptions { */ minY?: number; } -export interface IPath extends Object, IPathOptions {} -export class IPath { +export interface Path extends Object, IPathOptions {} +export class Path { /** * Constructor * @param path Path data (sequence of coordinates and corresponding "command" tokens) @@ -2680,7 +2684,7 @@ export class IPath { */ constructor(path?: string|any[], options?: IPathOptions); - initialize(path?: any[], options?: IPathOptions): IPath; + initialize(path?: any[], options?: IPathOptions): Path; /** * Returns number representation of an instance complexity @@ -2699,13 +2703,13 @@ export class IPath { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toDatalessObject(propertiesToInclude?: any[]): any; + toDatalessObject(propertiesToInclude?: string[]): any; /** * Returns object representation of an instance * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns string representation of an instance * @return string representation of an instance @@ -2724,12 +2728,12 @@ export class IPath { * @param callback Callback to invoke when an fabric.Path instance is created * @param [options] Options object */ - static fromElement(element: SVGElement, callback: (path: IPath) => any, options?: IPathOptions): void; + static fromElement(element: SVGElement, callback: (path: Path) => any, options?: IPathOptions): void; /** * Creates an instance of fabric.Path from an object * @param callback Callback to invoke when an fabric.Path instance is created */ - static fromObject(object: any, callback: (path: IPath) => any): void; + static fromObject(object: any, callback: (path: Path) => any): void; } export class PathGroup extends Object { @@ -2737,9 +2741,9 @@ export class PathGroup extends Object { * Constructor * @param [options] Options object */ - constructor(paths: IPath[], options?: IObjectOptions); + constructor(paths: Path[], options?: IObjectOptions); - initialize(paths: IPath[], options?: IObjectOptions): void; + initialize(paths: Path[], options?: IObjectOptions): void; /** * Returns number representation of object's complexity * @return complexity @@ -2760,13 +2764,13 @@ export class PathGroup extends Object { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return dataless object representation of an instance */ - toDatalessObject(propertiesToInclude?: any[]): any; + toDatalessObject(propertiesToInclude?: string[]): any; /** * Returns object representation of this path group * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns a string representation of this path group * @return string representation of an object @@ -2782,7 +2786,7 @@ export class PathGroup extends Object { * Returns all paths in this path group * @return array of path objects included in this path group */ - getObjects(): IPath[]; + getObjects(): Path[]; static fromObject(object: any): PathGroup; /** @@ -2829,7 +2833,7 @@ export class Polygon extends Object { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns svg representation of an instance * @param [reviver] Method for further parsing of svg representation. @@ -2891,7 +2895,7 @@ export class Polyline extends Object { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return Object representation of an instance */ - toObject(propertiesToInclude?: any[]): any; + toObject(propertiesToInclude?: string[]): any; /** * Returns SVG representation of an instance * @param [reviver] Method for further parsing of svg representation. @@ -3012,7 +3016,7 @@ interface ITextOptions extends IObjectOptions { * Shadow object representing shadow of this shape. * Backwards incompatibility note?: This property was named "textShadow" (String) until v1.2.11 */ - shadow?: IShadow|string; + shadow?: Shadow|string; /** * Background color of text lines */ @@ -3047,7 +3051,7 @@ export class Text extends Object { * Returns object representation of an instance * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - toObject(propertiesToInclude?: any[]): Object; + toObject(propertiesToInclude?: string[]): any; /** * Returns SVG representation of an instance * @param [reviver] Method for further parsing of svg representation. @@ -3237,7 +3241,7 @@ export class IText extends Object { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output * @return object representation of an instance */ - toObject(propertiesToInclude?: any[]): Object; + toObject(propertiesToInclude?: string[]): any; setText(value: string): Text; /** @@ -3843,7 +3847,7 @@ export class BaseBrush { * Backwards incompatibility note: This property replaces "shadowColor" (String), "shadowOffsetX" (Number), * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12 */ - shadow: IShadow|string; + shadow: Shadow|string; /** * Line endings style of a brush (one of "butt", "round", "square") */ @@ -3924,7 +3928,7 @@ export class PatternBrush extends PencilBrush { /** * Creates path */ - createPath(pathData: string): IPath; + createPath(pathData: string): Path; } export class PencilBrush extends BaseBrush { /** @@ -3937,7 +3941,7 @@ export class PencilBrush extends BaseBrush { * Creates fabric.Path object to add on canvas * @param pathData Path data */ - createPath(pathData: string): IPath; + createPath(pathData: string): Path; } /////////////////////////////////////////////////////////////////////////////// @@ -4258,6 +4262,13 @@ interface IUtilMisc { */ rotatePoint(point: Point, origin: Point, radians: number): Point; + /** + * Rotates `vector` with `radians` + * @param vector The vector to rotate (x and y) + * @param radians The radians of the angle for the rotation + */ + rotateVector(vector: { x: number, y: number }, radians: number): { x: number, y: number }; + /** * Apply transform t to point p * @param p The point to transform @@ -4378,7 +4389,13 @@ interface IUtilMisc { * @param a First transformMatrix * @param b Second transformMatrix */ - multiplyTransformMatrices(a: any[], b: any[]): any[]; + multiplyTransformMatrices(a: number[], b: number[]): number[]; + + /** + * Decomposes standard 2x2 matrix into transform componentes + * @param a transformMatrix + */ + qrDecompose(a: number[]): { angle: number, scaleX: number, scaleY: number, skewX: number, skewY: number, translateX: number, translateY: number }; /** * Returns string representation of function body diff --git a/types/feathersjs__authentication-client/feathersjs__authentication-client-tests.ts b/types/feathersjs__authentication-client/feathersjs__authentication-client-tests.ts index 3d4eb36362..2a4ea96f91 100644 --- a/types/feathersjs__authentication-client/feathersjs__authentication-client-tests.ts +++ b/types/feathersjs__authentication-client/feathersjs__authentication-client-tests.ts @@ -1,4 +1,11 @@ +import feathers from '@feathersjs/feathers'; import feathersAuthClient from '@feathersjs/authentication-client'; -// we can't really do much, because the augmentation of @feathersjs/feathers breaks importing it here. -const configureFn = feathersAuthClient({}); +const app = feathers(); +app.configure(feathersAuthClient()); +app.authenticate({strategy : 'abcdef'}).then(() => {}); +app.logout().then(() => {}); + +// check if the non-augmented @feathersjs/feathers typings still work +app.on('asd', () => {}); +app.service('asd').get(0).then(() => {}); diff --git a/types/feathersjs__authentication-client/feathersjs__feathers.d.ts b/types/feathersjs__authentication-client/feathersjs__feathers.d.ts deleted file mode 100644 index 9c0fa2e05e..0000000000 --- a/types/feathersjs__authentication-client/feathersjs__feathers.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -declare module '@feathersjs/feathers' { - import { - FeathersAuthCredentials, - Passport - } from '@feathersjs/authentication-client'; - - interface Application { - authenticate(options?: FeathersAuthCredentials): Promise; - - logout(): Promise; - - passport: Passport; - } -} diff --git a/types/feathersjs__authentication-client/index.d.ts b/types/feathersjs__authentication-client/index.d.ts index a29039aab9..16f4f4a415 100644 --- a/types/feathersjs__authentication-client/index.d.ts +++ b/types/feathersjs__authentication-client/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Abraao Alves , Jan Lohage // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript -import './feathersjs__feathers'; - export default function feathersAuthClient(config?: FeathersAuthClientConfig): () => void; export interface FeathersAuthClientConfig { @@ -62,3 +60,13 @@ export interface Passport { getStorage(storage: any): any; } + +declare module '@feathersjs/feathers' { + interface Application { + authenticate(options?: FeathersAuthCredentials): Promise; + + logout(): Promise; + + passport: Passport; + } +} diff --git a/types/feathersjs__express/feathersjs__express-tests.ts b/types/feathersjs__express/feathersjs__express-tests.ts index d7f981eaa0..687191d0c6 100644 --- a/types/feathersjs__express/feathersjs__express-tests.ts +++ b/types/feathersjs__express/feathersjs__express-tests.ts @@ -1,5 +1,8 @@ import feathers, { Application } from '@feathersjs/feathers'; -import feathersExpress from '@feathersjs/express'; -import { Application as ExpressApplication } from 'express'; +import feathersExpress, { original, rest, notFound, errorHandler } from '@feathersjs/express'; -const app: ExpressApplication & Application<{}> = feathersExpress(feathers()); +const app = feathersExpress(feathers()); + +app.configure(rest()); +app.use(notFound()); +app.use(errorHandler()); diff --git a/types/feathersjs__express/index.d.ts b/types/feathersjs__express/index.d.ts index 2bce8b54dd..eb49f00a78 100644 --- a/types/feathersjs__express/index.d.ts +++ b/types/feathersjs__express/index.d.ts @@ -5,6 +5,44 @@ // TypeScript Version: 2.2 import { Application as FeathersApplication } from '@feathersjs/feathers'; -import { Application as ExpressApplication } from 'express'; +import * as express from 'express'; -export default function feathersExpress(app: FeathersApplication): ExpressApplication & FeathersApplication; +export default function feathersExpress(app: FeathersApplication): Application; +export type Application = express.Application & FeathersApplication; + +export function errorHandler(options?: any): express.ErrorRequestHandler; +export function notFound(): express.RequestHandler; +export const rest: { + (): () => void; + formatter: express.RequestHandler; +}; + +/* + * Re-export of the express package. + **/ + +export { + CookieOptions, + Errback, + ErrorRequestHandler, + Express, + Handler, + IRoute, + IRouter, + IRouterHandler, + IRouterMatcher, + json, + MediaType, + NextFunction, + Request, + RequestHandler, + RequestParamHandler, + Response, + Router, + RouterOptions, + Send, + static, + urlencoded +} from 'express'; + +export const original: typeof express; diff --git a/types/feathersjs__primus/index.d.ts b/types/feathersjs__primus/index.d.ts index 9218a6a40e..5d93843822 100644 --- a/types/feathersjs__primus/index.d.ts +++ b/types/feathersjs__primus/index.d.ts @@ -2,6 +2,9 @@ // Project: http://feathersjs.com/ // Definitions by: Jan Lohage // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript +// TypeScript Version: 2.3 + +/// // primus removed its typings from the repo https://github.com/primus/primus/pull/623, as of 01/2018 there are none on DT export default function feathersPrimus(options: any, callback?: (primus: any) => void): () => void; diff --git a/types/feathersjs__socket-commons/feathers.d.ts b/types/feathersjs__socket-commons/feathers.d.ts deleted file mode 100644 index 08438e4899..0000000000 --- a/types/feathersjs__socket-commons/feathers.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -declare module '@feathersjs/feathers' { - import { Channel } from '@feathersjs/socket-commons'; - import { HookContext } from '@feathersjs/feathers'; - - export interface ServiceAddons { - publish(callback: (data: T, hook: HookContext) => Channel): this - - publish(event: string, callback: (data: T, hook: HookContext) => Channel): this - } - - export interface Application { - channel(...names: string[]): Channel; - - publish(callback: (data: T, hook: HookContext) => Channel | Channel[]): Application; - - publish(event: string, callback: (data: T, hook: HookContext) => Channel | Channel[]): Application; - } -} diff --git a/types/feathersjs__socket-commons/feathersjs__socket-commons-tests.ts b/types/feathersjs__socket-commons/feathersjs__socket-commons-tests.ts index 2b7e49481e..e52fa00d78 100644 --- a/types/feathersjs__socket-commons/feathersjs__socket-commons-tests.ts +++ b/types/feathersjs__socket-commons/feathersjs__socket-commons-tests.ts @@ -1 +1,9 @@ -const dummy: any = null; +import feathers from '@feathersjs/feathers'; + +const app = feathers(); + +app.channel('abc').send({}); + +// check if the non-augmented @feathersjs/feathers typings still work +app.on('asd', () => {}); +app.service('asd').get(0).then(() => {}); diff --git a/types/feathersjs__socket-commons/index.d.ts b/types/feathersjs__socket-commons/index.d.ts index 38d46a0ec5..fca658bf76 100644 --- a/types/feathersjs__socket-commons/index.d.ts +++ b/types/feathersjs__socket-commons/index.d.ts @@ -2,6 +2,34 @@ // Project: http://feathersjs.com/ // Definitions by: Jan Lohage // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript +// TypeScript Version: 2.3 -import './socket-commons'; -import './feathers'; +import { HookContext } from '@feathersjs/feathers'; + +export type Connection = any; // todo: spec connection + +export interface Channel { + join(...connections: Connection[]): this; + + leave(...connections: Connection[]): this; + + filter(callback: (connection: Connection) => boolean): Channel; + + send(data: any): this; +} + +declare module '@feathersjs/feathers' { + interface ServiceAddons { + publish(callback: (data: T, hook: HookContext) => Channel): this; + + publish(event: string, callback: (data: T, hook: HookContext) => Channel): this; + } + + interface Application { + channel(...names: string[]): Channel; + + publish(callback: (data: T, hook: HookContext) => Channel | Channel[]): Application; + + publish(event: string, callback: (data: T, hook: HookContext) => Channel | Channel[]): Application; + } +} diff --git a/types/feathersjs__socket-commons/socket-commons.d.ts b/types/feathersjs__socket-commons/socket-commons.d.ts deleted file mode 100644 index 2f32f24bd4..0000000000 --- a/types/feathersjs__socket-commons/socket-commons.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -declare module '@feathersjs/socket-commons' { - export type Connection = any; // todo: spec connection - - export interface Channel { - join(...connections: Connection[]): this; - - leave(...connections: Connection[]): this; - - filter(callback: (connection: Connection) => boolean): Channel; - - send(data: any): this; - } -} diff --git a/types/feathersjs__socketio/index.d.ts b/types/feathersjs__socketio/index.d.ts index 3994f73537..34b78eb749 100644 --- a/types/feathersjs__socketio/index.d.ts +++ b/types/feathersjs__socketio/index.d.ts @@ -2,8 +2,10 @@ // Project: http://feathersjs.com/ // Definitions by: Jan Lohage // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript +// TypeScript Version: 2.3 /// +/// export default function feathersSocketIO(callback: (io: SocketIO.Server) => void): () => void; export default function feathersSocketIO(options: number | SocketIO.ServerOptions, callback?: (io: SocketIO.Server) => void): () => void; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index e6783255eb..85f02aaad0 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -161,5 +161,6 @@ export interface Feature extend * https://tools.ietf.org/html/rfc7946#section-3.3 */ export interface FeatureCollection extends GeoJsonObject { + type: "FeatureCollection"; features: Array>; } diff --git a/types/google-libphonenumber/index.d.ts b/types/google-libphonenumber/index.d.ts index 0e410e121c..9a46ac69a6 100644 --- a/types/google-libphonenumber/index.d.ts +++ b/types/google-libphonenumber/index.d.ts @@ -42,7 +42,6 @@ declare namespace libphonenumber { hasCountryCode(): boolean; countryCodeCount(): number; clearCountryCode(): void; - getNationalNumber(): number | undefined; getNationalNumberOrDefault(): number; setNationalNumber(value: number): number; @@ -115,6 +114,7 @@ declare namespace libphonenumber { format(phoneNumber: PhoneNumber, format: PhoneNumberFormat): string; getNddPrefixForRegion(regionCode?: string, stripNonDigits?: boolean): string | undefined; getNumberType(phoneNumber: PhoneNumber): PhoneNumberType; + getCountryCodeForRegion(supportedRegion:string):string; getRegionCodeForCountryCode(countryCallingCode: number): string; getRegionCodeForNumber(phoneNumber: PhoneNumber): string | undefined; getSupportedRegions():string []; diff --git a/types/google.analytics/index.d.ts b/types/google.analytics/index.d.ts index b0412a362f..b7d4a8a6f4 100644 --- a/types/google.analytics/index.d.ts +++ b/types/google.analytics/index.d.ts @@ -39,9 +39,8 @@ interface GoogleAnalytics { declare namespace UniversalAnalytics { // https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference - enum HitType { - 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing' - } + // https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#hitType + type HitType = 'pageview' | 'screenview' | 'event' | 'transaction' | 'item' | 'social' | 'exception' | 'timing'; // https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference @@ -294,7 +293,7 @@ declare namespace UniversalAnalytics { flashVersion?: string; forceSSL?: boolean; hitCallback?(): void; - hitType?: string; + hitType?: HitType; hostname?: string; id?: string; javaEnabled?: boolean; diff --git a/types/graphql-iso-date/graphql-iso-date-tests.ts b/types/graphql-iso-date/graphql-iso-date-tests.ts new file mode 100644 index 0000000000..abc417cf5a --- /dev/null +++ b/types/graphql-iso-date/graphql-iso-date-tests.ts @@ -0,0 +1,5 @@ +import { GraphQLDate, GraphQLTime, GraphQLDateTime } from "graphql-iso-date"; + +GraphQLDate.name; +GraphQLTime.name; +GraphQLDateTime.name; diff --git a/types/graphql-iso-date/index.d.ts b/types/graphql-iso-date/index.d.ts new file mode 100644 index 0000000000..7f0731478e --- /dev/null +++ b/types/graphql-iso-date/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for graphql-iso-date 3.3 +// Project: https://github.com/excitement-engineer/graphql-iso-date +// Definitions by: Jason Waldrip +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { GraphQLScalarType } from "graphql"; + +export const GraphQLDate: GraphQLScalarType; +export const GraphQLTime: GraphQLScalarType; +export const GraphQLDateTime: GraphQLScalarType; diff --git a/types/graphql-iso-date/tsconfig.json b/types/graphql-iso-date/tsconfig.json new file mode 100644 index 0000000000..6feabb1388 --- /dev/null +++ b/types/graphql-iso-date/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "graphql-iso-date-tests.ts" + ] +} diff --git a/types/graphql-iso-date/tslint.json b/types/graphql-iso-date/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-iso-date/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/graphql/error/GraphQLError.d.ts b/types/graphql/error/GraphQLError.d.ts index fbafcb1e30..116f17c3fa 100644 --- a/types/graphql/error/GraphQLError.d.ts +++ b/types/graphql/error/GraphQLError.d.ts @@ -9,60 +9,60 @@ import { Source } from '../language/source'; * GraphQL document and/or execution result that correspond to the Error. */ export class GraphQLError extends Error { - /** - * A message describing the Error for debugging purposes. - * - * Enumerable, and appears in the result of JSON.stringify(). - */ - message: string; + /** + * A message describing the Error for debugging purposes. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + message: string; - /** - * An array of { line, column } locations within the source GraphQL document - * which correspond to this error. - * - * Errors during validation often contain multiple locations, for example to - * point out two things with the same name. Errors during execution include a - * single location, the field which produced the error. - * - * Enumerable, and appears in the result of JSON.stringify(). - */ - locations?: Array<{ line: number, column: number }> | undefined; + /** + * An array of { line, column } locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + locations?: Array<{ line: number; column: number }> | undefined; - /** - * An array describing the JSON-path into the execution response which - * corresponds to this error. Only included for errors during execution. - * - * Enumerable, and appears in the result of JSON.stringify(). - */ - path?: Array | undefined; + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + path?: Array | undefined; - /** - * An array of GraphQL AST Nodes corresponding to this error. - */ - nodes?: ASTNode[] | undefined; + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + nodes?: ASTNode[] | undefined; - /** - * The source GraphQL document corresponding to this error. - */ - source?: Source | undefined; + /** + * The source GraphQL document corresponding to this error. + */ + source?: Source | undefined; - /** - * An array of character offsets within the source GraphQL document - * which correspond to this error. - */ - positions?: number[] | undefined; + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + positions?: number[] | undefined; - /** - * The original error thrown from a field resolver during execution. - */ - originalError?: Error; + /** + * The original error thrown from a field resolver during execution. + */ + originalError?: Error; - constructor( - message: string, - nodes?: any[], - source?: Source, - positions?: number[], - path?: Array, - originalError?: Error, - ); + constructor( + message: string, + nodes?: any[], + source?: Source, + positions?: number[], + path?: Array, + originalError?: Error, + ); } diff --git a/types/graphql/error/formatError.d.ts b/types/graphql/error/formatError.d.ts index fbb31cdb23..26dbe0f743 100644 --- a/types/graphql/error/formatError.d.ts +++ b/types/graphql/error/formatError.d.ts @@ -7,12 +7,12 @@ import { GraphQLError } from './GraphQLError'; export function formatError(error: GraphQLError): GraphQLFormattedError; export interface GraphQLFormattedError { - message: string; - locations?: GraphQLErrorLocation[]; - path?: Array; + message: string; + locations?: GraphQLErrorLocation[]; + path?: Array; } export interface GraphQLErrorLocation { - line: number; - column: number; + line: number; + column: number; } diff --git a/types/graphql/error/index.d.ts b/types/graphql/error/index.d.ts index cfb5b92740..0e9a557794 100644 --- a/types/graphql/error/index.d.ts +++ b/types/graphql/error/index.d.ts @@ -1,4 +1,8 @@ export { GraphQLError } from './GraphQLError'; export { syntaxError } from './syntaxError'; export { locatedError } from './locatedError'; -export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from './formatError'; +export { + formatError, + GraphQLFormattedError, + GraphQLErrorLocation, +} from './formatError'; diff --git a/types/graphql/error/locatedError.d.ts b/types/graphql/error/locatedError.d.ts index c827f8ede8..64fadf49f4 100644 --- a/types/graphql/error/locatedError.d.ts +++ b/types/graphql/error/locatedError.d.ts @@ -6,7 +6,7 @@ import { GraphQLError } from './GraphQLError'; * document responsible for the original Error. */ export function locatedError( - originalError: Error, - nodes: T[], - path: Array + originalError: Error, + nodes: T[], + path: Array, ): GraphQLError; diff --git a/types/graphql/error/syntaxError.d.ts b/types/graphql/error/syntaxError.d.ts index 80c4453e03..ccf84044ca 100644 --- a/types/graphql/error/syntaxError.d.ts +++ b/types/graphql/error/syntaxError.d.ts @@ -6,7 +6,7 @@ import { GraphQLError } from './GraphQLError'; * descriptive information about the syntax error's position in the source. */ export function syntaxError( - source: Source, - position: number, - description: string + source: Source, + position: number, + description: string, ): GraphQLError; diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index c8ee7d9215..ea6ab8ed39 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -1,14 +1,18 @@ import { GraphQLError, locatedError } from '../error'; import { GraphQLSchema } from '../type/schema'; -import { GraphQLField, GraphQLFieldResolver, ResponsePath } from '../type/definition'; import { - DirectiveNode, - DocumentNode, - OperationDefinitionNode, - SelectionSetNode, - FieldNode, - InlineFragmentNode, - FragmentDefinitionNode, + GraphQLField, + GraphQLFieldResolver, + ResponsePath, +} from '../type/definition'; +import { + DirectiveNode, + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + InlineFragmentNode, + FragmentDefinitionNode, } from '../language/ast'; /** * Data that must be available at all points during query execution. @@ -17,13 +21,13 @@ import { * and the fragments defined in the query document */ export interface ExecutionContext { - schema: GraphQLSchema; - fragments: { [key: string]: FragmentDefinitionNode }; - rootValue: any; - operation: OperationDefinitionNode; - variableValues: { [key: string]: any }; - fieldResolver: GraphQLFieldResolver; - errors: GraphQLError[]; + schema: GraphQLSchema; + fragments: { [key: string]: FragmentDefinitionNode }; + rootValue: any; + operation: OperationDefinitionNode; + variableValues: { [key: string]: any }; + fieldResolver: GraphQLFieldResolver; + errors: GraphQLError[]; } /** @@ -33,19 +37,19 @@ export interface ExecutionContext { * non-empty array if an error occurred. */ export interface ExecutionResult { - data?: { [key: string]: any }; - extensions?: { [key: string]: any }; - errors?: GraphQLError[]; + data?: { [key: string]: any }; + extensions?: { [key: string]: any }; + errors?: GraphQLError[]; } export type ExecutionArgs = { - schema: GraphQLSchema, - document: DocumentNode, - rootValue?: any, - contextValue?: any, - variableValues?: {[key: string]: any}, - operationName?: string, - fieldResolver?: GraphQLFieldResolver + schema: GraphQLSchema; + document: DocumentNode; + rootValue?: any; + contextValue?: any; + variableValues?: { [key: string]: any }; + operationName?: string; + fieldResolver?: GraphQLFieldResolver; }; /** @@ -60,24 +64,22 @@ export type ExecutionArgs = { */ export function execute(args: ExecutionArgs): Promise; export function execute( - schema: GraphQLSchema, - document: DocumentNode, - rootValue?: any, - contextValue?: any, - variableValues?: { - [key: string]: any - }, - operationName?: string, - fieldResolver?: GraphQLFieldResolver, + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: { + [key: string]: any; + }, + operationName?: string, + fieldResolver?: GraphQLFieldResolver, ): Promise; /** * Given a ResponsePath (found in the `path` entry in the information provided * as the last argument to a field resolver), return an Array of the path keys. */ -export function responsePathAsArray( - path: ResponsePath -): Array; +export function responsePathAsArray(path: ResponsePath): Array; export function addPath(prev: ResponsePath, key: string | number): any; diff --git a/types/graphql/execution/index.d.ts b/types/graphql/execution/index.d.ts index 4bf4e395ab..a5c4980c0a 100644 --- a/types/graphql/execution/index.d.ts +++ b/types/graphql/execution/index.d.ts @@ -1,9 +1,9 @@ export { - execute, - defaultFieldResolver, - responsePathAsArray, - ExecutionArgs, - ExecutionResult + execute, + defaultFieldResolver, + responsePathAsArray, + ExecutionArgs, + ExecutionResult, } from './execute'; export { getDirectiveValues } from './values'; diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index 79a0176f8d..08e6041aa2 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -1,7 +1,15 @@ -import { GraphQLInputType, GraphQLField, GraphQLArgument } from '../type/definition'; +import { + GraphQLInputType, + GraphQLField, + GraphQLArgument, +} from '../type/definition'; import { GraphQLDirective } from '../type/directives'; import { GraphQLSchema } from '../type/schema'; -import { FieldNode, DirectiveNode, VariableDefinitionNode } from '../language/ast'; +import { + FieldNode, + DirectiveNode, + VariableDefinitionNode, +} from '../language/ast'; /** * Prepares an object map of variableValues of the correct type based on the @@ -9,9 +17,9 @@ import { FieldNode, DirectiveNode, VariableDefinitionNode } from '../language/as * parsed to match the variable definitions, a GraphQLError will be thrown. */ export function getVariableValues( - schema: GraphQLSchema, - varDefNodes: VariableDefinitionNode[], - inputs: { [key: string]: any } + schema: GraphQLSchema, + varDefNodes: VariableDefinitionNode[], + inputs: { [key: string]: any }, ): { [key: string]: any }; /** @@ -19,9 +27,9 @@ export function getVariableValues( * definitions and list of argument AST nodes. */ export function getArgumentValues( - def: GraphQLField | GraphQLDirective, - node: FieldNode | DirectiveNode, - variableValues?: { [key: string]: any } + def: GraphQLField | GraphQLDirective, + node: FieldNode | DirectiveNode, + variableValues?: { [key: string]: any }, ): { [key: string]: any }; /** @@ -32,7 +40,7 @@ export function getArgumentValues( * If the directive does not exist on the node, returns undefined. */ export function getDirectiveValues( - directiveDef: GraphQLDirective, - node: { directives?: Array }, - variableValues?: { [key: string]: any } + directiveDef: GraphQLDirective, + node: { directives?: Array }, + variableValues?: { [key: string]: any }, ): void | { [key: string]: any }; diff --git a/types/graphql/language/ast.d.ts b/types/graphql/language/ast.d.ts index 24344fe904..1873caeb1f 100644 --- a/types/graphql/language/ast.d.ts +++ b/types/graphql/language/ast.d.ts @@ -5,30 +5,30 @@ import { Source } from './source'; * identify the region of the source from which the AST derived. */ export interface Location { - /** - * The character offset at which this Node begins. - */ - start: number; + /** + * The character offset at which this Node begins. + */ + start: number; - /** - * The character offset at which this Node ends. - */ - end: number; + /** + * The character offset at which this Node ends. + */ + end: number; - /** - * The Token at which this Node begins. - */ - startToken: Token; + /** + * The Token at which this Node begins. + */ + startToken: Token; - /** - * The Token at which this Node ends. - */ - endToken: Token; + /** + * The Token at which this Node ends. + */ + endToken: Token; - /** - * The Source document the AST represents. - */ - source: Source; + /** + * The Source document the AST represents. + */ + source: Source; } /** @@ -37,181 +37,181 @@ export interface Location { * *only*. */ type TokenKind = - | '' - | '' - | '!' - | '$' - | '(' - | ')' - | '...' - | ':' - | '=' - | '@' - | '[' - | ']' - | '{' - | '|' - | '}' - | 'Name' - | 'Int' - | 'Float' - | 'String' - | 'BlockString' - | 'Comment'; + | '' + | '' + | '!' + | '$' + | '(' + | ')' + | '...' + | ':' + | '=' + | '@' + | '[' + | ']' + | '{' + | '|' + | '}' + | 'Name' + | 'Int' + | 'Float' + | 'String' + | 'BlockString' + | 'Comment'; /** * Represents a range of characters represented by a lexical token * within a Source. */ export interface Token { - /** - * The kind of Token. - */ - kind: TokenKind; + /** + * The kind of Token. + */ + kind: TokenKind; - /** - * The character offset at which this Node begins. - */ - start: number; + /** + * The character offset at which this Node begins. + */ + start: number; - /** - * The character offset at which this Node ends. - */ - end: number; + /** + * The character offset at which this Node ends. + */ + end: number; - /** - * The 1-indexed line number on which this Token appears. - */ - line: number; + /** + * The 1-indexed line number on which this Token appears. + */ + line: number; - /** - * The 1-indexed column number at which this Token begins. - */ - column: number; + /** + * The 1-indexed column number at which this Token begins. + */ + column: number; - /** - * For non-punctuation tokens, represents the interpreted value of the token. - */ - value: string | undefined; + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + value: string | undefined; - /** - * Tokens exist as nodes in a double-linked-list amongst all tokens - * including ignored tokens. is always the first node and - * the last. - */ - prev?: Token; - next?: Token; + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + prev?: Token; + next?: Token; } /** * The list of all possible AST node types. */ export type ASTNode = - | NameNode - | DocumentNode - | OperationDefinitionNode - | VariableDefinitionNode - | VariableNode - | SelectionSetNode - | FieldNode - | ArgumentNode - | FragmentSpreadNode - | InlineFragmentNode - | FragmentDefinitionNode - | IntValueNode - | FloatValueNode - | StringValueNode - | BooleanValueNode - | NullValueNode - | EnumValueNode - | ListValueNode - | ObjectValueNode - | ObjectFieldNode - | DirectiveNode - | NamedTypeNode - | ListTypeNode - | NonNullTypeNode - | SchemaDefinitionNode - | OperationTypeDefinitionNode - | ScalarTypeDefinitionNode - | ObjectTypeDefinitionNode - | FieldDefinitionNode - | InputValueDefinitionNode - | InterfaceTypeDefinitionNode - | UnionTypeDefinitionNode - | EnumTypeDefinitionNode - | EnumValueDefinitionNode - | InputObjectTypeDefinitionNode - | ScalarTypeExtensionNode - | ObjectTypeExtensionNode - | InterfaceTypeExtensionNode - | UnionTypeExtensionNode - | EnumTypeExtensionNode - | InputObjectTypeExtensionNode - | DirectiveDefinitionNode; + | NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode + | DirectiveDefinitionNode; /** * Utility type listing all nodes indexed by their kind. */ export interface ASTKindToNode { - Name: NameNode; - Document: DocumentNode; - OperationDefinition: OperationDefinitionNode; - VariableDefinition: VariableDefinitionNode; - Variable: VariableNode; - SelectionSet: SelectionSetNode; - Field: FieldNode; - Argument: ArgumentNode; - FragmentSpread: FragmentSpreadNode; - InlineFragment: InlineFragmentNode; - FragmentDefinition: FragmentDefinitionNode; - IntValue: IntValueNode; - FloatValue: FloatValueNode; - StringValue: StringValueNode; - BooleanValue: BooleanValueNode; - NullValue: NullValueNode; - EnumValue: EnumValueNode; - ListValue: ListValueNode; - ObjectValue: ObjectValueNode; - ObjectField: ObjectFieldNode; - Directive: DirectiveNode; - NamedType: NamedTypeNode; - ListType: ListTypeNode; - NonNullType: NonNullTypeNode; - SchemaDefinition: SchemaDefinitionNode; - OperationTypeDefinition: OperationTypeDefinitionNode; - ScalarTypeDefinition: ScalarTypeDefinitionNode; - ObjectTypeDefinition: ObjectTypeDefinitionNode; - FieldDefinition: FieldDefinitionNode; - InputValueDefinition: InputValueDefinitionNode; - InterfaceTypeDefinition: InterfaceTypeDefinitionNode; - UnionTypeDefinition: UnionTypeDefinitionNode; - EnumTypeDefinition: EnumTypeDefinitionNode; - EnumValueDefinition: EnumValueDefinitionNode; - InputObjectTypeDefinition: InputObjectTypeDefinitionNode; - ScalarTypeExtension: ScalarTypeExtensionNode; - ObjectTypeExtension: ObjectTypeExtensionNode; - InterfaceTypeExtension: InterfaceTypeExtensionNode; - UnionTypeExtension: UnionTypeExtensionNode; - EnumTypeExtension: EnumTypeExtensionNode; - InputObjectTypeExtension: InputObjectTypeExtensionNode; - DirectiveDefinition: DirectiveDefinitionNode; + Name: NameNode; + Document: DocumentNode; + OperationDefinition: OperationDefinitionNode; + VariableDefinition: VariableDefinitionNode; + Variable: VariableNode; + SelectionSet: SelectionSetNode; + Field: FieldNode; + Argument: ArgumentNode; + FragmentSpread: FragmentSpreadNode; + InlineFragment: InlineFragmentNode; + FragmentDefinition: FragmentDefinitionNode; + IntValue: IntValueNode; + FloatValue: FloatValueNode; + StringValue: StringValueNode; + BooleanValue: BooleanValueNode; + NullValue: NullValueNode; + EnumValue: EnumValueNode; + ListValue: ListValueNode; + ObjectValue: ObjectValueNode; + ObjectField: ObjectFieldNode; + Directive: DirectiveNode; + NamedType: NamedTypeNode; + ListType: ListTypeNode; + NonNullType: NonNullTypeNode; + SchemaDefinition: SchemaDefinitionNode; + OperationTypeDefinition: OperationTypeDefinitionNode; + ScalarTypeDefinition: ScalarTypeDefinitionNode; + ObjectTypeDefinition: ObjectTypeDefinitionNode; + FieldDefinition: FieldDefinitionNode; + InputValueDefinition: InputValueDefinitionNode; + InterfaceTypeDefinition: InterfaceTypeDefinitionNode; + UnionTypeDefinition: UnionTypeDefinitionNode; + EnumTypeDefinition: EnumTypeDefinitionNode; + EnumValueDefinition: EnumValueDefinitionNode; + InputObjectTypeDefinition: InputObjectTypeDefinitionNode; + ScalarTypeExtension: ScalarTypeExtensionNode; + ObjectTypeExtension: ObjectTypeExtensionNode; + InterfaceTypeExtension: InterfaceTypeExtensionNode; + UnionTypeExtension: UnionTypeExtensionNode; + EnumTypeExtension: EnumTypeExtensionNode; + InputObjectTypeExtension: InputObjectTypeExtensionNode; + DirectiveDefinition: DirectiveDefinitionNode; } // Name export interface NameNode { - kind: 'Name'; - loc?: Location; - value: string; + kind: 'Name'; + loc?: Location; + value: string; } // Document export interface DocumentNode { - kind: 'Document'; - loc?: Location; - definitions: DefinitionNode[]; + kind: 'Document'; + loc?: Location; + definitions: DefinitionNode[]; } export type DefinitionNode = @@ -223,300 +223,294 @@ export type ExecutableDefinitionNode = | FragmentDefinitionNode; export interface OperationDefinitionNode { - kind: 'OperationDefinition'; - loc?: Location; - operation: OperationTypeNode; - name?: NameNode; - variableDefinitions?: VariableDefinitionNode[]; - directives?: DirectiveNode[]; - selectionSet: SelectionSetNode; + kind: 'OperationDefinition'; + loc?: Location; + operation: OperationTypeNode; + name?: NameNode; + variableDefinitions?: VariableDefinitionNode[]; + directives?: DirectiveNode[]; + selectionSet: SelectionSetNode; } // Note: subscription is an experimental non-spec addition. export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; export interface VariableDefinitionNode { - kind: 'VariableDefinition'; - loc?: Location; - variable: VariableNode; - type: TypeNode; - defaultValue?: ValueNode; + kind: 'VariableDefinition'; + loc?: Location; + variable: VariableNode; + type: TypeNode; + defaultValue?: ValueNode; } export interface VariableNode { - kind: 'Variable'; - loc?: Location; - name: NameNode; + kind: 'Variable'; + loc?: Location; + name: NameNode; } export interface SelectionSetNode { - kind: 'SelectionSet'; - loc?: Location; - selections: SelectionNode[]; + kind: 'SelectionSet'; + loc?: Location; + selections: SelectionNode[]; } -export type SelectionNode = - | FieldNode - | FragmentSpreadNode - | InlineFragmentNode; +export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode; export interface FieldNode { - kind: 'Field'; - loc?: Location; - alias?: NameNode; - name: NameNode; - arguments?: ArgumentNode[]; - directives?: DirectiveNode[]; - selectionSet?: SelectionSetNode; + kind: 'Field'; + loc?: Location; + alias?: NameNode; + name: NameNode; + arguments?: ArgumentNode[]; + directives?: DirectiveNode[]; + selectionSet?: SelectionSetNode; } export interface ArgumentNode { - kind: 'Argument'; - loc?: Location; - name: NameNode; - value: ValueNode; + kind: 'Argument'; + loc?: Location; + name: NameNode; + value: ValueNode; } // Fragments export interface FragmentSpreadNode { - kind: 'FragmentSpread'; - loc?: Location; - name: NameNode; - directives?: DirectiveNode[]; + kind: 'FragmentSpread'; + loc?: Location; + name: NameNode; + directives?: DirectiveNode[]; } export interface InlineFragmentNode { - kind: 'InlineFragment'; - loc?: Location; - typeCondition?: NamedTypeNode; - directives?: DirectiveNode[]; - selectionSet: SelectionSetNode; + kind: 'InlineFragment'; + loc?: Location; + typeCondition?: NamedTypeNode; + directives?: DirectiveNode[]; + selectionSet: SelectionSetNode; } export interface FragmentDefinitionNode { - kind: 'FragmentDefinition'; - loc?: Location; - name: NameNode; - // Note: fragment variable definitions are experimental and may be changed - // or removed in the future. - variableDefinitions?: VariableDefinitionNode[]; - typeCondition: NamedTypeNode; - directives?: DirectiveNode[]; - selectionSet: SelectionSetNode; + kind: 'FragmentDefinition'; + loc?: Location; + name: NameNode; + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + variableDefinitions?: VariableDefinitionNode[]; + typeCondition: NamedTypeNode; + directives?: DirectiveNode[]; + selectionSet: SelectionSetNode; } // Values export type ValueNode = - | VariableNode - | IntValueNode - | FloatValueNode - | StringValueNode - | BooleanValueNode - | NullValueNode - | EnumValueNode - | ListValueNode - | ObjectValueNode; + | VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode; export interface IntValueNode { - kind: 'IntValue'; - loc?: Location; - value: string; + kind: 'IntValue'; + loc?: Location; + value: string; } export interface FloatValueNode { - kind: 'FloatValue'; - loc?: Location; - value: string; + kind: 'FloatValue'; + loc?: Location; + value: string; } export interface StringValueNode { - kind: 'StringValue'; - loc?: Location; - value: string; + kind: 'StringValue'; + loc?: Location; + value: string; } export interface BooleanValueNode { - kind: 'BooleanValue'; - loc?: Location; - value: boolean; + kind: 'BooleanValue'; + loc?: Location; + value: boolean; } export interface NullValueNode { - kind: 'NullValue'; - loc?: Location; + kind: 'NullValue'; + loc?: Location; } export interface EnumValueNode { - kind: 'EnumValue'; - loc?: Location; - value: string; + kind: 'EnumValue'; + loc?: Location; + value: string; } export interface ListValueNode { - kind: 'ListValue'; - loc?: Location; - values: ValueNode[]; + kind: 'ListValue'; + loc?: Location; + values: ValueNode[]; } export interface ObjectValueNode { - kind: 'ObjectValue'; - loc?: Location; - fields: ObjectFieldNode[]; + kind: 'ObjectValue'; + loc?: Location; + fields: ObjectFieldNode[]; } export interface ObjectFieldNode { - kind: 'ObjectField'; - loc?: Location; - name: NameNode; - value: ValueNode; + kind: 'ObjectField'; + loc?: Location; + name: NameNode; + value: ValueNode; } // Directives export interface DirectiveNode { - kind: 'Directive'; - loc?: Location; - name: NameNode; - arguments?: ArgumentNode[]; + kind: 'Directive'; + loc?: Location; + name: NameNode; + arguments?: ArgumentNode[]; } // Type Reference -export type TypeNode = - | NamedTypeNode - | ListTypeNode - | NonNullTypeNode; +export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; export interface NamedTypeNode { - kind: 'NamedType'; - loc?: Location; - name: NameNode; + kind: 'NamedType'; + loc?: Location; + name: NameNode; } export interface ListTypeNode { - kind: 'ListType'; - loc?: Location; - type: TypeNode; + kind: 'ListType'; + loc?: Location; + type: TypeNode; } export interface NonNullTypeNode { - kind: 'NonNullType'; - loc?: Location; - type: NamedTypeNode | ListTypeNode; + kind: 'NonNullType'; + loc?: Location; + type: NamedTypeNode | ListTypeNode; } // Type System Definition export type TypeSystemDefinitionNode = - | SchemaDefinitionNode - | TypeDefinitionNode - | TypeExtensionNode - | DirectiveDefinitionNode; + | SchemaDefinitionNode + | TypeDefinitionNode + | TypeExtensionNode + | DirectiveDefinitionNode; export interface SchemaDefinitionNode { - kind: 'SchemaDefinition'; - loc?: Location; - directives: DirectiveNode[]; - operationTypes: OperationTypeDefinitionNode[]; + kind: 'SchemaDefinition'; + loc?: Location; + directives: DirectiveNode[]; + operationTypes: OperationTypeDefinitionNode[]; } export interface OperationTypeDefinitionNode { - kind: 'OperationTypeDefinition'; - loc?: Location; - operation: OperationTypeNode; - type: NamedTypeNode; + kind: 'OperationTypeDefinition'; + loc?: Location; + operation: OperationTypeNode; + type: NamedTypeNode; } export type TypeDefinitionNode = - | ScalarTypeDefinitionNode - | ObjectTypeDefinitionNode - | InterfaceTypeDefinitionNode - | UnionTypeDefinitionNode - | EnumTypeDefinitionNode - | InputObjectTypeDefinitionNode; + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode; export interface ScalarTypeDefinitionNode { - kind: 'ScalarTypeDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - directives?: DirectiveNode[]; + kind: 'ScalarTypeDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + directives?: DirectiveNode[]; } export interface ObjectTypeDefinitionNode { - kind: 'ObjectTypeDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - interfaces?: NamedTypeNode[]; - directives?: DirectiveNode[]; - fields: FieldDefinitionNode[]; + kind: 'ObjectTypeDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + interfaces?: NamedTypeNode[]; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } export interface FieldDefinitionNode { - kind: 'FieldDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - arguments: InputValueDefinitionNode[]; - type: TypeNode; - directives?: DirectiveNode[]; + kind: 'FieldDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + arguments: InputValueDefinitionNode[]; + type: TypeNode; + directives?: DirectiveNode[]; } export interface InputValueDefinitionNode { - kind: 'InputValueDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - type: TypeNode; - defaultValue?: ValueNode; - directives?: DirectiveNode[]; + kind: 'InputValueDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + type: TypeNode; + defaultValue?: ValueNode; + directives?: DirectiveNode[]; } export interface InterfaceTypeDefinitionNode { - kind: 'InterfaceTypeDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - directives?: DirectiveNode[]; - fields: FieldDefinitionNode[]; + kind: 'InterfaceTypeDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } export interface UnionTypeDefinitionNode { - kind: 'UnionTypeDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - directives?: DirectiveNode[]; - types: NamedTypeNode[]; + kind: 'UnionTypeDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + directives?: DirectiveNode[]; + types: NamedTypeNode[]; } export interface EnumTypeDefinitionNode { - kind: 'EnumTypeDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - directives?: DirectiveNode[]; - values: EnumValueDefinitionNode[]; + kind: 'EnumTypeDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + directives?: DirectiveNode[]; + values: EnumValueDefinitionNode[]; } export interface EnumValueDefinitionNode { - kind: 'EnumValueDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - directives?: DirectiveNode[]; + kind: 'EnumValueDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + directives?: DirectiveNode[]; } export interface InputObjectTypeDefinitionNode { - kind: 'InputObjectTypeDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - directives?: DirectiveNode[]; - fields: InputValueDefinitionNode[]; + kind: 'InputObjectTypeDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + directives?: DirectiveNode[]; + fields: InputValueDefinitionNode[]; } export type TypeExtensionNode = @@ -528,60 +522,60 @@ export type TypeExtensionNode = | InputObjectTypeExtensionNode; export type ScalarTypeExtensionNode = { - kind: 'ScalarTypeExtension', - loc?: Location, - name: NameNode, - directives?: DirectiveNode[], + kind: 'ScalarTypeExtension'; + loc?: Location; + name: NameNode; + directives?: DirectiveNode[]; }; export type ObjectTypeExtensionNode = { - kind: 'ObjectTypeExtension', - loc?: Location, - name: NameNode, - interfaces?: NamedTypeNode[], - directives?: DirectiveNode[], - fields?: FieldDefinitionNode[], + kind: 'ObjectTypeExtension'; + loc?: Location; + name: NameNode; + interfaces?: NamedTypeNode[]; + directives?: DirectiveNode[]; + fields?: FieldDefinitionNode[]; }; export type InterfaceTypeExtensionNode = { - kind: 'InterfaceTypeExtension', - loc?: Location, - name: NameNode, - directives?: DirectiveNode[], - fields?: FieldDefinitionNode[], + kind: 'InterfaceTypeExtension'; + loc?: Location; + name: NameNode; + directives?: DirectiveNode[]; + fields?: FieldDefinitionNode[]; }; export type UnionTypeExtensionNode = { - kind: 'UnionTypeExtension', - loc?: Location, - name: NameNode, - directives?: DirectiveNode[], - types?: NamedTypeNode[], + kind: 'UnionTypeExtension'; + loc?: Location; + name: NameNode; + directives?: DirectiveNode[]; + types?: NamedTypeNode[]; }; export type EnumTypeExtensionNode = { - kind: 'EnumTypeExtension', - loc?: Location, - name: NameNode, - directives?: DirectiveNode[], - values?: EnumValueDefinitionNode[], + kind: 'EnumTypeExtension'; + loc?: Location; + name: NameNode; + directives?: DirectiveNode[]; + values?: EnumValueDefinitionNode[]; }; export type InputObjectTypeExtensionNode = { - kind: 'InputObjectTypeExtension', - loc?: Location, - name: NameNode, - directives?: DirectiveNode[], - fields?: InputValueDefinitionNode[], + kind: 'InputObjectTypeExtension'; + loc?: Location; + name: NameNode; + directives?: DirectiveNode[]; + fields?: InputValueDefinitionNode[]; }; // Directive Definitions export interface DirectiveDefinitionNode { - kind: 'DirectiveDefinition'; - loc?: Location; - description?: StringValueNode; - name: NameNode; - arguments?: InputValueDefinitionNode[]; - locations: NameNode[]; + kind: 'DirectiveDefinition'; + loc?: Location; + description?: StringValueNode; + name: NameNode; + arguments?: InputValueDefinitionNode[]; + locations: NameNode[]; } diff --git a/types/graphql/language/index.d.ts b/types/graphql/language/index.d.ts index bc00bb243d..c8fe4b13ec 100644 --- a/types/graphql/language/index.d.ts +++ b/types/graphql/language/index.d.ts @@ -7,9 +7,9 @@ export { parse, parseValue, parseType, ParseOptions } from './parser'; export { print } from './printer'; export { Source } from './source'; export { - visit, - visitInParallel, - visitWithTypeInfo, - getVisitFn, - BREAK + visit, + visitInParallel, + visitWithTypeInfo, + getVisitFn, + BREAK, } from './visitor'; diff --git a/types/graphql/language/lexer.d.ts b/types/graphql/language/lexer.d.ts index 4a55f03dc2..0db85434e2 100644 --- a/types/graphql/language/lexer.d.ts +++ b/types/graphql/language/lexer.d.ts @@ -11,41 +11,41 @@ import { syntaxError } from '../error'; * whenever called. */ export function createLexer( - source: Source, - options: TOptions + source: Source, + options: TOptions, ): Lexer; /** * The return type of createLexer. */ export interface Lexer { - source: Source; - options: TOptions; + source: Source; + options: TOptions; - /** - * The previously focused non-ignored token. - */ - lastToken: Token; + /** + * The previously focused non-ignored token. + */ + lastToken: Token; - /** - * The currently focused non-ignored token. - */ - token: Token; + /** + * The currently focused non-ignored token. + */ + token: Token; - /** - * The (1-indexed) line containing the current token. - */ - line: number; + /** + * The (1-indexed) line containing the current token. + */ + line: number; - /** - * The character offset at which the current line begins. - */ - lineStart: number; + /** + * The character offset at which the current line begins. + */ + lineStart: number; - /** - * Advances the token stream to the next non-ignored token. - */ - advance(): Token; + /** + * Advances the token stream to the next non-ignored token. + */ + advance(): Token; } /** @@ -53,26 +53,26 @@ export interface Lexer { * lexer emits. */ export const TokenKind: { - SOF: '' - EOF: '' - BANG: '!' - DOLLAR: '$' - PAREN_L: '(' - PAREN_R: ')' - SPREAD: '...' - COLON: ':' - EQUALS: '=' - AT: '@' - BRACKET_L: '[' - BRACKET_R: ']' - BRACE_L: '{' - PIPE: '|' - BRACE_R: '}' - NAME: 'Name' - INT: 'Int' - FLOAT: 'Float' - STRING: 'String' - COMMENT: 'Comment' + SOF: ''; + EOF: ''; + BANG: '!'; + DOLLAR: '$'; + PAREN_L: '('; + PAREN_R: ')'; + SPREAD: '...'; + COLON: ':'; + EQUALS: '='; + AT: '@'; + BRACKET_L: '['; + BRACKET_R: ']'; + BRACE_L: '{'; + PIPE: '|'; + BRACE_R: '}'; + NAME: 'Name'; + INT: 'Int'; + FLOAT: 'Float'; + STRING: 'String'; + COMMENT: 'Comment'; }; /** diff --git a/types/graphql/language/location.d.ts b/types/graphql/language/location.d.ts index 4d7a13e314..cb9744e0d5 100644 --- a/types/graphql/language/location.d.ts +++ b/types/graphql/language/location.d.ts @@ -1,8 +1,8 @@ -import { Source } from "./source"; +import { Source } from './source'; export interface SourceLocation { - line: number; - column: number; + line: number; + column: number; } export function getLocation(source: Source, position: number): SourceLocation; diff --git a/types/graphql/language/parser.d.ts b/types/graphql/language/parser.d.ts index 5aa195ddd4..a0b8a0c7a4 100644 --- a/types/graphql/language/parser.d.ts +++ b/types/graphql/language/parser.d.ts @@ -1,17 +1,17 @@ -import { NamedTypeNode, TypeNode, ValueNode, DocumentNode } from "./ast"; -import { Source } from "./source"; -import { Lexer } from "./lexer"; +import { NamedTypeNode, TypeNode, ValueNode, DocumentNode } from './ast'; +import { Source } from './source'; +import { Lexer } from './lexer'; /** * Configuration options to control parser behavior */ export interface ParseOptions { - /** - * By default, the parser creates AST nodes that know the location - * in the source that they correspond to. This configuration flag - * disables that behavior for performance or testing. - */ - noLocation?: boolean; + /** + * By default, the parser creates AST nodes that know the location + * in the source that they correspond to. This configuration flag + * disables that behavior for performance or testing. + */ + noLocation?: boolean; } /** @@ -19,8 +19,8 @@ export interface ParseOptions { * Throws GraphQLError if a syntax error is encountered. */ export function parse( - source: string | Source, - options?: ParseOptions + source: string | Source, + options?: ParseOptions, ): DocumentNode; /** @@ -31,8 +31,8 @@ export function parse( * in isolation of complete GraphQL documents. */ export function parseValue( - source: Source | string, - options?: ParseOptions + source: Source | string, + options?: ParseOptions, ): ValueNode; export function parseConstValue(lexer: Lexer): ValueNode; diff --git a/types/graphql/language/source.d.ts b/types/graphql/language/source.d.ts index 80e68f5557..236028b7df 100644 --- a/types/graphql/language/source.d.ts +++ b/types/graphql/language/source.d.ts @@ -1,5 +1,5 @@ export class Source { - body: string; - name: string; - constructor(body: string, name?: string); + body: string; + name: string; + constructor(body: string, name?: string); } diff --git a/types/graphql/language/visitor.d.ts b/types/graphql/language/visitor.d.ts index dc8bcc2692..e7e9d67da0 100644 --- a/types/graphql/language/visitor.d.ts +++ b/types/graphql/language/visitor.d.ts @@ -1,43 +1,43 @@ export const QueryDocumentKeys: { - Name: any[]; - Document: string[]; - OperationDefinition: string[]; - VariableDefinition: string[]; - Variable: string[]; - SelectionSet: string[]; - Field: string[]; - Argument: string[]; + Name: any[]; + Document: string[]; + OperationDefinition: string[]; + VariableDefinition: string[]; + Variable: string[]; + SelectionSet: string[]; + Field: string[]; + Argument: string[]; - FragmentSpread: string[]; - InlineFragment: string[]; - FragmentDefinition: string[]; + FragmentSpread: string[]; + InlineFragment: string[]; + FragmentDefinition: string[]; - IntValue: number[]; - FloatValue: number[]; - StringValue: string[]; - BooleanValue: boolean[]; - NullValue: null[], - EnumValue: any[]; - ListValue: string[]; - ObjectValue: string[]; - ObjectField: string[]; + IntValue: number[]; + FloatValue: number[]; + StringValue: string[]; + BooleanValue: boolean[]; + NullValue: null[]; + EnumValue: any[]; + ListValue: string[]; + ObjectValue: string[]; + ObjectField: string[]; - Directive: string[]; + Directive: string[]; - NamedType: string[]; - ListType: string[]; - NonNullType: string[]; + NamedType: string[]; + ListType: string[]; + NonNullType: string[]; - ObjectTypeDefinition: string[]; - FieldDefinition: string[]; - InputValueDefinition: string[]; - InterfaceTypeDefinition: string[]; - UnionTypeDefinition: string[]; - ScalarTypeDefinition: string[]; - EnumTypeDefinition: string[]; - EnumValueDefinition: string[]; - InputObjectTypeDefinition: string[]; - TypeExtensionDefinition: string[]; + ObjectTypeDefinition: string[]; + FieldDefinition: string[]; + InputValueDefinition: string[]; + InterfaceTypeDefinition: string[]; + UnionTypeDefinition: string[]; + ScalarTypeDefinition: string[]; + EnumTypeDefinition: string[]; + EnumValueDefinition: string[]; + InputObjectTypeDefinition: string[]; + TypeExtensionDefinition: string[]; }; export const BREAK: any; diff --git a/types/graphql/subscription/subscribe.d.ts b/types/graphql/subscription/subscribe.d.ts index 30efc010ec..dc2c096b86 100644 --- a/types/graphql/subscription/subscribe.d.ts +++ b/types/graphql/subscription/subscribe.d.ts @@ -4,26 +4,26 @@ import { GraphQLFieldResolver } from '../type/definition'; import { ExecutionResult } from '../execution/execute'; export function subscribe( - schema: GraphQLSchema, - document: DocumentNode, - rootValue?: any, - contextValue?: any, - variableValues?: { - [key: string]: any; - }, - operationName?: string, - fieldResolver?: GraphQLFieldResolver, - subscribeFieldResolver?: GraphQLFieldResolver + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: { + [key: string]: any; + }, + operationName?: string, + fieldResolver?: GraphQLFieldResolver, + subscribeFieldResolver?: GraphQLFieldResolver, ): Promise | ExecutionResult>; export function createSourceEventStream( - schema: GraphQLSchema, - document: DocumentNode, - rootValue?: any, - contextValue?: any, - variableValues?: { - [key: string]: any; - }, - operationName?: string, - fieldResolver?: GraphQLFieldResolver + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: { + [key: string]: any; + }, + operationName?: string, + fieldResolver?: GraphQLFieldResolver, ): Promise>; diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index ed39a51db6..098f7376ef 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -1,18 +1,18 @@ import { - ScalarTypeDefinitionNode, - ObjectTypeDefinitionNode, - FieldDefinitionNode, - InputValueDefinitionNode, - InterfaceTypeDefinitionNode, - UnionTypeDefinitionNode, - EnumTypeDefinitionNode, - EnumValueDefinitionNode, - InputObjectTypeDefinitionNode, - TypeExtensionNode, - OperationDefinitionNode, - FieldNode, - FragmentDefinitionNode, - ValueNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + TypeExtensionNode, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, } from '../language/ast'; import { GraphQLSchema } from './schema'; @@ -20,14 +20,14 @@ import { GraphQLSchema } from './schema'; * These are all of the possible kinds of types. */ export type GraphQLType = - | GraphQLScalarType - | GraphQLObjectType - | GraphQLInterfaceType - | GraphQLUnionType - | GraphQLEnumType - | GraphQLInputObjectType - | GraphQLList - | GraphQLNonNull; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull; export function isType(type: any): type is GraphQLType; @@ -37,15 +37,16 @@ export function assertType(type: any): GraphQLType; * These types may be used as input types for arguments and directives. */ export type GraphQLInputType = - | GraphQLScalarType - | GraphQLEnumType - | GraphQLInputObjectType - | GraphQLList - | GraphQLNonNull< - | GraphQLScalarType - | GraphQLEnumType - | GraphQLInputObjectType - | GraphQLList>; + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + >; export function isInputType(type: GraphQLType): type is GraphQLInputType; @@ -55,19 +56,20 @@ export function assertInputType(type: GraphQLType): GraphQLInputType; * These types may be used as output types as the result of fields. */ export type GraphQLOutputType = - | GraphQLScalarType - | GraphQLObjectType - | GraphQLInterfaceType - | GraphQLUnionType - | GraphQLEnumType - | GraphQLList - | GraphQLNonNull< - | GraphQLScalarType - | GraphQLObjectType - | GraphQLInterfaceType - | GraphQLUnionType - | GraphQLEnumType - | GraphQLList>; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + >; export function isOutputType(type: GraphQLType): type is GraphQLOutputType; @@ -76,9 +78,7 @@ export function assertOutputType(type: GraphQLType): GraphQLOutputType; /** * These types may describe types which may be leaf values. */ -export type GraphQLLeafType = - | GraphQLScalarType - | GraphQLEnumType; +export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; export function isLeafType(type: GraphQLType): type is GraphQLLeafType; @@ -88,20 +88,20 @@ export function assertLeafType(type: GraphQLType): GraphQLLeafType; * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = - | GraphQLObjectType - | GraphQLInterfaceType - | GraphQLUnionType; + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; -export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; +export function isCompositeType( + type: GraphQLType, +): type is GraphQLCompositeType; export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; /** * These types may describe the parent context of a selection set. */ -export type GraphQLAbstractType = - | GraphQLInterfaceType - | GraphQLUnionType; +export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; @@ -111,28 +111,28 @@ export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; * These types can all accept null as a value. */ export type GraphQLNullableType = - | GraphQLScalarType - | GraphQLObjectType - | GraphQLInterfaceType - | GraphQLUnionType - | GraphQLEnumType - | GraphQLInputObjectType - | GraphQLList; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; export function getNullableType( - type: T -): (T & GraphQLNullableType); + type: T, +): T & GraphQLNullableType; /** * These named types do not include modifiers like List or NonNull. */ export type GraphQLNamedType = - | GraphQLScalarType - | GraphQLObjectType - | GraphQLInterfaceType - | GraphQLUnionType - | GraphQLEnumType - | GraphQLInputObjectType; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType; export function isNamedType(type: GraphQLType): boolean; @@ -164,30 +164,30 @@ export type Thunk = (() => T) | T; * */ export class GraphQLScalarType { - name: string; - description: string; - astNode?: ScalarTypeDefinitionNode; - constructor(config: GraphQLScalarTypeConfig); + name: string; + description: string; + astNode?: ScalarTypeDefinitionNode; + constructor(config: GraphQLScalarTypeConfig); - // Serializes an internal value to include in a response. - serialize(value: any): any; + // Serializes an internal value to include in a response. + serialize(value: any): any; - // Parses an externally provided value to use as an input. - parseValue(value: any): any; + // Parses an externally provided value to use as an input. + parseValue(value: any): any; - // Parses an externally provided literal value to use as an input. - parseLiteral(valueNode: ValueNode): any; + // Parses an externally provided literal value to use as an input. + parseLiteral(valueNode: ValueNode): any; - toString(): string; + toString(): string; } export interface GraphQLScalarTypeConfig { - name: string; - description?: string; - astNode?: ScalarTypeDefinitionNode; - serialize(value: any): TExternal | null | undefined; - parseValue?(value: any): TInternal | null | undefined; - parseLiteral?(valueNode: ValueNode): TInternal | null | undefined; + name: string; + description?: string; + astNode?: ScalarTypeDefinitionNode; + serialize(value: any): TExternal | null | undefined; + parseValue?(value: any): TInternal | null | undefined; + parseLiteral?(valueNode: ValueNode): TInternal | null | undefined; } /** @@ -228,109 +228,123 @@ export interface GraphQLScalarTypeConfig { * */ export class GraphQLObjectType { - name: string; - description: string; - astNode?: ObjectTypeDefinitionNode; - extensionASTNodes: Array; - isTypeOf: GraphQLIsTypeOfFn; + name: string; + description: string; + astNode?: ObjectTypeDefinitionNode; + extensionASTNodes: Array; + isTypeOf: GraphQLIsTypeOfFn; - constructor(config: GraphQLObjectTypeConfig); - getFields(): GraphQLFieldMap; - getInterfaces(): GraphQLInterfaceType[]; - toString(): string; + constructor(config: GraphQLObjectTypeConfig); + getFields(): GraphQLFieldMap; + getInterfaces(): GraphQLInterfaceType[]; + toString(): string; } export interface GraphQLObjectTypeConfig { - name: string; - interfaces?: Thunk; - fields: Thunk>; - isTypeOf?: GraphQLIsTypeOfFn; - description?: string; - astNode?: ObjectTypeDefinitionNode; - extensionASTNodes?: Array; + name: string; + interfaces?: Thunk; + fields: Thunk>; + isTypeOf?: GraphQLIsTypeOfFn; + description?: string; + astNode?: ObjectTypeDefinitionNode; + extensionASTNodes?: Array; } export type GraphQLTypeResolver = ( - value: TSource, - context: TContext, - info: GraphQLResolveInfo + value: TSource, + context: TContext, + info: GraphQLResolveInfo, ) => GraphQLObjectType | string | Promise; export type GraphQLIsTypeOfFn = ( - source: TSource, - context: TContext, - info: GraphQLResolveInfo + source: TSource, + context: TContext, + info: GraphQLResolveInfo, ) => boolean | Promise; -export type GraphQLFieldResolver = ( - source: TSource, - args: TArgs, - context: TContext, - info: GraphQLResolveInfo +export type GraphQLFieldResolver< + TSource, + TContext, + TArgs = { [argName: string]: any } +> = ( + source: TSource, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo, ) => any; export interface GraphQLResolveInfo { - fieldName: string; - fieldNodes: FieldNode[]; - returnType: GraphQLOutputType; - parentType: GraphQLCompositeType; - path: ResponsePath; - schema: GraphQLSchema; - fragments: { [fragmentName: string]: FragmentDefinitionNode }; - rootValue: any; - operation: OperationDefinitionNode; - variableValues: { [variableName: string]: any }; + fieldName: string; + fieldNodes: FieldNode[]; + returnType: GraphQLOutputType; + parentType: GraphQLCompositeType; + path: ResponsePath; + schema: GraphQLSchema; + fragments: { [fragmentName: string]: FragmentDefinitionNode }; + rootValue: any; + operation: OperationDefinitionNode; + variableValues: { [variableName: string]: any }; } -export type ResponsePath = { prev: ResponsePath, key: string | number } | undefined; +export type ResponsePath = + | { prev: ResponsePath; key: string | number } + | undefined; -export interface GraphQLFieldConfig { - type: GraphQLOutputType; - args?: GraphQLFieldConfigArgumentMap; - resolve?: GraphQLFieldResolver; - subscribe?: GraphQLFieldResolver; - deprecationReason?: string; - description?: string; - astNode?: FieldDefinitionNode; +export interface GraphQLFieldConfig< + TSource, + TContext, + TArgs = { [argName: string]: any } +> { + type: GraphQLOutputType; + args?: GraphQLFieldConfigArgumentMap; + resolve?: GraphQLFieldResolver; + subscribe?: GraphQLFieldResolver; + deprecationReason?: string; + description?: string; + astNode?: FieldDefinitionNode; } export interface GraphQLFieldConfigArgumentMap { - [argName: string]: GraphQLArgumentConfig; + [argName: string]: GraphQLArgumentConfig; } export interface GraphQLArgumentConfig { - type: GraphQLInputType; - defaultValue?: any; - description?: string; - astNode?: InputValueDefinitionNode; + type: GraphQLInputType; + defaultValue?: any; + description?: string; + astNode?: InputValueDefinitionNode; } export interface GraphQLFieldConfigMap { - [fieldName: string]: GraphQLFieldConfig; + [fieldName: string]: GraphQLFieldConfig; } -export interface GraphQLField { - name: string; - description: string; - type: GraphQLOutputType; - args: GraphQLArgument[]; - resolve?: GraphQLFieldResolver; - subscribe?: GraphQLFieldResolver; - isDeprecated?: boolean; - deprecationReason?: string; - astNode?: FieldDefinitionNode; +export interface GraphQLField< + TSource, + TContext, + TArgs = { [argName: string]: any } +> { + name: string; + description: string; + type: GraphQLOutputType; + args: GraphQLArgument[]; + resolve?: GraphQLFieldResolver; + subscribe?: GraphQLFieldResolver; + isDeprecated?: boolean; + deprecationReason?: string; + astNode?: FieldDefinitionNode; } export interface GraphQLArgument { - name: string; - type: GraphQLInputType; - defaultValue?: any; - description?: string; - astNode?: InputValueDefinitionNode; + name: string; + type: GraphQLInputType; + defaultValue?: any; + description?: string; + astNode?: InputValueDefinitionNode; } export interface GraphQLFieldMap { - [fieldName: string]: GraphQLField; + [fieldName: string]: GraphQLField; } /** @@ -352,29 +366,29 @@ export interface GraphQLFieldMap { * */ export class GraphQLInterfaceType { - name: string; - description: string; - astNode?: InterfaceTypeDefinitionNode; - resolveType: GraphQLTypeResolver; + name: string; + description: string; + astNode?: InterfaceTypeDefinitionNode; + resolveType: GraphQLTypeResolver; - constructor(config: GraphQLInterfaceTypeConfig); + constructor(config: GraphQLInterfaceTypeConfig); - getFields(): GraphQLFieldMap; + getFields(): GraphQLFieldMap; - toString(): string; + toString(): string; } export interface GraphQLInterfaceTypeConfig { - name: string; - fields: Thunk>; - /** - * Optionally provide a custom type resolver function. If one is not provided, - * the default implementation will call `isTypeOf` on each implementing - * Object type. - */ - resolveType?: GraphQLTypeResolver; - description?: string; - astNode?: InterfaceTypeDefinitionNode; + name: string; + fields: Thunk>; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: GraphQLTypeResolver; + description?: string; + astNode?: InterfaceTypeDefinitionNode; } /** @@ -401,29 +415,29 @@ export interface GraphQLInterfaceTypeConfig { * */ export class GraphQLUnionType { - name: string; - description: string; - astNode?: UnionTypeDefinitionNode; - resolveType: GraphQLTypeResolver; + name: string; + description: string; + astNode?: UnionTypeDefinitionNode; + resolveType: GraphQLTypeResolver; - constructor(config: GraphQLUnionTypeConfig); + constructor(config: GraphQLUnionTypeConfig); - getTypes(): GraphQLObjectType[]; + getTypes(): GraphQLObjectType[]; - toString(): string; + toString(): string; } export interface GraphQLUnionTypeConfig { - name: string; - types: Thunk; - /** - * Optionally provide a custom type resolver function. If one is not provided, - * the default implementation will call `isTypeOf` on each implementing - * Object type. - */ - resolveType?: GraphQLTypeResolver; - description?: string; - astNode?: UnionTypeDefinitionNode; + name: string; + types: Thunk; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: GraphQLTypeResolver; + description?: string; + astNode?: UnionTypeDefinitionNode; } /** @@ -448,45 +462,45 @@ export interface GraphQLUnionTypeConfig { * will be used as its internal value. */ export class GraphQLEnumType { - name: string; - description: string; - astNode?: EnumTypeDefinitionNode; + name: string; + description: string; + astNode?: EnumTypeDefinitionNode; - constructor(config: GraphQLEnumTypeConfig); - getValues(): GraphQLEnumValue[]; - getValue(name: string): GraphQLEnumValue; - isValidValue(value: any): boolean; - serialize(value: any): string; - parseValue(value: any): any; - parseLiteral(valueNode: ValueNode): any; - toString(): string; + constructor(config: GraphQLEnumTypeConfig); + getValues(): GraphQLEnumValue[]; + getValue(name: string): GraphQLEnumValue; + isValidValue(value: any): boolean; + serialize(value: any): string; + parseValue(value: any): any; + parseLiteral(valueNode: ValueNode): any; + toString(): string; } export interface GraphQLEnumTypeConfig { - name: string; - values: GraphQLEnumValueConfigMap; - description?: string; - astNode?: EnumTypeDefinitionNode; + name: string; + values: GraphQLEnumValueConfigMap; + description?: string; + astNode?: EnumTypeDefinitionNode; } export interface GraphQLEnumValueConfigMap { - [valueName: string]: GraphQLEnumValueConfig; + [valueName: string]: GraphQLEnumValueConfig; } export interface GraphQLEnumValueConfig { - value?: any; - deprecationReason?: string; - description?: string; - astNode?: EnumValueDefinitionNode; + value?: any; + deprecationReason?: string; + description?: string; + astNode?: EnumValueDefinitionNode; } export interface GraphQLEnumValue { - name: string; - description: string; - isDeprecated?: boolean; - deprecationReason: string; - astNode?: EnumValueDefinitionNode; - value: any; + name: string; + description: string; + isDeprecated?: boolean; + deprecationReason: string; + astNode?: EnumValueDefinitionNode; + value: any; } /** @@ -510,42 +524,42 @@ export interface GraphQLEnumValue { * */ export class GraphQLInputObjectType { - name: string; - description: string; - astNode?: InputObjectTypeDefinitionNode; - constructor(config: GraphQLInputObjectTypeConfig); - getFields(): GraphQLInputFieldMap; - toString(): string; + name: string; + description: string; + astNode?: InputObjectTypeDefinitionNode; + constructor(config: GraphQLInputObjectTypeConfig); + getFields(): GraphQLInputFieldMap; + toString(): string; } export interface GraphQLInputObjectTypeConfig { - name: string; - fields: Thunk; - description?: string; - astNode?: InputObjectTypeDefinitionNode; + name: string; + fields: Thunk; + description?: string; + astNode?: InputObjectTypeDefinitionNode; } export interface GraphQLInputFieldConfig { - type: GraphQLInputType; - defaultValue?: any; - description?: string; - astNode?: InputValueDefinitionNode; + type: GraphQLInputType; + defaultValue?: any; + description?: string; + astNode?: InputValueDefinitionNode; } export interface GraphQLInputFieldConfigMap { - [fieldName: string]: GraphQLInputFieldConfig; + [fieldName: string]: GraphQLInputFieldConfig; } export interface GraphQLInputField { - name: string; - type: GraphQLInputType; - defaultValue?: any; - description?: string; - astNode?: InputValueDefinitionNode; + name: string; + type: GraphQLInputType; + defaultValue?: any; + description?: string; + astNode?: InputValueDefinitionNode; } export interface GraphQLInputFieldMap { - [fieldName: string]: GraphQLInputField; + [fieldName: string]: GraphQLInputField; } /** @@ -567,9 +581,9 @@ export interface GraphQLInputFieldMap { * */ export class GraphQLList { - ofType: T; - constructor(type: T); - toString(): string; + ofType: T; + constructor(type: T); + toString(): string; } /** @@ -593,9 +607,9 @@ export class GraphQLList { * Note: the enforcement of non-nullability occurs within the executor. */ export class GraphQLNonNull { - ofType: T; + ofType: T; - constructor(type: T); + constructor(type: T); - toString(): string; + toString(): string; } diff --git a/types/graphql/type/directives.d.ts b/types/graphql/type/directives.d.ts index 81befa9eba..b6962bc4ae 100644 --- a/types/graphql/type/directives.d.ts +++ b/types/graphql/type/directives.d.ts @@ -1,30 +1,27 @@ -import { - GraphQLFieldConfigArgumentMap, - GraphQLArgument -} from './definition'; +import { GraphQLFieldConfigArgumentMap, GraphQLArgument } from './definition'; import { DirectiveDefinitionNode } from '../language/ast'; export const DirectiveLocation: { - // Operations - QUERY: 'QUERY', - MUTATION: 'MUTATION', - SUBSCRIPTION: 'SUBSCRIPTION', - FIELD: 'FIELD', - FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', - FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', - INLINE_FRAGMENT: 'INLINE_FRAGMENT', - // Schema Definitions - SCHEMA: 'SCHEMA', - SCALAR: 'SCALAR', - OBJECT: 'OBJECT', - FIELD_DEFINITION: 'FIELD_DEFINITION', - ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', - INTERFACE: 'INTERFACE', - UNION: 'UNION', - ENUM: 'ENUM', - ENUM_VALUE: 'ENUM_VALUE', - INPUT_OBJECT: 'INPUT_OBJECT', - INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', + // Operations + QUERY: 'QUERY'; + MUTATION: 'MUTATION'; + SUBSCRIPTION: 'SUBSCRIPTION'; + FIELD: 'FIELD'; + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION'; + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD'; + INLINE_FRAGMENT: 'INLINE_FRAGMENT'; + // Schema Definitions + SCHEMA: 'SCHEMA'; + SCALAR: 'SCALAR'; + OBJECT: 'OBJECT'; + FIELD_DEFINITION: 'FIELD_DEFINITION'; + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION'; + INTERFACE: 'INTERFACE'; + UNION: 'UNION'; + ENUM: 'ENUM'; + ENUM_VALUE: 'ENUM_VALUE'; + INPUT_OBJECT: 'INPUT_OBJECT'; + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'; }; export type DirectiveLocationEnum = keyof typeof DirectiveLocation; @@ -34,21 +31,21 @@ export type DirectiveLocationEnum = keyof typeof DirectiveLocation; * behavior. Type system creators will usually not create these directly. */ export class GraphQLDirective { - name: string; - description?: string; - locations: DirectiveLocationEnum[]; - args: GraphQLArgument[]; - astNode?: DirectiveDefinitionNode; + name: string; + description?: string; + locations: DirectiveLocationEnum[]; + args: GraphQLArgument[]; + astNode?: DirectiveDefinitionNode; - constructor(config: GraphQLDirectiveConfig); + constructor(config: GraphQLDirectiveConfig); } export interface GraphQLDirectiveConfig { - name: string; - description?: string; - locations: DirectiveLocationEnum[]; - args?: GraphQLFieldConfigArgumentMap; - astNode?: DirectiveDefinitionNode; + name: string; + description?: string; + locations: DirectiveLocationEnum[]; + args?: GraphQLFieldConfigArgumentMap; + astNode?: DirectiveDefinitionNode; } /** diff --git a/types/graphql/type/index.d.ts b/types/graphql/type/index.d.ts index ae7a81e621..5fdfb1190a 100644 --- a/types/graphql/type/index.d.ts +++ b/types/graphql/type/index.d.ts @@ -4,49 +4,44 @@ export { GraphQLSchema } from './schema'; export * from './definition'; export { - // "Enum" of Directive Locations - DirectiveLocation, - - // Directives Definition - GraphQLDirective, - - // Built-in Directives defined by the Spec - specifiedDirectives, - GraphQLIncludeDirective, - GraphQLSkipDirective, - GraphQLDeprecatedDirective, - - // Constant Deprecation Reason - DEFAULT_DEPRECATION_REASON, + // "Enum" of Directive Locations + DirectiveLocation, + // Directives Definition + GraphQLDirective, + // Built-in Directives defined by the Spec + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, } from './directives'; // Common built-in scalar instances. export { - GraphQLInt, - GraphQLFloat, - GraphQLString, - GraphQLBoolean, - GraphQLID, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, } from './scalars'; export { - // "Enum" of Type Kinds - TypeKind, - - // GraphQL Types for introspection. - __Schema, - __Directive, - __DirectiveLocation, - __Type, - __Field, - __InputValue, - __EnumValue, - __TypeKind, - - // Meta-field definitions. - SchemaMetaFieldDef, - TypeMetaFieldDef, - TypeNameMetaFieldDef, + // "Enum" of Type Kinds + TypeKind, + // GraphQL Types for introspection. + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, } from './introspection'; export { DirectiveLocationEnum } from './directives'; diff --git a/types/graphql/type/introspection.d.ts b/types/graphql/type/introspection.d.ts index 989e34a882..48ac468ed0 100644 --- a/types/graphql/type/introspection.d.ts +++ b/types/graphql/type/introspection.d.ts @@ -1,12 +1,12 @@ import { - GraphQLScalarType, - GraphQLObjectType, - GraphQLInterfaceType, - GraphQLUnionType, - GraphQLEnumType, - GraphQLInputObjectType, - GraphQLList, - GraphQLNonNull, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, } from './definition'; import { GraphQLField } from './definition'; @@ -19,14 +19,14 @@ export const __InputValue: GraphQLObjectType; export const __EnumValue: GraphQLObjectType; export const TypeKind: { - SCALAR: 'SCALAR', - OBJECT: 'OBJECT', - INTERFACE: 'INTERFACE', - UNION: 'UNION', - ENUM: 'ENUM', - INPUT_OBJECT: 'INPUT_OBJECT', - LIST: 'LIST', - NON_NULL: 'NON_NULL', + SCALAR: 'SCALAR'; + OBJECT: 'OBJECT'; + INTERFACE: 'INTERFACE'; + UNION: 'UNION'; + ENUM: 'ENUM'; + INPUT_OBJECT: 'INPUT_OBJECT'; + LIST: 'LIST'; + NON_NULL: 'NON_NULL'; }; export const __TypeKind: GraphQLEnumType; diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index a7f4d394f4..3263274dd9 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -1,17 +1,11 @@ +import { GraphQLObjectType } from './definition'; import { - GraphQLObjectType, + GraphQLType, + GraphQLNamedType, + GraphQLAbstractType, } from './definition'; -import { - GraphQLType, - GraphQLNamedType, - GraphQLAbstractType -} from './definition'; -import { - SchemaDefinitionNode -} from '../language/ast'; -import { - GraphQLDirective, -} from './directives'; +import { SchemaDefinitionNode } from '../language/ast'; +import { GraphQLDirective } from './directives'; /** * Schema Definition @@ -40,38 +34,38 @@ import { * */ export class GraphQLSchema { - astNode?: SchemaDefinitionNode; - // private _queryType: GraphQLObjectType; - // private _mutationType: GraphQLObjectType; - // private _subscriptionType: GraphQLObjectType; - // private _directives: Array; - // private _typeMap: TypeMap; - // private _implementations: { [interfaceName: string]: Array }; - // private _possibleTypeMap: { [abstractName: string]: { [possibleName: string]: boolean } }; + astNode?: SchemaDefinitionNode; + // private _queryType: GraphQLObjectType; + // private _mutationType: GraphQLObjectType; + // private _subscriptionType: GraphQLObjectType; + // private _directives: Array; + // private _typeMap: TypeMap; + // private _implementations: { [interfaceName: string]: Array }; + // private _possibleTypeMap: { [abstractName: string]: { [possibleName: string]: boolean } }; - constructor(config: GraphQLSchemaConfig) + constructor(config: GraphQLSchemaConfig); - getQueryType(): GraphQLObjectType; - getMutationType(): GraphQLObjectType|null|undefined; - getSubscriptionType(): GraphQLObjectType|null|undefined; - getTypeMap(): { [typeName: string]: GraphQLNamedType }; - getType(name: string): GraphQLNamedType; - getPossibleTypes(abstractType: GraphQLAbstractType): GraphQLObjectType[]; + getQueryType(): GraphQLObjectType; + getMutationType(): GraphQLObjectType | null | undefined; + getSubscriptionType(): GraphQLObjectType | null | undefined; + getTypeMap(): { [typeName: string]: GraphQLNamedType }; + getType(name: string): GraphQLNamedType; + getPossibleTypes(abstractType: GraphQLAbstractType): GraphQLObjectType[]; - isPossibleType( - abstractType: GraphQLAbstractType, - possibleType: GraphQLObjectType - ): boolean; + isPossibleType( + abstractType: GraphQLAbstractType, + possibleType: GraphQLObjectType, + ): boolean; - getDirectives(): GraphQLDirective[]; - getDirective(name: string): GraphQLDirective; + getDirectives(): GraphQLDirective[]; + getDirective(name: string): GraphQLDirective; } export interface GraphQLSchemaConfig { - query: GraphQLObjectType; - mutation?: GraphQLObjectType; - subscription?: GraphQLObjectType; - types?: GraphQLNamedType[]; - directives?: GraphQLDirective[]; - astNode?: SchemaDefinitionNode; + query: GraphQLObjectType; + mutation?: GraphQLObjectType; + subscription?: GraphQLObjectType; + types?: GraphQLNamedType[]; + directives?: GraphQLDirective[]; + astNode?: SchemaDefinitionNode; } diff --git a/types/graphql/utilities/TypeInfo.d.ts b/types/graphql/utilities/TypeInfo.d.ts index 98a53d37ef..a04a24a1a7 100644 --- a/types/graphql/utilities/TypeInfo.d.ts +++ b/types/graphql/utilities/TypeInfo.d.ts @@ -1,12 +1,12 @@ import { GraphQLSchema } from '../type/schema'; import { - GraphQLOutputType, - GraphQLCompositeType, - GraphQLInputType, - GraphQLField, - GraphQLArgument, - GraphQLEnumValue, - GraphQLType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLInputType, + GraphQLField, + GraphQLArgument, + GraphQLEnumValue, + GraphQLType, } from '../type/definition'; import { GraphQLDirective } from '../type/directives'; import { ASTNode, FieldNode } from '../language/ast'; @@ -17,27 +17,27 @@ import { ASTNode, FieldNode } from '../language/ast'; * AST during a recursive descent by calling `enter(node)` and `leave(node)`. */ export class TypeInfo { - constructor( - schema: GraphQLSchema, - // NOTE: this experimental optional second parameter is only needed in order - // to support non-spec-compliant codebases. You should never need to use it. - // It may disappear in the future. - getFieldDefFn?: getFieldDef - ); + constructor( + schema: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn?: getFieldDef, + ); - getType(): GraphQLOutputType; - getParentType(): GraphQLCompositeType; - getInputType(): GraphQLInputType; - getFieldDef(): GraphQLField; - getDirective(): GraphQLDirective; - getArgument(): GraphQLArgument; - getEnumValue(): GraphQLEnumValue; - enter(node: ASTNode): any; - leave(node: ASTNode): any; + getType(): GraphQLOutputType; + getParentType(): GraphQLCompositeType; + getInputType(): GraphQLInputType; + getFieldDef(): GraphQLField; + getDirective(): GraphQLDirective; + getArgument(): GraphQLArgument; + getEnumValue(): GraphQLEnumValue; + enter(node: ASTNode): any; + leave(node: ASTNode): any; } export type getFieldDef = ( - schema: GraphQLSchema, - parentType: GraphQLType, - fieldNode: FieldNode, + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, ) => GraphQLField; diff --git a/types/graphql/utilities/astFromValue.d.ts b/types/graphql/utilities/astFromValue.d.ts index 44745c5e6c..557a07dd9d 100644 --- a/types/graphql/utilities/astFromValue.d.ts +++ b/types/graphql/utilities/astFromValue.d.ts @@ -1,6 +1,6 @@ import { - ValueNode, - /* + ValueNode, + /* TODO: IntValueNode, FloatValueNode, @@ -30,7 +30,4 @@ import { GraphQLInputType } from '../type/definition'; * */ // TODO: this should set overloads according to above the table -export function astFromValue( - value: any, - type: GraphQLInputType -): ValueNode; // Warning: there is a code in bottom: throw new TypeError +export function astFromValue(value: any, type: GraphQLInputType): ValueNode; // Warning: there is a code in bottom: throw new TypeError diff --git a/types/graphql/utilities/buildClientSchema.d.ts b/types/graphql/utilities/buildClientSchema.d.ts index 166ec43cf7..bdf898bc2b 100644 --- a/types/graphql/utilities/buildClientSchema.d.ts +++ b/types/graphql/utilities/buildClientSchema.d.ts @@ -11,5 +11,5 @@ import { GraphQLSchema } from '../type/schema'; * server-internal mechanisms. */ export function buildClientSchema( - introspection: IntrospectionQuery + introspection: IntrospectionQuery, ): GraphQLSchema; diff --git a/types/graphql/utilities/extendSchema.d.ts b/types/graphql/utilities/extendSchema.d.ts index f7d00b2fee..389bd02d8b 100644 --- a/types/graphql/utilities/extendSchema.d.ts +++ b/types/graphql/utilities/extendSchema.d.ts @@ -14,6 +14,6 @@ import { GraphQLSchema } from '../type/schema'; * producing the copy. The original schema remains unaltered. */ export function extendSchema( - schema: GraphQLSchema, - documentAST: DocumentNode + schema: GraphQLSchema, + documentAST: DocumentNode, ): GraphQLSchema; diff --git a/types/graphql/utilities/findBreakingChanges.d.ts b/types/graphql/utilities/findBreakingChanges.d.ts index 78d5a5a95b..0d5fc0041a 100644 --- a/types/graphql/utilities/findBreakingChanges.d.ts +++ b/types/graphql/utilities/findBreakingChanges.d.ts @@ -1,35 +1,35 @@ import { - getNamedType, - GraphQLScalarType, - GraphQLEnumType, - GraphQLInputObjectType, - GraphQLInterfaceType, - GraphQLObjectType, - GraphQLUnionType, - GraphQLNamedType, + getNamedType, + GraphQLScalarType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLObjectType, + GraphQLUnionType, + GraphQLNamedType, } from '../type/definition'; import { GraphQLSchema } from '../type/schema'; export const BreakingChangeType: { - FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', - FIELD_REMOVED: 'FIELD_REMOVED', - TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', - TYPE_REMOVED: 'TYPE_REMOVED', - TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', - VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND'; + FIELD_REMOVED: 'FIELD_REMOVED'; + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND'; + TYPE_REMOVED: 'TYPE_REMOVED'; + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION'; + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM'; }; export type BreakingChangeKey = - | 'FIELD_CHANGED_KIND' - | 'FIELD_REMOVED' - | 'TYPE_CHANGED_KIND' - | 'TYPE_REMOVED' - | 'TYPE_REMOVED_FROM_UNION' - | 'VALUE_REMOVED_FROM_ENUM'; + | 'FIELD_CHANGED_KIND' + | 'FIELD_REMOVED' + | 'TYPE_CHANGED_KIND' + | 'TYPE_REMOVED' + | 'TYPE_REMOVED_FROM_UNION' + | 'VALUE_REMOVED_FROM_ENUM'; export interface BreakingChange { - type: BreakingChangeKey; - description: string; + type: BreakingChangeKey; + description: string; } /** @@ -37,8 +37,8 @@ export interface BreakingChange { * of breaking changes covered by the other functions down below. */ export function findBreakingChanges( - oldSchema: GraphQLSchema, - newSchema: GraphQLSchema + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, ): BreakingChange[]; /** @@ -46,8 +46,8 @@ export function findBreakingChanges( * changes in the newSchema related to removing an entire type. */ export function findRemovedTypes( - oldSchema: GraphQLSchema, - newSchema: GraphQLSchema + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, ): BreakingChange[]; /** @@ -55,8 +55,8 @@ export function findRemovedTypes( * changes in the newSchema related to changing the type of a type. */ export function findTypesThatChangedKind( - oldSchema: GraphQLSchema, - newSchema: GraphQLSchema + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, ): BreakingChange[]; /** @@ -65,8 +65,8 @@ export function findTypesThatChangedKind( * a field has been removed from a type or if a field has changed type. */ export function findFieldsThatChangedType( - oldSchema: GraphQLSchema, - newSchema: GraphQLSchema + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, ): BreakingChange[]; /** @@ -74,8 +74,8 @@ export function findFieldsThatChangedType( * changes in the newSchema related to removing types from a union type. */ export function findTypesRemovedFromUnions( - oldSchema: GraphQLSchema, - newSchema: GraphQLSchema + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, ): BreakingChange[]; /** @@ -83,6 +83,6 @@ export function findTypesRemovedFromUnions( * changes in the newSchema related to removing values from an enum type. */ export function findValuesRemovedFromEnums( - oldSchema: GraphQLSchema, - newSchema: GraphQLSchema + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, ): BreakingChange[]; diff --git a/types/graphql/utilities/findDeprecatedUsages.d.ts b/types/graphql/utilities/findDeprecatedUsages.d.ts index 8f6ff48239..8cd844e15f 100644 --- a/types/graphql/utilities/findDeprecatedUsages.d.ts +++ b/types/graphql/utilities/findDeprecatedUsages.d.ts @@ -8,6 +8,6 @@ import { GraphQLError } from '../error/GraphQLError'; * Returns a list of GraphQLError instances describing each deprecated use. */ export function findDeprecatedUsages( - schema: GraphQLSchema, - ast: DocumentNode + schema: GraphQLSchema, + ast: DocumentNode, ): GraphQLError[]; diff --git a/types/graphql/utilities/getOperationAST.d.ts b/types/graphql/utilities/getOperationAST.d.ts index ce99d39b2b..0d5064d48d 100644 --- a/types/graphql/utilities/getOperationAST.d.ts +++ b/types/graphql/utilities/getOperationAST.d.ts @@ -6,6 +6,6 @@ import { DocumentNode, OperationDefinitionNode } from '../language/ast'; * provided in the document. */ export function getOperationAST( - documentAST: DocumentNode, - operationName?: string + documentAST: DocumentNode, + operationName?: string, ): OperationDefinitionNode; diff --git a/types/graphql/utilities/index.d.ts b/types/graphql/utilities/index.d.ts index 8815046735..cd0e23948f 100644 --- a/types/graphql/utilities/index.d.ts +++ b/types/graphql/utilities/index.d.ts @@ -1,23 +1,23 @@ // The GraphQL query recommended for a full schema introspection. export { introspectionQuery } from './introspectionQuery'; export { - IntrospectionQuery, - IntrospectionSchema, - IntrospectionType, - IntrospectionScalarType, - IntrospectionObjectType, - IntrospectionInterfaceType, - IntrospectionUnionType, - IntrospectionEnumType, - IntrospectionInputObjectType, - IntrospectionTypeRef, - IntrospectionNamedTypeRef, - IntrospectionListTypeRef, - IntrospectionNonNullTypeRef, - IntrospectionField, - IntrospectionInputValue, - IntrospectionEnumValue, - IntrospectionDirective, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, } from './introspectionQuery'; // Gets the target Operation from a Document @@ -33,7 +33,11 @@ export { buildASTSchema, buildSchema } from './buildASTSchema'; export { extendSchema } from './extendSchema'; // Print a GraphQLSchema to GraphQL Schema language. -export { printSchema, printType, printIntrospectionSchema } from './schemaPrinter'; +export { + printSchema, + printType, + printIntrospectionSchema, +} from './schemaPrinter'; // Create a GraphQLType from a GraphQL language AST. export { typeFromAST } from './typeFromAST'; @@ -62,9 +66,9 @@ export { separateOperations } from './separateOperations'; // Comparators for types export { - isEqualType, - isTypeSubTypeOf, - doTypesOverlap + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, } from './typeComparators'; // Asserts that a string is a valid GraphQL name diff --git a/types/graphql/utilities/introspectionQuery.d.ts b/types/graphql/utilities/introspectionQuery.d.ts index a89c5c1fec..f16b873a3a 100644 --- a/types/graphql/utilities/introspectionQuery.d.ts +++ b/types/graphql/utilities/introspectionQuery.d.ts @@ -96,114 +96,114 @@ fragment TypeRef on __Type { export const introspectionQuery: string; export interface IntrospectionQuery { - __schema: IntrospectionSchema; + __schema: IntrospectionSchema; } export interface IntrospectionSchema { - queryType: IntrospectionNamedTypeRef; - mutationType?: IntrospectionNamedTypeRef; - subscriptionType?: IntrospectionNamedTypeRef; - types: IntrospectionType[]; - directives: IntrospectionDirective[]; + queryType: IntrospectionNamedTypeRef; + mutationType?: IntrospectionNamedTypeRef; + subscriptionType?: IntrospectionNamedTypeRef; + types: IntrospectionType[]; + directives: IntrospectionDirective[]; } export type IntrospectionType = - | IntrospectionScalarType - | IntrospectionObjectType - | IntrospectionInterfaceType - | IntrospectionUnionType - | IntrospectionEnumType - | IntrospectionInputObjectType; + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; export interface IntrospectionScalarType { - kind: 'SCALAR'; - name: string; - description?: string; + kind: 'SCALAR'; + name: string; + description?: string; } export interface IntrospectionObjectType { - kind: 'OBJECT'; - name: string; - description?: string; - fields: IntrospectionField[]; - interfaces: IntrospectionNamedTypeRef[]; + kind: 'OBJECT'; + name: string; + description?: string; + fields: IntrospectionField[]; + interfaces: IntrospectionNamedTypeRef[]; } export interface IntrospectionInterfaceType { - kind: 'INTERFACE'; - name: string; - description?: string; - fields: IntrospectionField[]; - possibleTypes: IntrospectionNamedTypeRef[]; + kind: 'INTERFACE'; + name: string; + description?: string; + fields: IntrospectionField[]; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionUnionType { - kind: 'UNION'; - name: string; - description?: string; - possibleTypes: IntrospectionNamedTypeRef[]; + kind: 'UNION'; + name: string; + description?: string; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionEnumType { - kind: 'ENUM'; - name: string; - description?: string; - enumValues: IntrospectionEnumValue[]; + kind: 'ENUM'; + name: string; + description?: string; + enumValues: IntrospectionEnumValue[]; } export interface IntrospectionInputObjectType { - kind: 'INPUT_OBJECT'; - name: string; - description?: string; - inputFields: IntrospectionInputValue[]; + kind: 'INPUT_OBJECT'; + name: string; + description?: string; + inputFields: IntrospectionInputValue[]; } export type IntrospectionTypeRef = - | IntrospectionNamedTypeRef - | IntrospectionListTypeRef - | IntrospectionNonNullTypeRef; + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef; export interface IntrospectionNamedTypeRef { - kind: string; - name: string; + kind: string; + name: string; } export interface IntrospectionListTypeRef { - kind: 'LIST'; - ofType?: IntrospectionTypeRef; + kind: 'LIST'; + ofType?: IntrospectionTypeRef; } export interface IntrospectionNonNullTypeRef { - kind: 'NON_NULL'; - ofType?: IntrospectionTypeRef; + kind: 'NON_NULL'; + ofType?: IntrospectionTypeRef; } export interface IntrospectionField { - name: string; - description?: string; - args: IntrospectionInputValue[]; - type: IntrospectionTypeRef; - isDeprecated: boolean; - deprecationReason?: string; + name: string; + description?: string; + args: IntrospectionInputValue[]; + type: IntrospectionTypeRef; + isDeprecated: boolean; + deprecationReason?: string; } export interface IntrospectionInputValue { - name: string; - description?: string; - type: IntrospectionTypeRef; - defaultValue?: string; + name: string; + description?: string; + type: IntrospectionTypeRef; + defaultValue?: string; } export interface IntrospectionEnumValue { - name: string; - description?: string; - isDeprecated: boolean; - deprecationReason?: string; + name: string; + description?: string; + isDeprecated: boolean; + deprecationReason?: string; } export interface IntrospectionDirective { - name: string; - description?: string; - locations: DirectiveLocationEnum[]; - args: IntrospectionInputValue[]; + name: string; + description?: string; + locations: DirectiveLocationEnum[]; + args: IntrospectionInputValue[]; } diff --git a/types/graphql/utilities/isValidJSValue.d.ts b/types/graphql/utilities/isValidJSValue.d.ts index cd11014579..911d8fea67 100644 --- a/types/graphql/utilities/isValidJSValue.d.ts +++ b/types/graphql/utilities/isValidJSValue.d.ts @@ -5,7 +5,4 @@ import { GraphQLInputType } from '../type/definition'; * accepted for that type. This is primarily useful for validating the * runtime values of query variables. */ -export function isValidJSValue( - value: any, - type: GraphQLInputType -): string[]; +export function isValidJSValue(value: any, type: GraphQLInputType): string[]; diff --git a/types/graphql/utilities/isValidLiteralValue.d.ts b/types/graphql/utilities/isValidLiteralValue.d.ts index 697c8eb97e..4ad03d1013 100644 --- a/types/graphql/utilities/isValidLiteralValue.d.ts +++ b/types/graphql/utilities/isValidLiteralValue.d.ts @@ -9,6 +9,6 @@ import { GraphQLInputType } from '../type/definition'; * provide values of the correct type. */ export function isValidLiteralValue( - type: GraphQLInputType, - valueNode: ValueNode + type: GraphQLInputType, + valueNode: ValueNode, ): string[]; diff --git a/types/graphql/utilities/schemaPrinter.d.ts b/types/graphql/utilities/schemaPrinter.d.ts index 2bd40f1b96..f9cf9ad209 100644 --- a/types/graphql/utilities/schemaPrinter.d.ts +++ b/types/graphql/utilities/schemaPrinter.d.ts @@ -1,8 +1,12 @@ import { GraphQLSchema } from '../type/schema'; import { GraphQLType } from '../type/definition'; -export function printSchema(schema: GraphQLSchema): string; +export interface PrinterOptions { + commentDescriptions?: boolean; +} -export function printIntrospectionSchema(schema: GraphQLSchema): string; +export function printSchema(schema: GraphQLSchema, options?: PrinterOptions): string; -export function printType(type: GraphQLType): string; +export function printIntrospectionSchema(schema: GraphQLSchema, options?: PrinterOptions): string; + +export function printType(type: GraphQLType, options?: PrinterOptions): string; diff --git a/types/graphql/utilities/separateOperations.d.ts b/types/graphql/utilities/separateOperations.d.ts index 4b4106df53..a10ad0a29e 100644 --- a/types/graphql/utilities/separateOperations.d.ts +++ b/types/graphql/utilities/separateOperations.d.ts @@ -1,8 +1,5 @@ -import { - DocumentNode, - OperationDefinitionNode, -} from '../language/ast'; +import { DocumentNode, OperationDefinitionNode } from '../language/ast'; export function separateOperations( - documentAST: DocumentNode + documentAST: DocumentNode, ): { [operationName: string]: DocumentNode }; diff --git a/types/graphql/utilities/typeComparators.d.ts b/types/graphql/utilities/typeComparators.d.ts index 16e6acd680..ca0cdaf6c2 100644 --- a/types/graphql/utilities/typeComparators.d.ts +++ b/types/graphql/utilities/typeComparators.d.ts @@ -1,11 +1,9 @@ import { - GraphQLType, - GraphQLCompositeType, - GraphQLAbstractType + GraphQLType, + GraphQLCompositeType, + GraphQLAbstractType, } from '../type/definition'; -import { - GraphQLSchema -} from '../type/schema'; +import { GraphQLSchema } from '../type/schema'; /** * Provided two types, return true if the types are equal (invariant). @@ -17,9 +15,9 @@ export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean; * equal or a subset of the second super type (covariant). */ export function isTypeSubTypeOf( - schema: GraphQLSchema, - maybeSubType: GraphQLType, - superType: GraphQLType + schema: GraphQLSchema, + maybeSubType: GraphQLType, + superType: GraphQLType, ): boolean; /** @@ -32,7 +30,7 @@ export function isTypeSubTypeOf( * This function is commutative. */ export function doTypesOverlap( - schema: GraphQLSchema, - typeA: GraphQLCompositeType, - typeB: GraphQLCompositeType + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType, ): boolean; diff --git a/types/graphql/utilities/typeFromAST.d.ts b/types/graphql/utilities/typeFromAST.d.ts index c3cacf90df..415cbd2636 100644 --- a/types/graphql/utilities/typeFromAST.d.ts +++ b/types/graphql/utilities/typeFromAST.d.ts @@ -3,6 +3,6 @@ import { GraphQLType, GraphQLNullableType } from '../type/definition'; import { GraphQLSchema } from '../type/schema'; export function typeFromAST( - schema: GraphQLSchema, - typeNode: TypeNode + schema: GraphQLSchema, + typeNode: TypeNode, ): GraphQLType; diff --git a/types/graphql/utilities/valueFromAST.d.ts b/types/graphql/utilities/valueFromAST.d.ts index 24dd435448..0bfbf04981 100644 --- a/types/graphql/utilities/valueFromAST.d.ts +++ b/types/graphql/utilities/valueFromAST.d.ts @@ -1,15 +1,15 @@ import { GraphQLInputType } from '../type/definition'; import { - ValueNode, - VariableNode, - ListValueNode, - ObjectValueNode + ValueNode, + VariableNode, + ListValueNode, + ObjectValueNode, } from '../language/ast'; export function valueFromAST( - valueNode: ValueNode, - type: GraphQLInputType, - variables?: { - [key: string]: any - } + valueNode: ValueNode, + type: GraphQLInputType, + variables?: { + [key: string]: any; + }, ): any; diff --git a/types/graphql/validation/index.d.ts b/types/graphql/validation/index.d.ts index 7f897fe78d..b8cb9ddd00 100644 --- a/types/graphql/validation/index.d.ts +++ b/types/graphql/validation/index.d.ts @@ -3,130 +3,126 @@ export { specifiedRules } from './specifiedRules'; // Spec Section: "Argument Values Type Correctness" export { - ArgumentsOfCorrectType as ArgumentsOfCorrectTypeRule + ArgumentsOfCorrectType as ArgumentsOfCorrectTypeRule, } from './rules/ArgumentsOfCorrectType'; // Spec Section: "Variable Default Values Are Correctly Typed" export { - DefaultValuesOfCorrectType as DefaultValuesOfCorrectTypeRule + DefaultValuesOfCorrectType as DefaultValuesOfCorrectTypeRule, } from './rules/DefaultValuesOfCorrectType'; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" export { - FieldsOnCorrectType as FieldsOnCorrectTypeRule + FieldsOnCorrectType as FieldsOnCorrectTypeRule, } from './rules/FieldsOnCorrectType'; // Spec Section: "Fragments on Composite Types" export { - FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule + FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule, } from './rules/FragmentsOnCompositeTypes'; // Spec Section: "Argument Names" export { - KnownArgumentNames as KnownArgumentNamesRule + KnownArgumentNames as KnownArgumentNamesRule, } from './rules/KnownArgumentNames'; // Spec Section: "Directives Are Defined" export { - KnownDirectives as KnownDirectivesRule + KnownDirectives as KnownDirectivesRule, } from './rules/KnownDirectives'; // Spec Section: "Fragment spread target defined" export { - KnownFragmentNames as KnownFragmentNamesRule + KnownFragmentNames as KnownFragmentNamesRule, } from './rules/KnownFragmentNames'; // Spec Section: "Fragment Spread Type Existence" -export { - KnownTypeNames as KnownTypeNamesRule -} from './rules/KnownTypeNames'; +export { KnownTypeNames as KnownTypeNamesRule } from './rules/KnownTypeNames'; // Spec Section: "Lone Anonymous Operation" export { - LoneAnonymousOperation as LoneAnonymousOperationRule + LoneAnonymousOperation as LoneAnonymousOperationRule, } from './rules/LoneAnonymousOperation'; // Spec Section: "Fragments must not form cycles" export { - NoFragmentCycles as NoFragmentCyclesRule + NoFragmentCycles as NoFragmentCyclesRule, } from './rules/NoFragmentCycles'; // Spec Section: "All Variable Used Defined" export { - NoUndefinedVariables as NoUndefinedVariablesRule + NoUndefinedVariables as NoUndefinedVariablesRule, } from './rules/NoUndefinedVariables'; // Spec Section: "Fragments must be used" export { - NoUnusedFragments as NoUnusedFragmentsRule + NoUnusedFragments as NoUnusedFragmentsRule, } from './rules/NoUnusedFragments'; // Spec Section: "All Variables Used" export { - NoUnusedVariables as NoUnusedVariablesRule + NoUnusedVariables as NoUnusedVariablesRule, } from './rules/NoUnusedVariables'; // Spec Section: "Field Selection Merging" export { - OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule + OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule, } from './rules/OverlappingFieldsCanBeMerged'; // Spec Section: "Fragment spread is possible" export { - PossibleFragmentSpreads as PossibleFragmentSpreadsRule + PossibleFragmentSpreads as PossibleFragmentSpreadsRule, } from './rules/PossibleFragmentSpreads'; // Spec Section: "Argument Optionality" export { - ProvidedNonNullArguments as ProvidedNonNullArgumentsRule + ProvidedNonNullArguments as ProvidedNonNullArgumentsRule, } from './rules/ProvidedNonNullArguments'; // Spec Section: "Leaf Field Selections" -export { - ScalarLeafs as ScalarLeafsRule -} from './rules/ScalarLeafs'; +export { ScalarLeafs as ScalarLeafsRule } from './rules/ScalarLeafs'; // Spec Section: "Subscriptions with Single Root Field" export { - SingleFieldSubscriptions as SingleFieldSubscriptionsRule + SingleFieldSubscriptions as SingleFieldSubscriptionsRule, } from './rules/SingleFieldSubscriptions'; // Spec Section: "Argument Uniqueness" export { - UniqueArgumentNames as UniqueArgumentNamesRule + UniqueArgumentNames as UniqueArgumentNamesRule, } from './rules/UniqueArgumentNames'; // Spec Section: "Directives Are Unique Per Location" export { - UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule + UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule, } from './rules/UniqueDirectivesPerLocation'; // Spec Section: "Fragment Name Uniqueness" export { - UniqueFragmentNames as UniqueFragmentNamesRule + UniqueFragmentNames as UniqueFragmentNamesRule, } from './rules/UniqueFragmentNames'; // Spec Section: "Input Object Field Uniqueness" export { - UniqueInputFieldNames as UniqueInputFieldNamesRule + UniqueInputFieldNames as UniqueInputFieldNamesRule, } from './rules/UniqueInputFieldNames'; // Spec Section: "Operation Name Uniqueness" export { - UniqueOperationNames as UniqueOperationNamesRule + UniqueOperationNames as UniqueOperationNamesRule, } from './rules/UniqueOperationNames'; // Spec Section: "Variable Uniqueness" export { - UniqueVariableNames as UniqueVariableNamesRule + UniqueVariableNames as UniqueVariableNamesRule, } from './rules/UniqueVariableNames'; // Spec Section: "Variables are Input Types" export { - VariablesAreInputTypes as VariablesAreInputTypesRule + VariablesAreInputTypes as VariablesAreInputTypesRule, } from './rules/VariablesAreInputTypes'; // Spec Section: "All Variable Usages Are Allowed" export { - VariablesInAllowedPosition as VariablesInAllowedPositionRule + VariablesInAllowedPosition as VariablesInAllowedPositionRule, } from './rules/VariablesInAllowedPosition'; diff --git a/types/graphql/validation/validate.d.ts b/types/graphql/validation/validate.d.ts index a4b628777e..9e2fd479f1 100644 --- a/types/graphql/validation/validate.d.ts +++ b/types/graphql/validation/validate.d.ts @@ -1,19 +1,19 @@ import { GraphQLError } from '../error'; import { - DocumentNode, - OperationDefinitionNode, - VariableNode, - SelectionSetNode, - FragmentSpreadNode, - FragmentDefinitionNode, + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, } from '../language/ast'; import { GraphQLSchema } from '../type/schema'; import { - GraphQLInputType, - GraphQLOutputType, - GraphQLCompositeType, - GraphQLField, - GraphQLArgument + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, } from '../type/definition'; import { GraphQLDirective } from '../type/directives'; import { TypeInfo } from '../utilities/TypeInfo'; @@ -33,9 +33,9 @@ import { specifiedRules } from './specifiedRules'; * GraphQLErrors, or Arrays of GraphQLErrors when invalid. */ export function validate( - schema: GraphQLSchema, - ast: DocumentNode, - rules?: any[] + schema: GraphQLSchema, + ast: DocumentNode, + rules?: any[], ): GraphQLError[]; /** @@ -45,16 +45,18 @@ export function validate( * @internal */ export function visitUsingRules( - schema: GraphQLSchema, - typeInfo: TypeInfo, - documentAST: DocumentNode, - rules: any[] + schema: GraphQLSchema, + typeInfo: TypeInfo, + documentAST: DocumentNode, + rules: any[], ): GraphQLError[]; -export type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; +export type NodeWithSelectionSet = + | OperationDefinitionNode + | FragmentDefinitionNode; export interface VariableUsage { - node: VariableNode; - type: GraphQLInputType; + node: VariableNode; + type: GraphQLInputType; } /** @@ -63,38 +65,38 @@ export interface VariableUsage { * validation rule. */ export class ValidationContext { - constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); - reportError(error: GraphQLError): void; + constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); + reportError(error: GraphQLError): void; - getErrors(): GraphQLError[]; + getErrors(): GraphQLError[]; - getSchema(): GraphQLSchema; + getSchema(): GraphQLSchema; - getDocument(): DocumentNode; + getDocument(): DocumentNode; - getFragment(name: string): FragmentDefinitionNode; + getFragment(name: string): FragmentDefinitionNode; - getFragmentSpreads(node: SelectionSetNode): FragmentSpreadNode[]; + getFragmentSpreads(node: SelectionSetNode): FragmentSpreadNode[]; - getRecursivelyReferencedFragments( - operation: OperationDefinitionNode - ): FragmentDefinitionNode[]; + getRecursivelyReferencedFragments( + operation: OperationDefinitionNode, + ): FragmentDefinitionNode[]; - getVariableUsages(node: NodeWithSelectionSet): VariableUsage[]; + getVariableUsages(node: NodeWithSelectionSet): VariableUsage[]; - getRecursiveVariableUsages( - operation: OperationDefinitionNode - ): VariableUsage[]; + getRecursiveVariableUsages( + operation: OperationDefinitionNode, + ): VariableUsage[]; - getType(): GraphQLOutputType; + getType(): GraphQLOutputType; - getParentType(): GraphQLCompositeType; + getParentType(): GraphQLCompositeType; - getInputType(): GraphQLInputType; + getInputType(): GraphQLInputType; - getFieldDef(): GraphQLField; + getFieldDef(): GraphQLField; - getDirective(): GraphQLDirective; + getDirective(): GraphQLDirective; - getArgument(): GraphQLArgument; + getArgument(): GraphQLArgument; } diff --git a/types/gsap/TweenConfig.d.ts b/types/gsap/TweenConfig.d.ts index 59c472bea2..33cde9c6ae 100644 --- a/types/gsap/TweenConfig.d.ts +++ b/types/gsap/TweenConfig.d.ts @@ -1,6 +1,9 @@ declare namespace gsap { export interface TweenConfig { + /** Any tweenable property */ + [p: string]: any; + /** Amount of delay in seconds (or frames for frames-based tweens) before the animation should begin.*/ delay?: number; diff --git a/types/gsap/gsap-tests.ts b/types/gsap/gsap-tests.ts index 048a9d522e..36192141be 100644 --- a/types/gsap/gsap-tests.ts +++ b/types/gsap/gsap-tests.ts @@ -1,8 +1,19 @@ -import { TweenLite } from 'gsap'; +import { TweenLite, TweenMax } from 'gsap'; -const tween = TweenLite +const tweenLiteExample = TweenLite .to(document.getElementById('some-div'), 1, { width: '200px', - height: '200px' + height: '200px', + x: '100px', + y: '200px' }) .seek(0.5); + +const tweenMaxExample = TweenMax + .to(document.getElementById('some-div'), 1, { + width: '200px', + height: '200px', + x: '100px', + y: '200px' + }) + .seek(0.5); diff --git a/types/gsap/index.d.ts b/types/gsap/index.d.ts index cebefcf1c9..77d589603a 100644 --- a/types/gsap/index.d.ts +++ b/types/gsap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for GSAP 1.19 // Project: http://greensock.com/ -// Definitions by: VILIC VANE , Robert S , Richard Fox +// Definitions by: VILIC VANE , Robert S , Richard Fox , Philip Bulley // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/gulp-nodemon/gulp-nodemon-tests.ts b/types/gulp-nodemon/gulp-nodemon-tests.ts index 364536f778..4c36b42aa9 100644 --- a/types/gulp-nodemon/gulp-nodemon-tests.ts +++ b/types/gulp-nodemon/gulp-nodemon-tests.ts @@ -29,6 +29,8 @@ nodemon({ }); return tasks } + , nodeArgs: ['--trace-warnings'] + , args: ['-t'] }); diff --git a/types/gulp-nodemon/index.d.ts b/types/gulp-nodemon/index.d.ts index 7c5491f596..de08560463 100644 --- a/types/gulp-nodemon/index.d.ts +++ b/types/gulp-nodemon/index.d.ts @@ -69,6 +69,9 @@ declare namespace nodemon { execMap?: { [key: string]: string | boolean | number; }; events?: { [key: string]: string; }; restartable?: string; + args?: string[]; + nodeArgs?: string[]; + scriptPosition?: number; } interface EventEmitter extends NodeJS.EventEmitter { diff --git a/types/http-proxy/index.d.ts b/types/http-proxy/index.d.ts index 962a9ecdb6..811789af33 100644 --- a/types/http-proxy/index.d.ts +++ b/types/http-proxy/index.d.ts @@ -197,6 +197,8 @@ declare namespace Server { autoRewrite?: boolean; /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ protocolRewrite?: string; + /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ + proxyTimeout?: number; } } diff --git a/types/humanize-string/humanize-string-tests.ts b/types/humanize-string/humanize-string-tests.ts new file mode 100644 index 0000000000..851746f088 --- /dev/null +++ b/types/humanize-string/humanize-string-tests.ts @@ -0,0 +1,4 @@ +import humanizeString = require('humanize-string'); + +humanizeString('UnicornsAndRainbows'); +humanizeString('unicorns_and-Rainbows_andPonies '); diff --git a/types/humanize-string/index.d.ts b/types/humanize-string/index.d.ts new file mode 100644 index 0000000000..ba8bc4e867 --- /dev/null +++ b/types/humanize-string/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for humanize-string 1.0 +// Project: https://github.com/sindresorhus/humanize-string/ +// Definitions by: Kevin Nacios +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function humanizeString(text: string): string; + +export = humanizeString; diff --git a/types/humanize-string/tsconfig.json b/types/humanize-string/tsconfig.json new file mode 100644 index 0000000000..a0ec92be13 --- /dev/null +++ b/types/humanize-string/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "humanize-string-tests.ts" + ] +} diff --git a/types/humanize-string/tslint.json b/types/humanize-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/humanize-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index c510d824eb..61b59b32e1 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -103,6 +103,11 @@ declare namespace i18next { * set it to fallback to let passed namespaces to translated hoc act as fallbacks */ nsMode?: string; + /** + * set it to the default parent element created by the Trans component. + * @default div + */ + defaultTransParent?: string; } interface InitOptions { diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index dd482c925f..f3e0407bab 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -259,11 +259,11 @@ declare namespace jasmine { execute(): void; describe(description: string, specDefinitions: () => void): Suite; // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these - beforeEach(beforeEachFunction: () => void): void; - beforeAll(beforeAllFunction: () => void): void; + beforeEach(beforeEachFunction: (done: DoneFn) => void, timeout?: number): void; + beforeAll(beforeAllFunction: (done: DoneFn) => void, timeout?: number): void; currentRunner(): Runner; - afterEach(afterEachFunction: () => void): void; - afterAll(afterAllFunction: () => void): void; + afterEach(afterEachFunction: (done: DoneFn) => void, timeout?: number): void; + afterAll(afterAllFunction: (done: DoneFn) => void, timeout?: number): void; xdescribe(desc: string, specDefinitions: () => void): XSuite; it(description: string, func: () => void): Spec; // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index e0d73d5c9e..e3cac9b881 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -548,16 +548,6 @@ declare namespace jest { // Relevant parts of Jasmine's API are below so they can be changed and removed over time. // This file can't reference jasmine.d.ts since the globals aren't compatible. -declare function spyOn(object: any, method: string): jasmine.Spy; -/** - * If you call the function pending anywhere in the spec body, - * no matter the expectations, the spec will be marked pending. - */ -declare function pending(reason?: string): void; -/** - * Fails a test when called within one. - */ -declare function fail(error?: any): void; declare namespace jasmine { let DEFAULT_TIMEOUT_INTERVAL: number; function clock(): Clock; diff --git a/types/josa/index.d.ts b/types/josa/index.d.ts new file mode 100644 index 0000000000..3ce0d08ccc --- /dev/null +++ b/types/josa/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for josa 3.0 +// Project: https://github.com/kimdhoe/josa +// Definitions by: Vichyssoise +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Topic = '은' | '는'; +export type Subject = '이' | '가'; +export type Objective = '을' | '를'; +export type Conjunction = '와' | '과'; +export type Means = '으로' | '로'; +export type Josa = Topic | Subject | Objective | Conjunction | Means; + +/** 조사 플레이스홀더(ex. #{은})가 포함된 문자열을 입력받아 완성된 문자열을 반환합니다. */ +export function josa(sentence: string): string; + +/** 명사에 맞는 조사를 찾아주는 함수를 반환합니다. 예를 들면, 임의의 명사에 대해 _을_과 를 중 하나를 선택하는 함수가 필요할 때 사용할 수 있습니다. */ +export function getJosaPicker(josa: Topic): (noun: string) => Topic; +export function getJosaPicker(josa: Subject): (noun: string) => Subject; +export function getJosaPicker(josa: Objective): (noun: string) => Objective; +export function getJosaPicker(josa: Conjunction): (noun: string) => Conjunction; +export function getJosaPicker(josa: Means): (noun: string) => Means; + +/** 명사에 조사를 붙이는 함수를 반환합니다. */ +export function makeJosaify(josa: Josa): (noun: string) => string; diff --git a/types/josa/josa-tests.ts b/types/josa/josa-tests.ts new file mode 100644 index 0000000000..6dd2ab771d --- /dev/null +++ b/types/josa/josa-tests.ts @@ -0,0 +1,22 @@ +import { josa, getJosaPicker, makeJosaify } from 'josa'; + +josa('비시스와즈'); // $ExpectType string +josa('사람들#{은} 작동만 되면 그 원리#{는} 신경#{을} 안쓰지'); // $ExpectType string + +getJosaPicker('은'); +getJosaPicker('은')('사람'); + +getJosaPicker('이'); +getJosaPicker('이')('사람'); + +getJosaPicker('을'); +getJosaPicker('을')('사람'); + +getJosaPicker('와'); +getJosaPicker('와')('사람'); + +getJosaPicker('로'); +getJosaPicker('로')('사람'); + +makeJosaify('은'); +makeJosaify('은')('사람'); // $ExpectType string diff --git a/types/josa/tsconfig.json b/types/josa/tsconfig.json new file mode 100644 index 0000000000..0c56aa9a72 --- /dev/null +++ b/types/josa/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "josa-tests.ts" + ] +} diff --git a/types/josa/tslint.json b/types/josa/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/josa/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery-sticky/index.d.ts b/types/jquery-sticky/index.d.ts new file mode 100644 index 0000000000..469ebde7a1 --- /dev/null +++ b/types/jquery-sticky/index.d.ts @@ -0,0 +1,82 @@ +// Type definitions for jquery-sticky 1.0 +// Project: https://github.com/garand/sticky +// Definitions by: Matthieu Tabuteau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +interface JQueryStickyOptions { + /** + * Pixels between the page top and the element's top. + * @default 0 + */ + topSpacing?: number; + + /** + * Pixels between the page bottom and the element's bottom. + * @default 0 + */ + bottomSpacing?: number; + + /** + * CSS class added to the element's wrapper when "sticked". + * @default is-sticky + */ + className?: string; + + /** + * CSS class added to the wrapper. + * @default 'sticky-wrapper' + */ + wrapperClassName?: string; + + /** + * Boolean determining whether the sticky element should be horizontally centered in the page. + * @default false + */ + center?: boolean; + + /** + * Selector of element referenced to set fixed width of "sticky" element. + * @default '' + */ + getWidthFrom?: string; + + /** + * Boolean determining whether width of the "sticky" element should be updated to match the wrapper's width. + * Wrapper is a placeholder for "sticky" element while it is fixed (out of static elements flow), and its width depends on the context and CSS rules. + * Works only as long getWidthForm isn't set. + * @default true + */ + widthFromWrapper?: boolean; + + /** + * Boolean determining whether widths will be recalculated on window resize (using getWidthfrom). + * @default false + */ + responsiveWidth?: boolean; + + /** + * Controls z-index of the sticked element. + * @default inherit + */ + zIndex?: string; +} + +interface JQuery { + /** + * Initializer. options is optional. + */ + sticky(options?: JQueryStickyOptions): JQuery; + + /** + * Recalculates the element's position. + */ + sticky(method: 'update'): JQuery; + + /** + * To unstick an object. + */ + unstick(): JQuery; +} diff --git a/types/jquery-sticky/jquery-sticky-tests.ts b/types/jquery-sticky/jquery-sticky-tests.ts new file mode 100644 index 0000000000..e0e6e69d9c --- /dev/null +++ b/types/jquery-sticky/jquery-sticky-tests.ts @@ -0,0 +1,18 @@ +// initialization +$('#sticker').sticky({ + topSpacing: 12, + bottomSpacing: 12, + className: 'class-name', + wrapperClassName: 'wrapper-class-name', + center: true, + getWidthFrom: '#container', + widthFromWrapper: false, + responsiveWidth: true, + zIndex: '2' +}); + +// update element position +$('#sticker').sticky('update'); + +// unstick +$("#sticker").unstick(); diff --git a/types/jquery-sticky/tsconfig.json b/types/jquery-sticky/tsconfig.json new file mode 100644 index 0000000000..1981e2e74c --- /dev/null +++ b/types/jquery-sticky/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery-sticky-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-sticky/tslint.json b/types/jquery-sticky/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jquery-sticky/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsreport-core/index.d.ts b/types/jsreport-core/index.d.ts new file mode 100644 index 0000000000..23413889da --- /dev/null +++ b/types/jsreport-core/index.d.ts @@ -0,0 +1,96 @@ +// Type definitions for jsreport-core 1.5 +// Project: http://jsreport.net +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// +import { Buffer } from 'buffer'; +import { Readable } from 'stream'; + +declare namespace JsReport { + type helpers = string | { [fun: string]: (...args: any[]) => any }; + + interface RenderOptions { + template: { + content: string; + engine: 'jsrender' | 'handlebars' | 'ejs' | 'jade' | string; + helpers?: helpers; + recipe: 'phantom-pdf' | 'electron-pdf' | 'text' | 'xlsx' | 'html-to-xlsx' | 'phantom-image' | 'html-to-text' | 'fop-pdf' | 'client-html' | 'wrapped-html' | 'wkhtmltopdf' | string; + }; + data?: any; + } + + interface Report { + content: Buffer; + stream: Readable; + headers: { + [header: string]: string | number | boolean; + }; + } + + interface Request { + template: { + content: string; + }; + } + + // interface Response { + // // todo + // } + + type Response = any; + + interface Listener { + add(type: string, callback: (req: Request, res: Response, err: any) => void): void; + } + + interface Logger { + add(logger: any, options?: { + level: 'debug' | 'info' | 'log' | 'warn' | 'error'; + }): void; + } + + interface Collection { + find(query: { + [field: string]: any; + }): Promise; + } + + interface DocumentStore { + collection(options: string): Collection; + } + + interface JsReporter { + afterRenderListeners: Listener; + afterTemplatingEnginesExecutedListeners: Listener; + beforeRenderListeners: Listener; + documentStore: DocumentStore; + initializeListeners: Listener; + logger: Logger; + validateRenderListeners: Listener; + init(): Promise; + render(options: RenderOptions): Promise; + use(extension: any): any; + } +} + +declare function JsReport(options?: Partial<{ + autoTempCleanup: boolean; + dataDirectory: string; + extensionsLocationCache: boolean; + loadConfig: boolean; + logger: { + silent: boolean; + }; + rootDirectory: string; + scripts: { + allowedModules: string[]; + }; + tasks: { + [task: string]: any; + }; + tempDirectory: string; +}>): JsReport.JsReporter; + +export = JsReport; diff --git a/types/jsreport-core/jsreport-core-tests.ts b/types/jsreport-core/jsreport-core-tests.ts new file mode 100644 index 0000000000..c7ded76f4d --- /dev/null +++ b/types/jsreport-core/jsreport-core-tests.ts @@ -0,0 +1,20 @@ +import JsReport = require('jsreport-core'); + +const jsreport = JsReport(); +jsreport.init().then(() => { + return jsreport.render({ + template: { + content: '

Hello {{:foo}}

', + engine: 'jsrender', + recipe: 'phantom-pdf' + }, + data: { + foo: "world" + } + }).then((resp) => { + // prints pdf with headline Hello world + console.log(resp.content.toString()); + }); +}).catch((e) => { + console.log(e); +}); diff --git a/types/jsreport-core/tsconfig.json b/types/jsreport-core/tsconfig.json new file mode 100644 index 0000000000..1602790a14 --- /dev/null +++ b/types/jsreport-core/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "esnext" + ], + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jsreport-core-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jsreport-core/tslint.json b/types/jsreport-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsreport-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index 32c3521f22..87a7526267 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -2,6 +2,7 @@ // Project: http://developer.longtailvideo.com/trac/ // Definitions by: Martin Duparc // Tomer Kruvi +// Philipp Gürtler // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // JW Player is the leading HTML5 & Flash video player, optimized for mobile and the desktop. Easy enough for beginners, advanced enough for pros. @@ -224,6 +225,13 @@ interface EventCallback { (param: T): void; } +interface Region { + x: 0; // x and y will always be 0 according to https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayergetsaferegion + y: 0; + width: number; + height: number; +} + interface JWPlayer { addButton(icon: string, label: string, handler: () => void, id: string): void; getAudioTracks(): any[]; @@ -243,7 +251,7 @@ interface JWPlayer { getPosition(): number; getQualityLevels(): any[]; getRenderingMode(): string; - getSafeRegion(): any[]; + getSafeRegion(): Region; getState(): string; getVolume(): number; getEnvironment(): Environment; diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 4f566a8587..e5aa9cf0a8 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -99,7 +99,7 @@ export interface Message { offset?: number; partition?: number; highWaterOffset?: number; - key?: number; + key?: string; } export interface ProducerOptions { diff --git a/types/kendo-ui/index.d.ts b/types/kendo-ui/index.d.ts index 97b840e2cf..6ea7fea725 100644 --- a/types/kendo-ui/index.d.ts +++ b/types/kendo-ui/index.d.ts @@ -3810,7 +3810,7 @@ declare namespace kendo.ui { aggregates?: any; attributes?: any; columns?: any; - command?: GridColumnCommandItem[]; + command?: string|(string|GridColumnCommandItem)[]; editable?: Function; encoded?: boolean; field?: string; @@ -20341,4 +20341,4 @@ interface JQuery { kendoWindow(options: kendo.ui.WindowOptions): JQuery; data(key: "kendoWindow"): kendo.ui.Window; -} \ No newline at end of file +} diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 72b9c828a4..99b6a10476 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -116,7 +116,7 @@ declare namespace Knex { // Union union: Union; - unionAll(callback: Function): QueryBuilder; + unionAll(callback: QueryCallback): QueryBuilder; // Having having: Having; @@ -183,29 +183,29 @@ declare namespace Knex { interface Join { (raw: Raw): QueryBuilder; - (tableName: TableName, clause: (this: JoinClause, join: JoinClause) => void): QueryBuilder; - (tableName: TableName, columns: { [key: string]: string | number | Raw }): QueryBuilder; - (tableName: TableName, raw: Raw): QueryBuilder; - (tableName: TableName, column1: string, column2: string): QueryBuilder; - (tableName: TableName, column1: string, raw: Raw): QueryBuilder; - (tableName: TableName, column1: string, operator: string, column2: string): QueryBuilder; + (tableName: TableName | QueryCallback, clause: (this: JoinClause, join: JoinClause) => void): QueryBuilder; + (tableName: TableName | QueryCallback, columns: { [key: string]: string | number | Raw }): QueryBuilder; + (tableName: TableName | QueryCallback, raw: Raw): QueryBuilder; + (tableName: TableName | QueryCallback, column1: string, column2: string): QueryBuilder; + (tableName: TableName | QueryCallback, column1: string, raw: Raw): QueryBuilder; + (tableName: TableName | QueryCallback, column1: string, operator: string, column2: string): QueryBuilder; } interface JoinClause { on(raw: Raw): JoinClause; - on(callback: Function): JoinClause; + on(callback: QueryCallback): JoinClause; on(columns: { [key: string]: string | Raw }): JoinClause; on(column1: string, column2: string): JoinClause; on(column1: string, raw: Raw): JoinClause; on(column1: string, operator: string, column2: string | Raw): JoinClause; andOn(raw: Raw): JoinClause; - andOn(callback: Function): JoinClause; + andOn(callback: QueryCallback): JoinClause; andOn(columns: { [key: string]: string | Raw }): JoinClause; andOn(column1: string, column2: string): JoinClause; andOn(column1: string, raw: Raw): JoinClause; andOn(column1: string, operator: string, column2: string | Raw): JoinClause; orOn(raw: Raw): JoinClause; - orOn(callback: Function): JoinClause; + orOn(callback: QueryCallback): JoinClause; orOn(columns: { [key: string]: string | Raw }): JoinClause; orOn(column1: string, column2: string): JoinClause; orOn(column1: string, raw: Raw): JoinClause; @@ -222,12 +222,12 @@ declare namespace Knex { onNotNull(column1: string): JoinClause; andOnNotNull(column1: string): JoinClause; orOnNotNull(column1: string): JoinClause; - onExists(callback: () => void): JoinClause; - andOnExists(callback: () => void): JoinClause; - orOnExists(callback: () => void): JoinClause; - onNotExists(callback: () => void): JoinClause; - andOnNotExists(callback: () => void): JoinClause; - orOnNotExists(callback: () => void): JoinClause; + onExists(callback: QueryCallback): JoinClause; + andOnExists(callback: QueryCallback): JoinClause; + orOnExists(callback: QueryCallback): JoinClause; + onNotExists(callback: QueryCallback): JoinClause; + andOnNotExists(callback: QueryCallback): JoinClause; + orOnNotExists(callback: QueryCallback): JoinClause; onBetween(column1: string, range: [any, any]): JoinClause; andOnBetween(column1: string, range: [any, any]): JoinClause; orOnBetween(column1: string, range: [any, any]): JoinClause; @@ -260,7 +260,7 @@ declare namespace Knex { interface Where extends WhereRaw, WhereWrapped, WhereNull { (raw: Raw): QueryBuilder; - (callback: (queryBuilder: QueryBuilder) => any): QueryBuilder; + (callback: QueryCallback): QueryBuilder; (object: Object): QueryBuilder; (columnName: string, value: Value): QueryBuilder; (columnName: string, operator: string, value: Value): QueryBuilder; @@ -272,7 +272,7 @@ declare namespace Knex { } interface WhereWrapped { - (callback: Function): QueryBuilder; + (callback: QueryCallback): QueryBuilder; } interface WhereNull { @@ -281,7 +281,7 @@ declare namespace Knex { interface WhereIn { (columnName: string, values: Value[]): QueryBuilder; - (columnName: string, callback: Function): QueryBuilder; + (columnName: string, callback: QueryCallback): QueryBuilder; (columnName: string, query: QueryBuilder): QueryBuilder; } @@ -290,7 +290,7 @@ declare namespace Knex { } interface WhereExists { - (callback: Function): QueryBuilder; + (callback: QueryCallback): QueryBuilder; (query: QueryBuilder): QueryBuilder; } @@ -310,10 +310,10 @@ declare namespace Knex { } interface Union { - (callback: Function, wrap?: boolean): QueryBuilder; - (callbacks: Function[], wrap?: boolean): QueryBuilder; - (...callbacks: Function[]): QueryBuilder; - // (...callbacks: Function[], wrap?: boolean): QueryInterface; + (callback: QueryCallback, wrap?: boolean): QueryBuilder; + (callbacks: QueryCallback[], wrap?: boolean): QueryBuilder; + (...callbacks: QueryCallback[]): QueryBuilder; + // (...callbacks: QueryCallback[], wrap?: boolean): QueryInterface; } interface Having extends RawQueryBuilder, WhereWrapped { @@ -350,6 +350,7 @@ declare namespace Knex { // QueryBuilder // + type QueryCallback = (this: QueryBuilder, builder: QueryBuilder) => void; interface QueryBuilder extends QueryInterface, ChainableInterface { or: QueryBuilder; and: QueryBuilder; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index f85168d552..3aaefb6909 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -459,6 +459,44 @@ knex.select('*').from('accounts').joinRaw('natural full join table1').where('id' knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); +knex.select('*').from('accounts') + .join(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .leftJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .leftOuterJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .rightJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .rightOuterJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .innerJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .crossJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .fullOuterJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); +knex.select('*').from('accounts') + .outerJoin(function() { + this.select('*').from('accounts').as('special_accounts'); + }, 'special_accounts.a', '=', 'accounts.b'); + + knex('customers') .distinct('first_name', 'last_name') .select(); @@ -903,6 +941,72 @@ knex.select('*') knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); +// +// Callback functions +// +knex('users') + .select('*') + .join('contacts', function(builder) { + this.on(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).andOn(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).orOn(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).onExists(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).orOnExists(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).andOnExists(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).onNotExists(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).andOnNotExists(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).orOnNotExists(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }); + }).where(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).orWhere(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).andWhere(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).whereIn('column', function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).orWhereIn('column', function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).whereNotIn('column', function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).orWhereNotIn('column', function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).whereWrapped(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).union(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }).unionAll(function(builder) { + let self: Knex.QueryBuilder = this; + self = builder; + }); + // // Migrations // diff --git a/types/koa-multer/index.d.ts b/types/koa-multer/index.d.ts new file mode 100644 index 0000000000..1c518bdd61 --- /dev/null +++ b/types/koa-multer/index.d.ts @@ -0,0 +1,134 @@ +// Type definitions for koa-multer 1.0 +// Project: https://github.com/koa-modules/multer +// Definitions by: benstevens48 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/** + * @file + * These definitions are based on the type definitions for multer - https://github.com/expressjs/multer - found on DefinitelyTyped. + * + * Note that it is necessary to explicitly cast the `Context.req` object to type `multer.MulterIncomingMessage` + * to get the correct type for the patched `Context.req` object, as in the following example. + * ```ts + * import * as Koa from 'koa'; + * import * as Router from 'koa-router'; + * import * as multer from 'koa-multer'; + * + * async function uploadFile(ctx: Koa.Context){ + * let multerReq = ctx.req; + * let files = multerReq.files; + * let baseFilePath: string = ctx.params.path || ''; + * //... + * } + * + * let router = new Router(); + * router.put('/uploads/:path?', upload.array('files'), uploadFile); + * ``` + * The type cast is necessary since the type definitions for Koa do not allow for the `Context.req` property to be extended. + */ + +import * as Koa from 'koa'; +import { IncomingMessage } from 'http'; + +declare namespace multer { + interface File { + /** Field name specified in the form */ + fieldname: string; + /** Name of the file on the user's computer */ + originalname: string; + /** Encoding type of the file */ + encoding: string; + /** Mime type of the file */ + mimetype: string; + /** Size of the file in bytes */ + size: number; + /** The folder to which the file has been saved (DiskStorage) */ + destination: string; + /** The name of the file within the destination (DiskStorage) */ + filename: string; + /** Location of the uploaded file (DiskStorage) */ + path: string; + /** A Buffer of the entire file (MemoryStorage) */ + buffer: Buffer; + } + + interface MulterIncomingMessage extends IncomingMessage { + body: any; + file: File; + files: { + [fieldname: string]: File[]; + } | File[]; + } + + interface Field { + /** The field name. */ + name: string; + /** Optional maximum number of files per field to accept. */ + maxCount?: number; + } + + interface Options { + /** The destination directory for the uploaded files. */ + dest?: string; + /** The storage engine to use for uploaded files. */ + storage?: StorageEngine; + /** + * An object specifying the size limits of the following optional properties. This object is passed to busboy + * directly, and the details of properties can be found on https://github.com/mscdex/busboy#busboy-methods + */ + limits?: { + /** Max field name size (Default: 100 bytes) */ + fieldNameSize?: number; + /** Max field value size (Default: 1MB) */ + fieldSize?: number; + /** Max number of non- file fields (Default: Infinity) */ + fields?: number; + /** For multipart forms, the max file size (in bytes)(Default: Infinity) */ + fileSize?: number; + /** For multipart forms, the max number of file fields (Default: Infinity) */ + files?: number; + /** For multipart forms, the max number of parts (fields + files)(Default: Infinity) */ + parts?: number; + /** For multipart forms, the max number of header key=> value pairs to parse Default: 2000(same as node's http). */ + headerPairs?: number; + /** Keep the full path of files instead of just the base name (Default: false) */ + preservePath?: boolean; + }; + /** A function to control which files to upload and which to skip. */ + fileFilter?(req: IncomingMessage, file: File, callback: (error: Error | null, acceptFile: boolean) => void): void; + } + + interface StorageEngine { + _handleFile(req: IncomingMessage, file: File, callback: (error?: any, info?: File) => void): void; + _removeFile(req: IncomingMessage, file: File, callback: (error: Error) => void): void; + } + + interface DiskStorageOptions { + /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ + destination?: string | ((req: IncomingMessage, file: File, callback: (error: Error | null, destination: string) => void) => void); + /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ + filename?(req: IncomingMessage, file: File, callback: (error: Error | null, filename: string) => void): void; + } + + interface Instance { + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + /** Accept a single file with the name fieldName. The single file will be stored in req.file. */ + single(fieldName?: string): Koa.Middleware; + /** Accept an array of files, all with the name fieldName. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ + array(fieldName: string, maxCount?: number): Koa.Middleware; + /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ + fields(fields: Field[]): Koa.Middleware; + /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ + any(): Koa.Middleware; + } + + /* The disk storage engine gives you full control on storing files to disk. */ + function diskStorage(options: DiskStorageOptions): StorageEngine; + /* The memory storage engine stores the files in memory as Buffer objects. */ + function memoryStorage(): StorageEngine; +} + +declare function multer(options?: multer.Options): multer.Instance; + +export = multer; diff --git a/types/koa-multer/koa-multer-tests.ts b/types/koa-multer/koa-multer-tests.ts new file mode 100644 index 0000000000..212b4d95b0 --- /dev/null +++ b/types/koa-multer/koa-multer-tests.ts @@ -0,0 +1,32 @@ +import * as Koa from 'koa'; +import * as multer from 'koa-multer'; + +const upload = multer({ + dest: 'uploads/', + fileFilter: (req, file, cb) => { + cb(null, true); + } +}); + +const app = new Koa(); + +app.use(upload.single('avatar')); + +app.use(upload.array('photos', 12)); + +const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]); +app.use(cpUpload); + +const diskStorage = multer.diskStorage({ + destination(req, file, cb) { + cb(null, '/tmp/my-uploads'); + }, + filename(req, file, cb) { + cb(null, `${file.fieldname}-${Date.now()}`); + } +}); + +const diskUpload = multer({ storage: diskStorage }); + +const memoryStorage = multer.memoryStorage(); +const memoryUpload = multer({ storage: memoryStorage }); diff --git a/types/koa-multer/tsconfig.json b/types/koa-multer/tsconfig.json new file mode 100644 index 0000000000..63f7b13ec3 --- /dev/null +++ b/types/koa-multer/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-multer-tests.ts" + ] +} diff --git a/types/koa-multer/tslint.json b/types/koa-multer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-multer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/leaflet-draw/index.d.ts b/types/leaflet-draw/index.d.ts index 35d014b699..7fd33f2152 100644 --- a/types/leaflet-draw/index.d.ts +++ b/types/leaflet-draw/index.d.ts @@ -387,7 +387,7 @@ declare module 'leaflet' { /** * Layer that was just created. */ - layer: Layer; + layer: Circle | CircleMarker | Marker | Polygon | Polyline | Rectangle; /** * The type of layer this is. One of: polyline, polygon, rectangle, circle, marker. diff --git a/types/leaflet-draw/leaflet-draw-tests.ts b/types/leaflet-draw/leaflet-draw-tests.ts index e63006edce..54015fa404 100644 --- a/types/leaflet-draw/leaflet-draw-tests.ts +++ b/types/leaflet-draw/leaflet-draw-tests.ts @@ -41,6 +41,7 @@ map.addControl(drawControl); map.on(L.Draw.Event.CREATED, (e: L.DrawEvents.Created) => { const type = e.layerType; const layer = e.layer; + const geojson = e.layer.toGeoJSON(); drawnItems.addLayer(layer); }); diff --git a/types/leaflet.locatecontrol/index.d.ts b/types/leaflet.locatecontrol/index.d.ts index 35c88be5be..542461cec7 100644 --- a/types/leaflet.locatecontrol/index.d.ts +++ b/types/leaflet.locatecontrol/index.d.ts @@ -8,6 +8,12 @@ import * as L from 'leaflet'; declare module 'leaflet' { namespace Control { + class Locate extends Control { + onAdd(map: Map): HTMLElement; + start(): void; + stop(): void; + setView(): void; + } interface LocateOptions { position?: string; layer?: Layer; @@ -40,6 +46,6 @@ declare module 'leaflet' { /** * Creates a Leaflet.Locate control */ - function locate(options?: Control.LocateOptions): Control; + function locate(options?: Control.LocateOptions): Control.Locate; } } diff --git a/types/lodash/array/chunk.d.ts b/types/lodash/array/chunk.d.ts index de40df8673..a1fe16cc02 100644 --- a/types/lodash/array/chunk.d.ts +++ b/types/lodash/array/chunk.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of elements split into groups the length of size. If collection can’t be split evenly, the diff --git a/types/lodash/array/compact.d.ts b/types/lodash/array/compact.d.ts index 1de3bbae4c..4240c7d329 100644 --- a/types/lodash/array/compact.d.ts +++ b/types/lodash/array/compact.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are diff --git a/types/lodash/array/concat.d.ts b/types/lodash/array/concat.d.ts index 977a086525..acd381f393 100644 --- a/types/lodash/array/concat.d.ts +++ b/types/lodash/array/concat.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a new array concatenating `array` with any additional arrays diff --git a/types/lodash/array/difference.d.ts b/types/lodash/array/difference.d.ts index c6d1797192..16e2c5317c 100644 --- a/types/lodash/array/difference.d.ts +++ b/types/lodash/array/difference.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of unique array values not included in the other provided arrays using SameValueZero for diff --git a/types/lodash/array/differenceBy.d.ts b/types/lodash/array/differenceBy.d.ts index 6b291ac272..ab6fb9d732 100644 --- a/types/lodash/array/differenceBy.d.ts +++ b/types/lodash/array/differenceBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.difference except that it accepts iteratee which is invoked for each element of array diff --git a/types/lodash/array/differenceWith.d.ts b/types/lodash/array/differenceWith.d.ts index c238f54b06..70b3e9bc83 100644 --- a/types/lodash/array/differenceWith.d.ts +++ b/types/lodash/array/differenceWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of unique `array` values not included in the other diff --git a/types/lodash/array/drop.d.ts b/types/lodash/array/drop.d.ts index 89e5b68b9b..cff9e9fe2b 100644 --- a/types/lodash/array/drop.d.ts +++ b/types/lodash/array/drop.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array with n elements dropped from the beginning. diff --git a/types/lodash/array/dropRight.d.ts b/types/lodash/array/dropRight.d.ts index 518080db8b..e2a0b52077 100644 --- a/types/lodash/array/dropRight.d.ts +++ b/types/lodash/array/dropRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array with n elements dropped from the end. diff --git a/types/lodash/array/dropRightWhile.d.ts b/types/lodash/array/dropRightWhile.d.ts index 26aeba29eb..f565512a2c 100644 --- a/types/lodash/array/dropRightWhile.d.ts +++ b/types/lodash/array/dropRightWhile.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array excluding elements dropped from the end. Elements are dropped until predicate diff --git a/types/lodash/array/dropWhile.d.ts b/types/lodash/array/dropWhile.d.ts index 6335cec6b6..54324ff8ee 100644 --- a/types/lodash/array/dropWhile.d.ts +++ b/types/lodash/array/dropWhile.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array excluding elements dropped from the beginning. Elements are dropped until predicate diff --git a/types/lodash/array/fill.d.ts b/types/lodash/array/fill.d.ts index de22051cc8..7d729dc27a 100644 --- a/types/lodash/array/fill.d.ts +++ b/types/lodash/array/fill.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Fills elements of array with value from start up to, but not including, end. diff --git a/types/lodash/array/findIndex.d.ts b/types/lodash/array/findIndex.d.ts index eb0d6ae1a1..5993462151 100644 --- a/types/lodash/array/findIndex.d.ts +++ b/types/lodash/array/findIndex.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.find except that it returns the index of the first element predicate returns truthy diff --git a/types/lodash/array/findLastIndex.d.ts b/types/lodash/array/findLastIndex.d.ts index 04088a7ea2..46399aab51 100644 --- a/types/lodash/array/findLastIndex.d.ts +++ b/types/lodash/array/findLastIndex.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.findIndex except that it iterates over elements of collection from right to left. diff --git a/types/lodash/array/first.d.ts b/types/lodash/array/first.d.ts index 13c28fbce0..3b17d66ebe 100644 --- a/types/lodash/array/first.d.ts +++ b/types/lodash/array/first.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { first: typeof _.head; // tslint:disable-line:no-unnecessary-qualifier } diff --git a/types/lodash/array/flatten.d.ts b/types/lodash/array/flatten.d.ts index cce7ded984..8d78592bb4 100644 --- a/types/lodash/array/flatten.d.ts +++ b/types/lodash/array/flatten.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Flattens a nested array. If isDeep is true the array is recursively flattened, otherwise it’s only diff --git a/types/lodash/array/flattenDeep.d.ts b/types/lodash/array/flattenDeep.d.ts index f25386327a..6b676f474f 100644 --- a/types/lodash/array/flattenDeep.d.ts +++ b/types/lodash/array/flattenDeep.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Recursively flattens a nested array. diff --git a/types/lodash/array/flattenDepth.d.ts b/types/lodash/array/flattenDepth.d.ts index 807e925308..65bd6c161e 100644 --- a/types/lodash/array/flattenDepth.d.ts +++ b/types/lodash/array/flattenDepth.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Recursively flatten array up to depth times. diff --git a/types/lodash/array/fromPairs.d.ts b/types/lodash/array/fromPairs.d.ts index 08af96f8e2..bc6264448c 100644 --- a/types/lodash/array/fromPairs.d.ts +++ b/types/lodash/array/fromPairs.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The inverse of `_.toPairs`; this method returns an object composed diff --git a/types/lodash/array/head.d.ts b/types/lodash/array/head.d.ts index 19c2d2df77..cc9a0ec697 100644 --- a/types/lodash/array/head.d.ts +++ b/types/lodash/array/head.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets the first element of array. diff --git a/types/lodash/array/indexOf.d.ts b/types/lodash/array/indexOf.d.ts index da5d91e0d3..d957c852db 100644 --- a/types/lodash/array/indexOf.d.ts +++ b/types/lodash/array/indexOf.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets the index at which the first occurrence of `value` is found in `array` diff --git a/types/lodash/array/initial.d.ts b/types/lodash/array/initial.d.ts index d011a0998f..3e09fbc4d4 100644 --- a/types/lodash/array/initial.d.ts +++ b/types/lodash/array/initial.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets all but the last element of array. diff --git a/types/lodash/array/intersection.d.ts b/types/lodash/array/intersection.d.ts index 71a7c06abc..a562d6f306 100644 --- a/types/lodash/array/intersection.d.ts +++ b/types/lodash/array/intersection.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of unique values that are included in all of the provided arrays using SameValueZero for diff --git a/types/lodash/array/intersectionBy.d.ts b/types/lodash/array/intersectionBy.d.ts index 251dbd78f7..3572367f4d 100644 --- a/types/lodash/array/intersectionBy.d.ts +++ b/types/lodash/array/intersectionBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.intersection` except that it accepts `iteratee` diff --git a/types/lodash/array/intersectionWith.d.ts b/types/lodash/array/intersectionWith.d.ts index 5dce77beab..9214da8652 100644 --- a/types/lodash/array/intersectionWith.d.ts +++ b/types/lodash/array/intersectionWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of unique `array` values not included in the other diff --git a/types/lodash/array/join.d.ts b/types/lodash/array/join.d.ts index 27d62caaff..01ee4c1e3b 100644 --- a/types/lodash/array/join.d.ts +++ b/types/lodash/array/join.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts all elements in `array` into a string separated by `separator`. diff --git a/types/lodash/array/last.d.ts b/types/lodash/array/last.d.ts index 1c6d435eff..5e018dd8d6 100644 --- a/types/lodash/array/last.d.ts +++ b/types/lodash/array/last.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets the last element of array. diff --git a/types/lodash/array/lastIndexOf.d.ts b/types/lodash/array/lastIndexOf.d.ts index 454b8b2676..bcec4239cd 100644 --- a/types/lodash/array/lastIndexOf.d.ts +++ b/types/lodash/array/lastIndexOf.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.indexOf except that it iterates over elements of array from right to left. diff --git a/types/lodash/array/nth.d.ts b/types/lodash/array/nth.d.ts index e6ebe7834d..bc6846d047 100644 --- a/types/lodash/array/nth.d.ts +++ b/types/lodash/array/nth.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets the element at index `n` of `array`. If `n` is negative, the nth element from the end is returned. diff --git a/types/lodash/array/pull.d.ts b/types/lodash/array/pull.d.ts index b604bc9ff7..00e4ea87f4 100644 --- a/types/lodash/array/pull.d.ts +++ b/types/lodash/array/pull.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Removes all provided values from array using SameValueZero for equality comparisons. diff --git a/types/lodash/array/pullAll.d.ts b/types/lodash/array/pullAll.d.ts index 33e663c8be..0b01b938e0 100644 --- a/types/lodash/array/pullAll.d.ts +++ b/types/lodash/array/pullAll.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.pull` except that it accepts an array of values to remove. diff --git a/types/lodash/array/pullAllBy.d.ts b/types/lodash/array/pullAllBy.d.ts index e2261a7d8b..c9eda04ee6 100644 --- a/types/lodash/array/pullAllBy.d.ts +++ b/types/lodash/array/pullAllBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.pullAll` except that it accepts `iteratee` which is diff --git a/types/lodash/array/pullAllWith.d.ts b/types/lodash/array/pullAllWith.d.ts index aefdf90981..931c58363a 100644 --- a/types/lodash/array/pullAllWith.d.ts +++ b/types/lodash/array/pullAllWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.pullAll` except that it accepts `comparator` which is diff --git a/types/lodash/array/pullAt.d.ts b/types/lodash/array/pullAt.d.ts index 8a161cfd97..27633413e1 100644 --- a/types/lodash/array/pullAt.d.ts +++ b/types/lodash/array/pullAt.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Removes elements from array corresponding to the given indexes and returns an array of the removed elements. diff --git a/types/lodash/array/remove.d.ts b/types/lodash/array/remove.d.ts index cc8ed55a3c..4aa873cb51 100644 --- a/types/lodash/array/remove.d.ts +++ b/types/lodash/array/remove.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Removes all elements from array that predicate returns truthy for and returns an array of the removed diff --git a/types/lodash/array/reverse.d.ts b/types/lodash/array/reverse.d.ts index a5a4c61b2a..b5e0e7df2b 100644 --- a/types/lodash/array/reverse.d.ts +++ b/types/lodash/array/reverse.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Reverses `array` so that the first element becomes the last, the second diff --git a/types/lodash/array/slice.d.ts b/types/lodash/array/slice.d.ts index 4161cf25de..68140b77c2 100644 --- a/types/lodash/array/slice.d.ts +++ b/types/lodash/array/slice.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array from start up to, but not including, end. diff --git a/types/lodash/array/sortedIndex.d.ts b/types/lodash/array/sortedIndex.d.ts index 2390a19e66..c772692e1c 100644 --- a/types/lodash/array/sortedIndex.d.ts +++ b/types/lodash/array/sortedIndex.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Uses a binary search to determine the lowest index at which `value` should diff --git a/types/lodash/array/sortedIndexBy.d.ts b/types/lodash/array/sortedIndexBy.d.ts index b71ae3b859..216cb9564b 100644 --- a/types/lodash/array/sortedIndexBy.d.ts +++ b/types/lodash/array/sortedIndexBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Uses a binary search to determine the lowest index at which `value` should diff --git a/types/lodash/array/sortedIndexOf.d.ts b/types/lodash/array/sortedIndexOf.d.ts index f3e7143074..d0bd2da2f2 100644 --- a/types/lodash/array/sortedIndexOf.d.ts +++ b/types/lodash/array/sortedIndexOf.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.indexOf` except that it performs a binary diff --git a/types/lodash/array/sortedLastIndex.d.ts b/types/lodash/array/sortedLastIndex.d.ts index af4cc1663b..a218e16097 100644 --- a/types/lodash/array/sortedLastIndex.d.ts +++ b/types/lodash/array/sortedLastIndex.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.sortedIndex` except that it returns the highest diff --git a/types/lodash/array/sortedLastIndexBy.d.ts b/types/lodash/array/sortedLastIndexBy.d.ts index 5a691a6b28..8db2dd2002 100644 --- a/types/lodash/array/sortedLastIndexBy.d.ts +++ b/types/lodash/array/sortedLastIndexBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` diff --git a/types/lodash/array/sortedLastIndexOf.d.ts b/types/lodash/array/sortedLastIndexOf.d.ts index 6230ec6c44..9ae49e52f4 100644 --- a/types/lodash/array/sortedLastIndexOf.d.ts +++ b/types/lodash/array/sortedLastIndexOf.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.lastIndexOf` except that it performs a binary diff --git a/types/lodash/array/sortedUniq.d.ts b/types/lodash/array/sortedUniq.d.ts index 74e7e79f0f..5771155512 100644 --- a/types/lodash/array/sortedUniq.d.ts +++ b/types/lodash/array/sortedUniq.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.uniq` except that it's designed and optimized diff --git a/types/lodash/array/sortedUniqBy.d.ts b/types/lodash/array/sortedUniqBy.d.ts index 6cad3ad107..3f25ac1e70 100644 --- a/types/lodash/array/sortedUniqBy.d.ts +++ b/types/lodash/array/sortedUniqBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.uniqBy` except that it's designed and optimized diff --git a/types/lodash/array/tail.d.ts b/types/lodash/array/tail.d.ts index ed73ef0fbe..6f0366d4e3 100644 --- a/types/lodash/array/tail.d.ts +++ b/types/lodash/array/tail.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets all but the first element of array. diff --git a/types/lodash/array/take.d.ts b/types/lodash/array/take.d.ts index 5044113e2d..13f9706a86 100644 --- a/types/lodash/array/take.d.ts +++ b/types/lodash/array/take.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array with n elements taken from the beginning. diff --git a/types/lodash/array/takeRight.d.ts b/types/lodash/array/takeRight.d.ts index 4620ac6e4d..aa3debabb1 100644 --- a/types/lodash/array/takeRight.d.ts +++ b/types/lodash/array/takeRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array with n elements taken from the end. diff --git a/types/lodash/array/takeRightWhile.d.ts b/types/lodash/array/takeRightWhile.d.ts index aa9822bbfb..6152aeac3f 100644 --- a/types/lodash/array/takeRightWhile.d.ts +++ b/types/lodash/array/takeRightWhile.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array with elements taken from the end. Elements are taken until predicate returns diff --git a/types/lodash/array/takeWhile.d.ts b/types/lodash/array/takeWhile.d.ts index e9d28e076a..1988e9e6b9 100644 --- a/types/lodash/array/takeWhile.d.ts +++ b/types/lodash/array/takeWhile.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a slice of array with elements taken from the beginning. Elements are taken until predicate returns diff --git a/types/lodash/array/union.d.ts b/types/lodash/array/union.d.ts index 4e977dc4f5..c4dff47929 100644 --- a/types/lodash/array/union.d.ts +++ b/types/lodash/array/union.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of unique values, in order, from all of the provided arrays using SameValueZero for diff --git a/types/lodash/array/unionBy.d.ts b/types/lodash/array/unionBy.d.ts index bafedc0b14..62546c75f0 100644 --- a/types/lodash/array/unionBy.d.ts +++ b/types/lodash/array/unionBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.union` except that it accepts `iteratee` which is diff --git a/types/lodash/array/unionWith.d.ts b/types/lodash/array/unionWith.d.ts index 9e427abdbf..55ed7a3630 100644 --- a/types/lodash/array/unionWith.d.ts +++ b/types/lodash/array/unionWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.union` except that it accepts `comparator` which diff --git a/types/lodash/array/uniq.d.ts b/types/lodash/array/uniq.d.ts index 670000bfb7..57a5226989 100644 --- a/types/lodash/array/uniq.d.ts +++ b/types/lodash/array/uniq.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a duplicate-free version of an array, using diff --git a/types/lodash/array/uniqBy.d.ts b/types/lodash/array/uniqBy.d.ts index 61345382c1..86fe09323d 100644 --- a/types/lodash/array/uniqBy.d.ts +++ b/types/lodash/array/uniqBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.uniq` except that it accepts `iteratee` which is diff --git a/types/lodash/array/uniqWith.d.ts b/types/lodash/array/uniqWith.d.ts index e5c28bb2d3..cbf93a5313 100644 --- a/types/lodash/array/uniqWith.d.ts +++ b/types/lodash/array/uniqWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.uniq` except that it accepts `comparator` which diff --git a/types/lodash/array/unzip.d.ts b/types/lodash/array/unzip.d.ts index c374a2369b..ec261d4b81 100644 --- a/types/lodash/array/unzip.d.ts +++ b/types/lodash/array/unzip.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.zip except that it accepts an array of grouped elements and creates an array diff --git a/types/lodash/array/unzipWith.d.ts b/types/lodash/array/unzipWith.d.ts index 2b0c0bf119..601b58869c 100644 --- a/types/lodash/array/unzipWith.d.ts +++ b/types/lodash/array/unzipWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.unzip except that it accepts an iteratee to specify how regrouped values should be diff --git a/types/lodash/array/without.d.ts b/types/lodash/array/without.d.ts index d722342d89..a134f2047b 100644 --- a/types/lodash/array/without.d.ts +++ b/types/lodash/array/without.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array excluding all provided values using SameValueZero for equality comparisons. diff --git a/types/lodash/array/xor.d.ts b/types/lodash/array/xor.d.ts index 04eaa051e7..7db9f8aec9 100644 --- a/types/lodash/array/xor.d.ts +++ b/types/lodash/array/xor.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of unique values that is the symmetric difference of the provided arrays. diff --git a/types/lodash/array/xorBy.d.ts b/types/lodash/array/xorBy.d.ts index 6728c569dc..b3aa53c3c6 100644 --- a/types/lodash/array/xorBy.d.ts +++ b/types/lodash/array/xorBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.xor` except that it accepts `iteratee` which is diff --git a/types/lodash/array/xorWith.d.ts b/types/lodash/array/xorWith.d.ts index cec73890d3..811fa0bb69 100644 --- a/types/lodash/array/xorWith.d.ts +++ b/types/lodash/array/xorWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.xor` except that it accepts `comparator` which is diff --git a/types/lodash/array/zip.d.ts b/types/lodash/array/zip.d.ts index 612899b87e..cc8fa0be88 100644 --- a/types/lodash/array/zip.d.ts +++ b/types/lodash/array/zip.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of grouped elements, the first of which contains the first elements of the given arrays, @@ -7,10 +8,68 @@ declare namespace _ { * @param arrays The arrays to process. * @return Returns the new array of grouped elements. */ + zip(arrays1: List, arrays2: List): Array<[T1, T2]>; + + /** + * @see _.zip + */ + zip(arrays1: List, arrays2: List, arrays3: List): Array<[T1, T2, T3]>; + + /** + * @see _.zip + */ + zip(arrays1: List, arrays2: List, arrays3: List, arrays4: List): Array<[T1, T2, T3, T4]>; + + /** + * @see _.zip + */ + zip(arrays1: List, arrays2: List, arrays3: List, arrays4: List, arrays5: List): Array<[T1, T2, T3, T4, T5]>; + + /** + * @see _.zip + */ zip(...arrays: Array | null | undefined>): T[][]; } interface LoDashImplicitWrapper { + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + ): LoDashImplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + ): LoDashImplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + ): LoDashImplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + ): LoDashImplicitWrapper>; + /** * @see _.zip */ @@ -21,6 +80,44 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + ): LoDashExplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + ): LoDashExplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + ): LoDashExplicitWrapper>; + + /** + * @see _.zip + */ + zip( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + ): LoDashExplicitWrapper>; + /** * @see _.zip */ diff --git a/types/lodash/array/zipObject.d.ts b/types/lodash/array/zipObject.d.ts index 49b34166c2..5178fe4b56 100644 --- a/types/lodash/array/zipObject.d.ts +++ b/types/lodash/array/zipObject.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.fromPairs except that it accepts two arrays, one of property diff --git a/types/lodash/array/zipObjectDeep.d.ts b/types/lodash/array/zipObjectDeep.d.ts index e68c5d1292..d4f4ace14a 100644 --- a/types/lodash/array/zipObjectDeep.d.ts +++ b/types/lodash/array/zipObjectDeep.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.zipObject except that it supports property paths. diff --git a/types/lodash/array/zipWith.d.ts b/types/lodash/array/zipWith.d.ts index f0cef3776a..db4d709467 100644 --- a/types/lodash/array/zipWith.d.ts +++ b/types/lodash/array/zipWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.zip except that it accepts an iteratee to specify how grouped values should be @@ -9,89 +10,110 @@ declare namespace _ { * @param [thisArg] The `this` binding of `iteratee`. * @return Returns the new array of grouped elements. */ - zipWith( - ...arrays: Array | null | undefined> - ): T[][]; - - /** - * @see _.zipWith - */ zipWith( - arrays: List | null | undefined, + arrays: List, iteratee: (value1: T) => TResult ): TResult[]; /** * @see _.zipWith */ - zipWith( - arrays: List | null | undefined, - arrays2: List | null | undefined, - iteratee: (value1: T, value2: T) => TResult + zipWith( + arrays1: List, + arrays2: List, + iteratee: (value1: T1, value2: T2) => TResult ): TResult[]; /** * @see _.zipWith */ - zipWith( - arrays: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee: (value1: T, value2: T, value3: T) => TResult + zipWith( + arrays1: List, + arrays2: List, + arrays3: List, + iteratee: (value1: T1, value2: T2, value3: T3) => TResult ): TResult[]; /** * @see _.zipWith */ - zipWith( - arrays: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee: (value1: T, value2: T, value3: T, value4: T) => TResult + zipWith( + arrays1: List, + arrays2: List, + arrays3: List, + arrays4: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4) => TResult ): TResult[]; /** * @see _.zipWith */ - zipWith( - arrays: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee: (value1: T, value2: T, value3: T, value4: T, value5: T) => TResult + zipWith( + arrays1: List, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => TResult ): TResult[]; + /** + * @see _.zipWith + */ zipWith( ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> ): TResult[]; } interface LoDashImplicitWrapper { - /** - * @see _.zipWith - */ - zipWith( - this: LoDashImplicitWrapper | null | undefined>, - ...arrays: Array | null | undefined> - ): LoDashImplicitWrapper; - /** * @see _.zipWith */ zipWith( - this: LoDashImplicitWrapper | null | undefined>, + this: LoDashImplicitWrapper>, iteratee: (value1: T) => TResult ): LoDashImplicitWrapper; /** * @see _.zipWith */ - zipWith( - this: LoDashImplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - iteratee: (value1: T, value2: T) => TResult + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + iteratee: (value1: T1, value2: T2) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + iteratee: (value1: T1, value2: T2, value3: T3) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => TResult ): LoDashImplicitWrapper; /** @@ -99,59 +121,59 @@ declare namespace _ { */ zipWith( this: LoDashImplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee: (value1: T, value2: T, value3: T) => TResult - ): LoDashImplicitWrapper; - - /** - * @see _.zipWith - */ - zipWith( - this: LoDashImplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee: (value1: T, value2: T, value3: T, value4: T) => TResult - ): LoDashImplicitWrapper; - - /** - * @see _.zipWith - */ - zipWith( - this: LoDashImplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> ): LoDashImplicitWrapper; } interface LoDashExplicitWrapper { - /** - * @see _.zipWith - */ - zipWith( - this: LoDashExplicitWrapper | null | undefined>, - ...arrays: Array | null | undefined> - ): LoDashExplicitWrapper; - /** * @see _.zipWith */ zipWith( - this: LoDashExplicitWrapper | null | undefined>, + this: LoDashExplicitWrapper>, iteratee: (value1: T) => TResult ): LoDashExplicitWrapper; /** * @see _.zipWith */ - zipWith( - this: LoDashExplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - iteratee: (value1: T, value2: T) => TResult + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + iteratee: (value1: T1, value2: T2) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + iteratee: (value1: T1, value2: T2, value3: T3) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper>, + arrays2: List, + arrays3: List, + arrays4: List, + arrays5: List, + iteratee: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => TResult ): LoDashExplicitWrapper; /** @@ -159,31 +181,6 @@ declare namespace _ { */ zipWith( this: LoDashExplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee: (value1: T, value2: T, value3: T) => TResult - ): LoDashExplicitWrapper; - - /** - * @see _.zipWith - */ - zipWith( - this: LoDashExplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee: (value1: T, value2: T, value3: T, value4: T) => TResult - ): LoDashExplicitWrapper; - - /** - * @see _.zipWith - */ - zipWith( - this: LoDashExplicitWrapper | null | undefined>, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> ): LoDashExplicitWrapper; } diff --git a/types/lodash/collection/countBy.d.ts b/types/lodash/collection/countBy.d.ts index 0a6a819c5f..05318138f6 100644 --- a/types/lodash/collection/countBy.d.ts +++ b/types/lodash/collection/countBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object composed of keys generated from the results of running each element of collection through diff --git a/types/lodash/collection/each.d.ts b/types/lodash/collection/each.d.ts index a12df91b30..7455dbbe9b 100644 --- a/types/lodash/collection/each.d.ts +++ b/types/lodash/collection/each.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { each: typeof _.forEach; // tslint:disable-line:no-unnecessary-qualifier } diff --git a/types/lodash/collection/eachRight.d.ts b/types/lodash/collection/eachRight.d.ts index d8e448a486..cbc847670a 100644 --- a/types/lodash/collection/eachRight.d.ts +++ b/types/lodash/collection/eachRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { eachRight: typeof _.forEachRight; // tslint:disable-line:no-unnecessary-qualifier } diff --git a/types/lodash/collection/every.d.ts b/types/lodash/collection/every.d.ts index 76e6e659d7..fbf6734802 100644 --- a/types/lodash/collection/every.d.ts +++ b/types/lodash/collection/every.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if predicate returns truthy for all elements of collection. Iteration is stopped once predicate diff --git a/types/lodash/collection/filter.d.ts b/types/lodash/collection/filter.d.ts index adfe9a22c7..58640ecd9e 100644 --- a/types/lodash/collection/filter.d.ts +++ b/types/lodash/collection/filter.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The diff --git a/types/lodash/collection/find.d.ts b/types/lodash/collection/find.d.ts index d4593ac9d3..612a337355 100644 --- a/types/lodash/collection/find.d.ts +++ b/types/lodash/collection/find.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Iterates over elements of collection, returning the first element predicate returns truthy for. diff --git a/types/lodash/collection/findLast.d.ts b/types/lodash/collection/findLast.d.ts index 43b3dfbd28..c18f28265d 100644 --- a/types/lodash/collection/findLast.d.ts +++ b/types/lodash/collection/findLast.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.find except that it iterates over elements of a collection from diff --git a/types/lodash/collection/flatMap.d.ts b/types/lodash/collection/flatMap.d.ts index 8eec7ddea1..453abf37f2 100644 --- a/types/lodash/collection/flatMap.d.ts +++ b/types/lodash/collection/flatMap.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of flattened values by running each element in collection through iteratee diff --git a/types/lodash/collection/flatMapDeep.d.ts b/types/lodash/collection/flatMapDeep.d.ts index d15ce69070..63d1750b0e 100644 --- a/types/lodash/collection/flatMapDeep.d.ts +++ b/types/lodash/collection/flatMapDeep.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.flatMap` except that it recursively flattens the diff --git a/types/lodash/collection/flatMapDepth.d.ts b/types/lodash/collection/flatMapDepth.d.ts index fd8004dc1a..b7b8abba4e 100644 --- a/types/lodash/collection/flatMapDepth.d.ts +++ b/types/lodash/collection/flatMapDepth.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.flatMap` except that it recursively flattens the diff --git a/types/lodash/collection/forEach.d.ts b/types/lodash/collection/forEach.d.ts index 8ede8dfc15..847f95ad58 100644 --- a/types/lodash/collection/forEach.d.ts +++ b/types/lodash/collection/forEach.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Iterates over elements of collection invoking iteratee for each element. The iteratee is bound to thisArg diff --git a/types/lodash/collection/forEachRight.d.ts b/types/lodash/collection/forEachRight.d.ts index 67c3ec3b8b..e6820d743c 100644 --- a/types/lodash/collection/forEachRight.d.ts +++ b/types/lodash/collection/forEachRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.forEach except that it iterates over elements of collection from right to left. diff --git a/types/lodash/collection/groupBy.d.ts b/types/lodash/collection/groupBy.d.ts index 192154de0a..4bd1da4674 100644 --- a/types/lodash/collection/groupBy.d.ts +++ b/types/lodash/collection/groupBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object composed of keys generated from the results of running each element of collection through diff --git a/types/lodash/collection/includes.d.ts b/types/lodash/collection/includes.d.ts index 76fcd79a6f..94eae4491a 100644 --- a/types/lodash/collection/includes.d.ts +++ b/types/lodash/collection/includes.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if target is in collection using SameValueZero for equality comparisons. If fromIndex is negative, diff --git a/types/lodash/collection/invokeMap.d.ts b/types/lodash/collection/invokeMap.d.ts index 73c283fbde..d780e5b944 100644 --- a/types/lodash/collection/invokeMap.d.ts +++ b/types/lodash/collection/invokeMap.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Invokes the method named by methodName on each element in the collection returning diff --git a/types/lodash/collection/keyBy.d.ts b/types/lodash/collection/keyBy.d.ts index 47f2c35cc5..7214537a68 100644 --- a/types/lodash/collection/keyBy.d.ts +++ b/types/lodash/collection/keyBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object composed of keys generated from the results of running each element of collection through diff --git a/types/lodash/collection/map.d.ts b/types/lodash/collection/map.d.ts index 493f6300b6..798cec1dd8 100644 --- a/types/lodash/collection/map.d.ts +++ b/types/lodash/collection/map.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of values by running each element in collection through iteratee. The iteratee is bound to diff --git a/types/lodash/collection/orderBy.d.ts b/types/lodash/collection/orderBy.d.ts index bac15cefa4..fea3d82755 100644 --- a/types/lodash/collection/orderBy.d.ts +++ b/types/lodash/collection/orderBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.sortBy` except that it allows specifying the sort diff --git a/types/lodash/collection/partition.d.ts b/types/lodash/collection/partition.d.ts index e293220770..cf9f69d954 100644 --- a/types/lodash/collection/partition.d.ts +++ b/types/lodash/collection/partition.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, diff --git a/types/lodash/collection/reduce.d.ts b/types/lodash/collection/reduce.d.ts index f924a149bb..31d7661c2e 100644 --- a/types/lodash/collection/reduce.d.ts +++ b/types/lodash/collection/reduce.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Reduces a collection to a value which is the accumulated result of running each diff --git a/types/lodash/collection/reduceRight.d.ts b/types/lodash/collection/reduceRight.d.ts index d250def9a6..fb2b74da16 100644 --- a/types/lodash/collection/reduceRight.d.ts +++ b/types/lodash/collection/reduceRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.reduce except that it iterates over elements of a collection from diff --git a/types/lodash/collection/reject.d.ts b/types/lodash/collection/reject.d.ts index a475baf1ee..4e051b9504 100644 --- a/types/lodash/collection/reject.d.ts +++ b/types/lodash/collection/reject.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The opposite of _.filter; this method returns the elements of collection that predicate does not return diff --git a/types/lodash/collection/sample.d.ts b/types/lodash/collection/sample.d.ts index f078711033..48b0aac49b 100644 --- a/types/lodash/collection/sample.d.ts +++ b/types/lodash/collection/sample.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets a random element from collection. diff --git a/types/lodash/collection/sampleSize.d.ts b/types/lodash/collection/sampleSize.d.ts index e21ed6eea4..fb9b7fb97a 100644 --- a/types/lodash/collection/sampleSize.d.ts +++ b/types/lodash/collection/sampleSize.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets n random elements at unique keys from collection up to the size of collection. diff --git a/types/lodash/collection/shuffle.d.ts b/types/lodash/collection/shuffle.d.ts index 0c91dc097d..070d2923a6 100644 --- a/types/lodash/collection/shuffle.d.ts +++ b/types/lodash/collection/shuffle.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. diff --git a/types/lodash/collection/size.d.ts b/types/lodash/collection/size.d.ts index 6653becb5f..52c78ee3a9 100644 --- a/types/lodash/collection/size.d.ts +++ b/types/lodash/collection/size.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets the size of collection by returning its length for array-like values or the number of own enumerable diff --git a/types/lodash/collection/some.d.ts b/types/lodash/collection/some.d.ts index b6393023ec..c7a90b1c9b 100644 --- a/types/lodash/collection/some.d.ts +++ b/types/lodash/collection/some.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate diff --git a/types/lodash/collection/sortBy.d.ts b/types/lodash/collection/sortBy.d.ts index c2bcdcf9e8..a192254250 100644 --- a/types/lodash/collection/sortBy.d.ts +++ b/types/lodash/collection/sortBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of elements, sorted in ascending order by the results of diff --git a/types/lodash/common/common.d.ts b/types/lodash/common/common.d.ts index 930525f1f0..88a5741ae1 100644 --- a/types/lodash/common/common.d.ts +++ b/types/lodash/common/common.d.ts @@ -1,6 +1,7 @@ -declare let _: _.LoDashStatic; -type PartialObject = Partial; -declare namespace _ { +import * as _ from "../index"; +type GlobalPartial = Partial; +declare module "../index" { + type PartialObject = GlobalPartial; type Many = T | T[]; interface LoDashStatic { /** diff --git a/types/lodash/date/now.d.ts b/types/lodash/date/now.d.ts index 1213cc0ea1..39a01dd654 100644 --- a/types/lodash/date/now.d.ts +++ b/types/lodash/date/now.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC). diff --git a/types/lodash/function/after.d.ts b/types/lodash/function/after.d.ts index 4585a1a87d..b86f417556 100644 --- a/types/lodash/function/after.d.ts +++ b/types/lodash/function/after.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The opposite of _.before; this method creates a function that invokes func once it’s called n or more times. diff --git a/types/lodash/function/ary.d.ts b/types/lodash/function/ary.d.ts index 3e81a1b72c..de384c8026 100644 --- a/types/lodash/function/ary.d.ts +++ b/types/lodash/function/ary.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that accepts up to n arguments ignoring any additional arguments. diff --git a/types/lodash/function/before.d.ts b/types/lodash/function/before.d.ts index 3d2df831da..5d67a70be1 100644 --- a/types/lodash/function/before.d.ts +++ b/types/lodash/function/before.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes func, with the this binding and arguments of the created function, while diff --git a/types/lodash/function/bind.d.ts b/types/lodash/function/bind.d.ts index 73311a37b7..3f708a1f91 100644 --- a/types/lodash/function/bind.d.ts +++ b/types/lodash/function/bind.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface FunctionBind { placeholder: any; diff --git a/types/lodash/function/bindKey.d.ts b/types/lodash/function/bindKey.d.ts index 8cf23ae4a1..9e3e547c7f 100644 --- a/types/lodash/function/bindKey.d.ts +++ b/types/lodash/function/bindKey.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface FunctionBindKey { placeholder: any; diff --git a/types/lodash/function/curry.d.ts b/types/lodash/function/curry.d.ts index 5810d89a9b..523cdee399 100644 --- a/types/lodash/function/curry.d.ts +++ b/types/lodash/function/curry.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning diff --git a/types/lodash/function/curryRight.d.ts b/types/lodash/function/curryRight.d.ts index 73249d8fe8..473a9e039b 100644 --- a/types/lodash/function/curryRight.d.ts +++ b/types/lodash/function/curryRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight diff --git a/types/lodash/function/debounce.d.ts b/types/lodash/function/debounce.d.ts index ef3adff643..286c516ddd 100644 --- a/types/lodash/function/debounce.d.ts +++ b/types/lodash/function/debounce.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface DebounceSettings { /** * Specify invoking on the leading edge of the timeout. diff --git a/types/lodash/function/defer.d.ts b/types/lodash/function/defer.d.ts index 15488207c9..5bf02bf1b8 100644 --- a/types/lodash/function/defer.d.ts +++ b/types/lodash/function/defer.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to diff --git a/types/lodash/function/delay.d.ts b/types/lodash/function/delay.d.ts index 4273689166..8ccf40d12c 100644 --- a/types/lodash/function/delay.d.ts +++ b/types/lodash/function/delay.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Invokes func after wait milliseconds. Any additional arguments are provided to func when it’s invoked. diff --git a/types/lodash/function/flip.d.ts b/types/lodash/function/flip.d.ts index 428dcf774d..bad49a2022 100644 --- a/types/lodash/function/flip.d.ts +++ b/types/lodash/function/flip.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes `func` with arguments reversed. diff --git a/types/lodash/function/memoize.d.ts b/types/lodash/function/memoize.d.ts index 88257bd8ce..eb7be00430 100644 --- a/types/lodash/function/memoize.d.ts +++ b/types/lodash/function/memoize.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface MemoizedFunction { cache: MapCache; } diff --git a/types/lodash/function/negate.d.ts b/types/lodash/function/negate.d.ts index b42e395cf6..b826db7368 100644 --- a/types/lodash/function/negate.d.ts +++ b/types/lodash/function/negate.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that negates the result of the predicate func. The func predicate is invoked with diff --git a/types/lodash/function/once.d.ts b/types/lodash/function/once.d.ts index a49423171f..cd1d0e8554 100644 --- a/types/lodash/function/once.d.ts +++ b/types/lodash/function/once.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that is restricted to invoking func once. Repeat calls to the function return the value diff --git a/types/lodash/function/overArgs.d.ts b/types/lodash/function/overArgs.d.ts index 6cc5cf6c41..7267540ce4 100644 --- a/types/lodash/function/overArgs.d.ts +++ b/types/lodash/function/overArgs.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that runs each argument through a corresponding transform function. diff --git a/types/lodash/function/partial.d.ts b/types/lodash/function/partial.d.ts index 1d15995cea..047c5ce724 100644 --- a/types/lodash/function/partial.d.ts +++ b/types/lodash/function/partial.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that, when called, invokes func with any additional partial arguments diff --git a/types/lodash/function/partialRight.d.ts b/types/lodash/function/partialRight.d.ts index e0280262e8..bacbd88440 100644 --- a/types/lodash/function/partialRight.d.ts +++ b/types/lodash/function/partialRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.partial except that partial arguments are appended to those provided diff --git a/types/lodash/function/rearg.d.ts b/types/lodash/function/rearg.d.ts index bcabbbb62b..829dbebf5e 100644 --- a/types/lodash/function/rearg.d.ts +++ b/types/lodash/function/rearg.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes func with arguments arranged according to the specified indexes where the diff --git a/types/lodash/function/rest.d.ts b/types/lodash/function/rest.d.ts index 738f206967..d3d7689f63 100644 --- a/types/lodash/function/rest.d.ts +++ b/types/lodash/function/rest.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes func with the this binding of the created function and arguments from start diff --git a/types/lodash/function/spread.d.ts b/types/lodash/function/spread.d.ts index 36aab5fe33..2828089805 100644 --- a/types/lodash/function/spread.d.ts +++ b/types/lodash/function/spread.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes func with the this binding of the created function and an array of arguments diff --git a/types/lodash/function/throttle.d.ts b/types/lodash/function/throttle.d.ts index 37a1c60bec..c2661ec0e3 100644 --- a/types/lodash/function/throttle.d.ts +++ b/types/lodash/function/throttle.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface ThrottleSettings { /** * If you'd like to disable the leading-edge call, pass this as false. diff --git a/types/lodash/function/unary.d.ts b/types/lodash/function/unary.d.ts index 810f359a6c..145dbefba2 100644 --- a/types/lodash/function/unary.d.ts +++ b/types/lodash/function/unary.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that accepts up to one argument, ignoring any diff --git a/types/lodash/function/wrap.d.ts b/types/lodash/function/wrap.d.ts index f00a27fc74..b5636b1c25 100644 --- a/types/lodash/function/wrap.d.ts +++ b/types/lodash/function/wrap.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that provides value to the wrapper function as its first argument. Any additional diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index aeebd3b5c2..fd421681c1 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -355,6 +355,12 @@ export = _; export as namespace _; +declare const _: _.LoDashStatic; +declare namespace _ { + // tslint:disable-next-line no-empty-interface (This will be augmented) + interface LoDashStatic {} +} + // Backward compatibility with --target es5 declare global { // tslint:disable-next-line:no-empty-interface diff --git a/types/lodash/lang/castArray.d.ts b/types/lodash/lang/castArray.d.ts index 33b7d83771..8e79155940 100644 --- a/types/lodash/lang/castArray.d.ts +++ b/types/lodash/lang/castArray.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Casts value as an array if it’s not one. diff --git a/types/lodash/lang/clone.d.ts b/types/lodash/lang/clone.d.ts index 5e3405e68a..9bfd32f5c7 100644 --- a/types/lodash/lang/clone.d.ts +++ b/types/lodash/lang/clone.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a shallow clone of value. diff --git a/types/lodash/lang/cloneDeep.d.ts b/types/lodash/lang/cloneDeep.d.ts index 73099ff92a..9390ece09e 100644 --- a/types/lodash/lang/cloneDeep.d.ts +++ b/types/lodash/lang/cloneDeep.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.clone except that it recursively clones value. diff --git a/types/lodash/lang/cloneDeepWith.d.ts b/types/lodash/lang/cloneDeepWith.d.ts index 7805a598f0..1cd2339889 100644 --- a/types/lodash/lang/cloneDeepWith.d.ts +++ b/types/lodash/lang/cloneDeepWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type CloneDeepWithCustomizer = (value: any, key: number | string | undefined, object: TObject | undefined, stack: any) => any; interface LoDashStatic { diff --git a/types/lodash/lang/cloneWith.d.ts b/types/lodash/lang/cloneWith.d.ts index 2135d0ed53..f091ba7710 100644 --- a/types/lodash/lang/cloneWith.d.ts +++ b/types/lodash/lang/cloneWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type CloneWithCustomizer = (value: TValue, key: number | string | undefined, object: any, stack: any) => TResult; interface LoDashStatic { diff --git a/types/lodash/lang/conformsTo.d.ts b/types/lodash/lang/conformsTo.d.ts index 859186f97c..15e11ddf34 100644 --- a/types/lodash/lang/conformsTo.d.ts +++ b/types/lodash/lang/conformsTo.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** diff --git a/types/lodash/lang/eq.d.ts b/types/lodash/lang/eq.d.ts index 08d4fb9497..f70867eb97 100644 --- a/types/lodash/lang/eq.d.ts +++ b/types/lodash/lang/eq.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) diff --git a/types/lodash/lang/gt.d.ts b/types/lodash/lang/gt.d.ts index 6d63801d1e..0f5e0cf20e 100644 --- a/types/lodash/lang/gt.d.ts +++ b/types/lodash/lang/gt.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is greater than other. diff --git a/types/lodash/lang/gte.d.ts b/types/lodash/lang/gte.d.ts index 43887befcd..24e9938aa2 100644 --- a/types/lodash/lang/gte.d.ts +++ b/types/lodash/lang/gte.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is greater than or equal to other. diff --git a/types/lodash/lang/isArguments.d.ts b/types/lodash/lang/isArguments.d.ts index e2549b24f6..3d4be77f98 100644 --- a/types/lodash/lang/isArguments.d.ts +++ b/types/lodash/lang/isArguments.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as an arguments object. diff --git a/types/lodash/lang/isArray.d.ts b/types/lodash/lang/isArray.d.ts index 0218c836d8..7949e6adf5 100644 --- a/types/lodash/lang/isArray.d.ts +++ b/types/lodash/lang/isArray.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as an Array object. diff --git a/types/lodash/lang/isArrayBuffer.d.ts b/types/lodash/lang/isArrayBuffer.d.ts index c6e9d8cd05..a7033110c1 100644 --- a/types/lodash/lang/isArrayBuffer.d.ts +++ b/types/lodash/lang/isArrayBuffer.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as an ArrayBuffer object. diff --git a/types/lodash/lang/isArrayLike.d.ts b/types/lodash/lang/isArrayLike.d.ts index edf5e419bd..0f3a924b52 100644 --- a/types/lodash/lang/isArrayLike.d.ts +++ b/types/lodash/lang/isArrayLike.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `value` is array-like. A value is considered array-like if it's diff --git a/types/lodash/lang/isArrayLikeObject.d.ts b/types/lodash/lang/isArrayLikeObject.d.ts index acdc7b9a50..d53566feeb 100644 --- a/types/lodash/lang/isArrayLikeObject.d.ts +++ b/types/lodash/lang/isArrayLikeObject.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.isArrayLike` except that it also checks if `value` diff --git a/types/lodash/lang/isBoolean.d.ts b/types/lodash/lang/isBoolean.d.ts index fea535c696..db2d2230b7 100644 --- a/types/lodash/lang/isBoolean.d.ts +++ b/types/lodash/lang/isBoolean.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a boolean primitive or object. diff --git a/types/lodash/lang/isBuffer.d.ts b/types/lodash/lang/isBuffer.d.ts index 333fef2a20..79fe9f479d 100644 --- a/types/lodash/lang/isBuffer.d.ts +++ b/types/lodash/lang/isBuffer.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is a buffer. diff --git a/types/lodash/lang/isDate.d.ts b/types/lodash/lang/isDate.d.ts index f220b1fa66..e02811097a 100644 --- a/types/lodash/lang/isDate.d.ts +++ b/types/lodash/lang/isDate.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a Date object. diff --git a/types/lodash/lang/isElement.d.ts b/types/lodash/lang/isElement.d.ts index 2e0bafd105..049435dace 100644 --- a/types/lodash/lang/isElement.d.ts +++ b/types/lodash/lang/isElement.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is a DOM element. diff --git a/types/lodash/lang/isEmpty.d.ts b/types/lodash/lang/isEmpty.d.ts index c19139b8d3..e8c44dec8f 100644 --- a/types/lodash/lang/isEmpty.d.ts +++ b/types/lodash/lang/isEmpty.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is empty. A value is considered empty unless it’s an arguments object, array, string, or diff --git a/types/lodash/lang/isEqual.d.ts b/types/lodash/lang/isEqual.d.ts index c8d9449d45..9741781d08 100644 --- a/types/lodash/lang/isEqual.d.ts +++ b/types/lodash/lang/isEqual.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Performs a deep comparison between two values to determine if they are diff --git a/types/lodash/lang/isEqualWith.d.ts b/types/lodash/lang/isEqualWith.d.ts index 8e0e41a52c..a87919d3c4 100644 --- a/types/lodash/lang/isEqualWith.d.ts +++ b/types/lodash/lang/isEqualWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type IsEqualCustomizer = (value: any, other: any, indexOrKey: PropertyName | undefined, parent: any, otherParent: any, stack: any) => boolean|undefined; interface LoDashStatic { diff --git a/types/lodash/lang/isError.d.ts b/types/lodash/lang/isError.d.ts index a33c934906..0b04dc63b7 100644 --- a/types/lodash/lang/isError.d.ts +++ b/types/lodash/lang/isError.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError diff --git a/types/lodash/lang/isFinite.d.ts b/types/lodash/lang/isFinite.d.ts index 8fb984b178..023eed061e 100644 --- a/types/lodash/lang/isFinite.d.ts +++ b/types/lodash/lang/isFinite.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is a finite primitive number. diff --git a/types/lodash/lang/isFunction.d.ts b/types/lodash/lang/isFunction.d.ts index 067da708b3..0b4c539721 100644 --- a/types/lodash/lang/isFunction.d.ts +++ b/types/lodash/lang/isFunction.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is a callable function. diff --git a/types/lodash/lang/isInteger.d.ts b/types/lodash/lang/isInteger.d.ts index 125575c051..6c1c85a4b5 100644 --- a/types/lodash/lang/isInteger.d.ts +++ b/types/lodash/lang/isInteger.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `value` is an integer. diff --git a/types/lodash/lang/isLength.d.ts b/types/lodash/lang/isLength.d.ts index a0449ef93c..2045c8642b 100644 --- a/types/lodash/lang/isLength.d.ts +++ b/types/lodash/lang/isLength.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `value` is a valid array-like length. diff --git a/types/lodash/lang/isMap.d.ts b/types/lodash/lang/isMap.d.ts index 9ce44582a1..7ff700592f 100644 --- a/types/lodash/lang/isMap.d.ts +++ b/types/lodash/lang/isMap.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a Map object. diff --git a/types/lodash/lang/isMatch.d.ts b/types/lodash/lang/isMatch.d.ts index 199a64c2cd..4ec05e5651 100644 --- a/types/lodash/lang/isMatch.d.ts +++ b/types/lodash/lang/isMatch.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type isMatchCustomizer = (value: any, other: any, indexOrKey?: PropertyName) => boolean; interface LoDashStatic { diff --git a/types/lodash/lang/isMatchWith.d.ts b/types/lodash/lang/isMatchWith.d.ts index 516b9b9947..8ed28e0ca9 100644 --- a/types/lodash/lang/isMatchWith.d.ts +++ b/types/lodash/lang/isMatchWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName) => boolean; interface LoDashStatic { diff --git a/types/lodash/lang/isNaN.d.ts b/types/lodash/lang/isNaN.d.ts index 7ac79bc794..cfc6466d89 100644 --- a/types/lodash/lang/isNaN.d.ts +++ b/types/lodash/lang/isNaN.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is NaN. diff --git a/types/lodash/lang/isNative.d.ts b/types/lodash/lang/isNative.d.ts index a1c0e2ff30..8cc7682e08 100644 --- a/types/lodash/lang/isNative.d.ts +++ b/types/lodash/lang/isNative.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is a native function. diff --git a/types/lodash/lang/isNil.d.ts b/types/lodash/lang/isNil.d.ts index d44c1f3893..19f0d0510d 100644 --- a/types/lodash/lang/isNil.d.ts +++ b/types/lodash/lang/isNil.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `value` is `null` or `undefined`. diff --git a/types/lodash/lang/isNull.d.ts b/types/lodash/lang/isNull.d.ts index 7978835f2d..d75bc31dbe 100644 --- a/types/lodash/lang/isNull.d.ts +++ b/types/lodash/lang/isNull.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is null. diff --git a/types/lodash/lang/isNumber.d.ts b/types/lodash/lang/isNumber.d.ts index 1bfd01db46..b149f779e9 100644 --- a/types/lodash/lang/isNumber.d.ts +++ b/types/lodash/lang/isNumber.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a Number primitive or object. diff --git a/types/lodash/lang/isObject.d.ts b/types/lodash/lang/isObject.d.ts index c9b47124a0..760d08bcf5 100644 --- a/types/lodash/lang/isObject.d.ts +++ b/types/lodash/lang/isObject.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), diff --git a/types/lodash/lang/isObjectLike.d.ts b/types/lodash/lang/isObjectLike.d.ts index dfb1d20a1a..1f59f71035 100644 --- a/types/lodash/lang/isObjectLike.d.ts +++ b/types/lodash/lang/isObjectLike.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `value` is object-like. A value is object-like if it's not `null` diff --git a/types/lodash/lang/isPlainObject.d.ts b/types/lodash/lang/isPlainObject.d.ts index e9708075ef..48031c8aeb 100644 --- a/types/lodash/lang/isPlainObject.d.ts +++ b/types/lodash/lang/isPlainObject.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is a plain object, that is, an object created by the Object constructor or one with a diff --git a/types/lodash/lang/isRegExp.d.ts b/types/lodash/lang/isRegExp.d.ts index 7e60fc4012..5d63d6bed1 100644 --- a/types/lodash/lang/isRegExp.d.ts +++ b/types/lodash/lang/isRegExp.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a RegExp object. diff --git a/types/lodash/lang/isSafeInteger.d.ts b/types/lodash/lang/isSafeInteger.d.ts index 3c51308410..c1ba912c76 100644 --- a/types/lodash/lang/isSafeInteger.d.ts +++ b/types/lodash/lang/isSafeInteger.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 diff --git a/types/lodash/lang/isSet.d.ts b/types/lodash/lang/isSet.d.ts index ae92840e4e..173f8aa8b8 100644 --- a/types/lodash/lang/isSet.d.ts +++ b/types/lodash/lang/isSet.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a Set object. diff --git a/types/lodash/lang/isString.d.ts b/types/lodash/lang/isString.d.ts index dff362cde4..739f8730a8 100644 --- a/types/lodash/lang/isString.d.ts +++ b/types/lodash/lang/isString.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a String primitive or object. diff --git a/types/lodash/lang/isSymbol.d.ts b/types/lodash/lang/isSymbol.d.ts index cd6c142ea2..7831c3d4b2 100644 --- a/types/lodash/lang/isSymbol.d.ts +++ b/types/lodash/lang/isSymbol.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `value` is classified as a `Symbol` primitive or object. diff --git a/types/lodash/lang/isTypedArray.d.ts b/types/lodash/lang/isTypedArray.d.ts index 29309c7ced..fc55e1b06a 100644 --- a/types/lodash/lang/isTypedArray.d.ts +++ b/types/lodash/lang/isTypedArray.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a typed array. diff --git a/types/lodash/lang/isUndefined.d.ts b/types/lodash/lang/isUndefined.d.ts index 02a5697b74..1803b36c29 100644 --- a/types/lodash/lang/isUndefined.d.ts +++ b/types/lodash/lang/isUndefined.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is undefined. diff --git a/types/lodash/lang/isWeakMap.d.ts b/types/lodash/lang/isWeakMap.d.ts index b6f009c535..36251720a9 100644 --- a/types/lodash/lang/isWeakMap.d.ts +++ b/types/lodash/lang/isWeakMap.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a WeakMap object. diff --git a/types/lodash/lang/isWeakSet.d.ts b/types/lodash/lang/isWeakSet.d.ts index cb06d4c9b5..ce523a098d 100644 --- a/types/lodash/lang/isWeakSet.d.ts +++ b/types/lodash/lang/isWeakSet.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is classified as a WeakSet object. diff --git a/types/lodash/lang/lt.d.ts b/types/lodash/lang/lt.d.ts index a9ce5e6c4d..ff991eb9a7 100644 --- a/types/lodash/lang/lt.d.ts +++ b/types/lodash/lang/lt.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is less than other. diff --git a/types/lodash/lang/lte.d.ts b/types/lodash/lang/lte.d.ts index b8fac76627..21a1710da3 100644 --- a/types/lodash/lang/lte.d.ts +++ b/types/lodash/lang/lte.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if value is less than or equal to other. diff --git a/types/lodash/lang/toArray.d.ts b/types/lodash/lang/toArray.d.ts index 6dd5ef8e27..be11eecb6d 100644 --- a/types/lodash/lang/toArray.d.ts +++ b/types/lodash/lang/toArray.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts value to an array. diff --git a/types/lodash/lang/toFinite.d.ts b/types/lodash/lang/toFinite.d.ts index 0d14f49715..53a913e212 100644 --- a/types/lodash/lang/toFinite.d.ts +++ b/types/lodash/lang/toFinite.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `value` to a finite number. diff --git a/types/lodash/lang/toInteger.d.ts b/types/lodash/lang/toInteger.d.ts index 7e0b865078..2fe3f91f5d 100644 --- a/types/lodash/lang/toInteger.d.ts +++ b/types/lodash/lang/toInteger.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `value` to an integer. diff --git a/types/lodash/lang/toLength.d.ts b/types/lodash/lang/toLength.d.ts index dcc84d78ee..4b3629eccd 100644 --- a/types/lodash/lang/toLength.d.ts +++ b/types/lodash/lang/toLength.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `value` to an integer suitable for use as the length of an diff --git a/types/lodash/lang/toNumber.d.ts b/types/lodash/lang/toNumber.d.ts index 76c0032391..5632b018f1 100644 --- a/types/lodash/lang/toNumber.d.ts +++ b/types/lodash/lang/toNumber.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `value` to a number. diff --git a/types/lodash/lang/toPlainObject.d.ts b/types/lodash/lang/toPlainObject.d.ts index 9ae43dcf62..74ede5011d 100644 --- a/types/lodash/lang/toPlainObject.d.ts +++ b/types/lodash/lang/toPlainObject.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts value to a plain object flattening inherited enumerable properties of value to own properties diff --git a/types/lodash/lang/toSafeInteger.d.ts b/types/lodash/lang/toSafeInteger.d.ts index 88e517d42c..774492cbe0 100644 --- a/types/lodash/lang/toSafeInteger.d.ts +++ b/types/lodash/lang/toSafeInteger.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `value` to a safe integer. A safe integer can be compared and diff --git a/types/lodash/lang/toString.d.ts b/types/lodash/lang/toString.d.ts index 1b461d1217..2a0de1e865 100644 --- a/types/lodash/lang/toString.d.ts +++ b/types/lodash/lang/toString.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `value` to a string if it's not one. An empty string is returned diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 77cc1984eb..9baaa64815 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -3192,7 +3192,7 @@ namespace TestXor { } // _.zip -namespace TestZip { +{ let array: TResult[] | null | undefined = [] as any; let list: _.List | null | undefined = [] as any; @@ -3206,6 +3206,8 @@ namespace TestZip { result = _.zip(list); result = _.zip(list, array); result = _.zip(list, array, list); + + result = _.zip(list, array, list, array, list, array); } { @@ -3227,6 +3229,12 @@ namespace TestZip { result = _(list).chain().zip(array); result = _(list).chain().zip(array, list); } + + { + _.zip([1, 2], [3, 4]); // $ExpectType [number, number][] + _.zip([1, 2], ["a", "b"]); // $ExpectType [number, string][] + _.zip([1, 2], ["a", "b"], [true, false]); // $ExpectType [number, string, boolean][] + } } // _.zipObject @@ -3359,18 +3367,9 @@ namespace TestZipObject { } // _.zipWith -namespace TestZipWith { +{ type TestZipWithFn = (a1: number, a2: number) => number; - { - let result: number[][]; - result = _.zipWith([1, 2]); - result = _.zipWith([1, 2], [3, 4], [5, 6]); - result = _([1, 2]).zipWith().value(); - result = _([1, 2]).zipWith([3, 4], [5, 6]).value(); - result = _.chain([1, 2]).zipWith().value(); - result = _.chain([1, 2]).zipWith([3, 4], [5, 6]).value(); - } { let result: number[]; @@ -3511,6 +3510,19 @@ namespace TestZipWith { group; // $ExpectType number[] return 1; }).value(); + + result = _([1, 2]).zipWith(["a", "b"], (value1, value2) => { + value1; // $ExpectType number + value2; // $ExpectType string + return 1; + }).value(); + + result = _([1, 2]).zipWith(["a", "b"], [true, false], (value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType string + value3; // $ExpectType boolean + return 1; + }).value(); } } diff --git a/types/lodash/math/add.d.ts b/types/lodash/math/add.d.ts index 5e026fc671..bed1f749f4 100644 --- a/types/lodash/math/add.d.ts +++ b/types/lodash/math/add.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Adds two numbers. diff --git a/types/lodash/math/ceil.d.ts b/types/lodash/math/ceil.d.ts index 1977160c4e..4fcca60b3f 100644 --- a/types/lodash/math/ceil.d.ts +++ b/types/lodash/math/ceil.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Calculates n rounded up to precision. diff --git a/types/lodash/math/divide.d.ts b/types/lodash/math/divide.d.ts index 5af529f97f..7a301014a4 100644 --- a/types/lodash/math/divide.d.ts +++ b/types/lodash/math/divide.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Divide two numbers. diff --git a/types/lodash/math/floor.d.ts b/types/lodash/math/floor.d.ts index db8d35def3..edd71c16d4 100644 --- a/types/lodash/math/floor.d.ts +++ b/types/lodash/math/floor.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Calculates n rounded down to precision. diff --git a/types/lodash/math/max.d.ts b/types/lodash/math/max.d.ts index 8a6108ab16..426c4c0fb7 100644 --- a/types/lodash/math/max.d.ts +++ b/types/lodash/math/max.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Computes the maximum value of `array`. If `array` is empty or falsey diff --git a/types/lodash/math/maxBy.d.ts b/types/lodash/math/maxBy.d.ts index 1b57efb78c..03be231888 100644 --- a/types/lodash/math/maxBy.d.ts +++ b/types/lodash/math/maxBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.max` except that it accepts `iteratee` which is diff --git a/types/lodash/math/mean.d.ts b/types/lodash/math/mean.d.ts index ea2f39a952..a67a1d7c33 100644 --- a/types/lodash/math/mean.d.ts +++ b/types/lodash/math/mean.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Computes the mean of the values in `array`. diff --git a/types/lodash/math/meanBy.d.ts b/types/lodash/math/meanBy.d.ts index c3ff1fded4..03bca381b8 100644 --- a/types/lodash/math/meanBy.d.ts +++ b/types/lodash/math/meanBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Computes the mean of the provided propties of the objects in the `array` diff --git a/types/lodash/math/min.d.ts b/types/lodash/math/min.d.ts index 6d0bc8ab60..be8e1c7caa 100644 --- a/types/lodash/math/min.d.ts +++ b/types/lodash/math/min.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Computes the minimum value of `array`. If `array` is empty or falsey diff --git a/types/lodash/math/minBy.d.ts b/types/lodash/math/minBy.d.ts index 2e70263af8..1ddbe31c3a 100644 --- a/types/lodash/math/minBy.d.ts +++ b/types/lodash/math/minBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.min` except that it accepts `iteratee` which is diff --git a/types/lodash/math/multiply.d.ts b/types/lodash/math/multiply.d.ts index 6381b4f2d8..c86a73ec98 100644 --- a/types/lodash/math/multiply.d.ts +++ b/types/lodash/math/multiply.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Multiply two numbers. diff --git a/types/lodash/math/round.d.ts b/types/lodash/math/round.d.ts index b3bc0dcaa1..b4e0397220 100644 --- a/types/lodash/math/round.d.ts +++ b/types/lodash/math/round.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Calculates n rounded to precision. diff --git a/types/lodash/math/subtract.d.ts b/types/lodash/math/subtract.d.ts index 0c1ddabcca..653b07a586 100644 --- a/types/lodash/math/subtract.d.ts +++ b/types/lodash/math/subtract.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Subtract two numbers. diff --git a/types/lodash/math/sum.d.ts b/types/lodash/math/sum.d.ts index de92ef1f0d..5b4499f0f5 100644 --- a/types/lodash/math/sum.d.ts +++ b/types/lodash/math/sum.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Computes the sum of the values in `array`. diff --git a/types/lodash/math/sumBy.d.ts b/types/lodash/math/sumBy.d.ts index 05e836325a..dbb537283c 100644 --- a/types/lodash/math/sumBy.d.ts +++ b/types/lodash/math/sumBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.sum` except that it accepts `iteratee` which is diff --git a/types/lodash/number/clamp.d.ts b/types/lodash/number/clamp.d.ts index e7aff8c4ae..1ef3321b09 100644 --- a/types/lodash/number/clamp.d.ts +++ b/types/lodash/number/clamp.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Clamps `number` within the inclusive `lower` and `upper` bounds. diff --git a/types/lodash/number/inRange.d.ts b/types/lodash/number/inRange.d.ts index 0e3fd3ed8e..499d71e8de 100644 --- a/types/lodash/number/inRange.d.ts +++ b/types/lodash/number/inRange.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if n is between start and up to but not including, end. If end is not specified it’s set to start diff --git a/types/lodash/number/random.d.ts b/types/lodash/number/random.d.ts index 112e579896..621f29ffe9 100644 --- a/types/lodash/number/random.d.ts +++ b/types/lodash/number/random.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Produces a random number between min and max (inclusive). If only one argument is provided a number between diff --git a/types/lodash/object/assign.d.ts b/types/lodash/object/assign.d.ts index e329c27ab5..e4a03fb995 100644 --- a/types/lodash/object/assign.d.ts +++ b/types/lodash/object/assign.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Assigns own enumerable properties of source objects to the destination diff --git a/types/lodash/object/assignIn.d.ts b/types/lodash/object/assignIn.d.ts index a5981e75a0..1f877fb8af 100644 --- a/types/lodash/object/assignIn.d.ts +++ b/types/lodash/object/assignIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.assign` except that it iterates over own and diff --git a/types/lodash/object/assignInWith.d.ts b/types/lodash/object/assignInWith.d.ts index 85a6311cda..10a4c7297d 100644 --- a/types/lodash/object/assignInWith.d.ts +++ b/types/lodash/object/assignInWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type AssignCustomizer = (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; interface LoDashStatic { diff --git a/types/lodash/object/assignWith.d.ts b/types/lodash/object/assignWith.d.ts index e31cd8d9bc..e26494a3d6 100644 --- a/types/lodash/object/assignWith.d.ts +++ b/types/lodash/object/assignWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.assign` except that it accepts `customizer` which diff --git a/types/lodash/object/at.d.ts b/types/lodash/object/at.d.ts index d6046e597d..a2b0bb926a 100644 --- a/types/lodash/object/at.d.ts +++ b/types/lodash/object/at.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of elements corresponding to the given keys, or indexes, of collection. Keys may be diff --git a/types/lodash/object/create.d.ts b/types/lodash/object/create.d.ts index 025b4dbe66..f743b15022 100644 --- a/types/lodash/object/create.d.ts +++ b/types/lodash/object/create.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object that inherits from the given prototype object. If a properties object is provided its own diff --git a/types/lodash/object/defaults.d.ts b/types/lodash/object/defaults.d.ts index ea53dbddc5..908d44f364 100644 --- a/types/lodash/object/defaults.d.ts +++ b/types/lodash/object/defaults.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Assigns own enumerable properties of source object(s) to the destination object for all destination diff --git a/types/lodash/object/defaultsDeep.d.ts b/types/lodash/object/defaultsDeep.d.ts index 89ba6b9b7e..72985f8fe7 100644 --- a/types/lodash/object/defaultsDeep.d.ts +++ b/types/lodash/object/defaultsDeep.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.defaults except that it recursively assigns default properties. diff --git a/types/lodash/object/entries.d.ts b/types/lodash/object/entries.d.ts index fee39417ae..11925694c4 100644 --- a/types/lodash/object/entries.d.ts +++ b/types/lodash/object/entries.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * @see _.toPairs diff --git a/types/lodash/object/entriesIn.d.ts b/types/lodash/object/entriesIn.d.ts index 8df728058d..d4a91f50bb 100644 --- a/types/lodash/object/entriesIn.d.ts +++ b/types/lodash/object/entriesIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * @see _.entriesIn diff --git a/types/lodash/object/extend.d.ts b/types/lodash/object/extend.d.ts index 17ce0232fa..d2a7a55200 100644 --- a/types/lodash/object/extend.d.ts +++ b/types/lodash/object/extend.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * @see _.extend diff --git a/types/lodash/object/extendWith.d.ts b/types/lodash/object/extendWith.d.ts index d02803cf32..9a6b1d1767 100644 --- a/types/lodash/object/extendWith.d.ts +++ b/types/lodash/object/extendWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * @see _.extendWith diff --git a/types/lodash/object/findKey.d.ts b/types/lodash/object/findKey.d.ts index 768c8aa3aa..f6fe55a2bd 100644 --- a/types/lodash/object/findKey.d.ts +++ b/types/lodash/object/findKey.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.find except that it returns the key of the first element predicate returns truthy for diff --git a/types/lodash/object/findLastKey.d.ts b/types/lodash/object/findLastKey.d.ts index e772dc3f80..53f224d943 100644 --- a/types/lodash/object/findLastKey.d.ts +++ b/types/lodash/object/findLastKey.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.findKey except that it iterates over elements of a collection in the opposite order. diff --git a/types/lodash/object/forIn.d.ts b/types/lodash/object/forIn.d.ts index a5e700aa22..a6f92dd690 100644 --- a/types/lodash/object/forIn.d.ts +++ b/types/lodash/object/forIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Iterates over own and inherited enumerable properties of an object invoking iteratee for each property. The diff --git a/types/lodash/object/forInRight.d.ts b/types/lodash/object/forInRight.d.ts index 98506ebc4e..72edd3a538 100644 --- a/types/lodash/object/forInRight.d.ts +++ b/types/lodash/object/forInRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.forIn except that it iterates over properties of object in the opposite order. diff --git a/types/lodash/object/forOwn.d.ts b/types/lodash/object/forOwn.d.ts index 84b389080f..06d0c9e370 100644 --- a/types/lodash/object/forOwn.d.ts +++ b/types/lodash/object/forOwn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Iterates over own enumerable properties of an object invoking iteratee for each property. The iteratee is diff --git a/types/lodash/object/forOwnRight.d.ts b/types/lodash/object/forOwnRight.d.ts index fc8160edff..d0526721fb 100644 --- a/types/lodash/object/forOwnRight.d.ts +++ b/types/lodash/object/forOwnRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.forOwn except that it iterates over properties of object in the opposite order. diff --git a/types/lodash/object/functions.d.ts b/types/lodash/object/functions.d.ts index 9871ffdc81..7226972151 100644 --- a/types/lodash/object/functions.d.ts +++ b/types/lodash/object/functions.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of function property names from own enumerable properties diff --git a/types/lodash/object/functionsIn.d.ts b/types/lodash/object/functionsIn.d.ts index 959f05743b..e07972f0c0 100644 --- a/types/lodash/object/functionsIn.d.ts +++ b/types/lodash/object/functionsIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of function property names from own and inherited diff --git a/types/lodash/object/get.d.ts b/types/lodash/object/get.d.ts index 957eaf716e..04b66860d1 100644 --- a/types/lodash/object/get.d.ts +++ b/types/lodash/object/get.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Gets the property value at path of object. If the resolved value is undefined the defaultValue is used diff --git a/types/lodash/object/has.d.ts b/types/lodash/object/has.d.ts index b8dc9ffc4d..ddd762ad2e 100644 --- a/types/lodash/object/has.d.ts +++ b/types/lodash/object/has.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `path` is a direct property of `object`. diff --git a/types/lodash/object/hasIn.d.ts b/types/lodash/object/hasIn.d.ts index 58917bdb19..05924d1c9d 100644 --- a/types/lodash/object/hasIn.d.ts +++ b/types/lodash/object/hasIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if `path` is a direct or inherited property of `object`. diff --git a/types/lodash/object/invert.d.ts b/types/lodash/object/invert.d.ts index 8bb5d784ed..ebb0f2ebdf 100644 --- a/types/lodash/object/invert.d.ts +++ b/types/lodash/object/invert.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object composed of the inverted keys and values of object. If object contains duplicate values, diff --git a/types/lodash/object/invertBy.d.ts b/types/lodash/object/invertBy.d.ts index 3feb6ee0b6..48b1fe6179 100644 --- a/types/lodash/object/invertBy.d.ts +++ b/types/lodash/object/invertBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.invert except that the inverted object is generated from the results of running each diff --git a/types/lodash/object/invoke.d.ts b/types/lodash/object/invoke.d.ts index 2e5f9970c3..f51f6e35fb 100644 --- a/types/lodash/object/invoke.d.ts +++ b/types/lodash/object/invoke.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Invokes the method at path of object. diff --git a/types/lodash/object/keys.d.ts b/types/lodash/object/keys.d.ts index 14a5f41b94..af84fdab93 100644 --- a/types/lodash/object/keys.d.ts +++ b/types/lodash/object/keys.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of the own enumerable property names of object. diff --git a/types/lodash/object/keysIn.d.ts b/types/lodash/object/keysIn.d.ts index c0c1210c02..60efebf88a 100644 --- a/types/lodash/object/keysIn.d.ts +++ b/types/lodash/object/keysIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of the own and inherited enumerable property names of object. diff --git a/types/lodash/object/mapKeys.d.ts b/types/lodash/object/mapKeys.d.ts index 992b0e3026..dda3eecc9a 100644 --- a/types/lodash/object/mapKeys.d.ts +++ b/types/lodash/object/mapKeys.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The opposite of _.mapValues; this method creates an object with the same values as object and keys generated diff --git a/types/lodash/object/mapValues.d.ts b/types/lodash/object/mapValues.d.ts index 94c97417f4..9f30b1774b 100644 --- a/types/lodash/object/mapValues.d.ts +++ b/types/lodash/object/mapValues.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object with the same keys as object and values generated by running each own diff --git a/types/lodash/object/merge.d.ts b/types/lodash/object/merge.d.ts index 1136f2d9bb..70bcf5c5c2 100644 --- a/types/lodash/object/merge.d.ts +++ b/types/lodash/object/merge.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Recursively merges own and inherited enumerable properties of source diff --git a/types/lodash/object/mergeWith.d.ts b/types/lodash/object/mergeWith.d.ts index 2f568e67db..42148ed3a8 100644 --- a/types/lodash/object/mergeWith.d.ts +++ b/types/lodash/object/mergeWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type MergeWithCustomizer = { bivariantHack(value: any, srcValue: any, key: string, object: any, source: any): any; }["bivariantHack"] interface LoDashStatic { diff --git a/types/lodash/object/omit.d.ts b/types/lodash/object/omit.d.ts index ae9890f7d9..6692221fc8 100644 --- a/types/lodash/object/omit.d.ts +++ b/types/lodash/object/omit.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The opposite of `_.pick`; this method creates an object composed of the diff --git a/types/lodash/object/omitBy.d.ts b/types/lodash/object/omitBy.d.ts index 0f5018e32b..cf123af47a 100644 --- a/types/lodash/object/omitBy.d.ts +++ b/types/lodash/object/omitBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The opposite of `_.pickBy`; this method creates an object composed of the diff --git a/types/lodash/object/pick.d.ts b/types/lodash/object/pick.d.ts index d20f7b9ae4..d84e655efe 100644 --- a/types/lodash/object/pick.d.ts +++ b/types/lodash/object/pick.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object composed of the picked `object` properties. diff --git a/types/lodash/object/pickBy.d.ts b/types/lodash/object/pickBy.d.ts index 7e1edefd77..dfe9023ba5 100644 --- a/types/lodash/object/pickBy.d.ts +++ b/types/lodash/object/pickBy.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an object composed of the `object` properties `predicate` returns diff --git a/types/lodash/object/result.d.ts b/types/lodash/object/result.d.ts index a8ec08387d..58814bb2a1 100644 --- a/types/lodash/object/result.d.ts +++ b/types/lodash/object/result.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.get except that if the resolved value is a function it’s invoked with the this binding diff --git a/types/lodash/object/set.d.ts b/types/lodash/object/set.d.ts index 38a7442807..1d621b64d1 100644 --- a/types/lodash/object/set.d.ts +++ b/types/lodash/object/set.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Sets the value at path of object. If a portion of path doesn’t exist it’s created. Arrays are created for diff --git a/types/lodash/object/setWith.d.ts b/types/lodash/object/setWith.d.ts index b57b8ebcb3..e347569709 100644 --- a/types/lodash/object/setWith.d.ts +++ b/types/lodash/object/setWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type SetWithCustomizer = (nsValue: any, key: string, nsObject: T) => any; interface LoDashStatic { diff --git a/types/lodash/object/toPairs.d.ts b/types/lodash/object/toPairs.d.ts index d1b6fe86d4..12945f7941 100644 --- a/types/lodash/object/toPairs.d.ts +++ b/types/lodash/object/toPairs.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of own enumerable key-value pairs for object. diff --git a/types/lodash/object/toPairsIn.d.ts b/types/lodash/object/toPairsIn.d.ts index 832fab7050..b9d1318cd6 100644 --- a/types/lodash/object/toPairsIn.d.ts +++ b/types/lodash/object/toPairsIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of own and inherited enumerable key-value pairs for object. diff --git a/types/lodash/object/transform.d.ts b/types/lodash/object/transform.d.ts index 1f8f4e9a48..67e16c4b86 100644 --- a/types/lodash/object/transform.d.ts +++ b/types/lodash/object/transform.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of diff --git a/types/lodash/object/unset.d.ts b/types/lodash/object/unset.d.ts index 4bbdc0593b..8b473e48ba 100644 --- a/types/lodash/object/unset.d.ts +++ b/types/lodash/object/unset.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Removes the property at path of object. diff --git a/types/lodash/object/update.d.ts b/types/lodash/object/update.d.ts index fd612dc970..23db9431c4 100644 --- a/types/lodash/object/update.d.ts +++ b/types/lodash/object/update.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.set except that accepts updater to produce the value to set. Use _.updateWith to diff --git a/types/lodash/object/updateWith.d.ts b/types/lodash/object/updateWith.d.ts index 5b51ce4554..fc0b96ec35 100644 --- a/types/lodash/object/updateWith.d.ts +++ b/types/lodash/object/updateWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.update` except that it accepts `customizer` which is diff --git a/types/lodash/object/values.d.ts b/types/lodash/object/values.d.ts index 743157cdf0..808335f9bc 100644 --- a/types/lodash/object/values.d.ts +++ b/types/lodash/object/values.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of the own enumerable property values of object. diff --git a/types/lodash/object/valuesIn.d.ts b/types/lodash/object/valuesIn.d.ts index a5e2bacc57..a60a449c4e 100644 --- a/types/lodash/object/valuesIn.d.ts +++ b/types/lodash/object/valuesIn.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of the own and inherited enumerable property values of object. diff --git a/types/lodash/seq/chain.d.ts b/types/lodash/seq/chain.d.ts index 5c45689b0e..dedc92da2b 100644 --- a/types/lodash/seq/chain.d.ts +++ b/types/lodash/seq/chain.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a lodash object that wraps value with explicit method chaining enabled. diff --git a/types/lodash/seq/prototype.at.d.ts b/types/lodash/seq/prototype.at.d.ts index 09b4fd5bc2..01aa3c7f86 100644 --- a/types/lodash/seq/prototype.at.d.ts +++ b/types/lodash/seq/prototype.at.d.ts @@ -1,4 +1,5 @@ -// declare namespace _ { +// import * as _ from "../index"; +// declare module "../index" { // interface LoDashWrapper { // /** // * This method is the wrapper version of _.at. diff --git a/types/lodash/seq/prototype.chain.d.ts b/types/lodash/seq/prototype.chain.d.ts index 5c45689b0e..dedc92da2b 100644 --- a/types/lodash/seq/prototype.chain.d.ts +++ b/types/lodash/seq/prototype.chain.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a lodash object that wraps value with explicit method chaining enabled. diff --git a/types/lodash/seq/prototype.commit.d.ts b/types/lodash/seq/prototype.commit.d.ts index b8eab97095..8d2393cb06 100644 --- a/types/lodash/seq/prototype.commit.d.ts +++ b/types/lodash/seq/prototype.commit.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashWrapper { /** * Executes the chained sequence and returns the wrapped result. diff --git a/types/lodash/seq/prototype.plant.d.ts b/types/lodash/seq/prototype.plant.d.ts index a419a750d9..72410991ec 100644 --- a/types/lodash/seq/prototype.plant.d.ts +++ b/types/lodash/seq/prototype.plant.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashImplicitWrapper { /** * Creates a clone of the chained sequence planting value as the wrapped value. diff --git a/types/lodash/seq/prototype.reverse.d.ts b/types/lodash/seq/prototype.reverse.d.ts index dd72272798..5bc1408784 100644 --- a/types/lodash/seq/prototype.reverse.d.ts +++ b/types/lodash/seq/prototype.reverse.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashWrapper { /** * Reverses the wrapped array so the first element becomes the last, the second element becomes the second to diff --git a/types/lodash/seq/prototype.toJSON.d.ts b/types/lodash/seq/prototype.toJSON.d.ts index 08e39d5558..d1838eaf2f 100644 --- a/types/lodash/seq/prototype.toJSON.d.ts +++ b/types/lodash/seq/prototype.toJSON.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashWrapper { /** * @see _.value diff --git a/types/lodash/seq/prototype.toString.d.ts b/types/lodash/seq/prototype.toString.d.ts index 5672a08667..b829902207 100644 --- a/types/lodash/seq/prototype.toString.d.ts +++ b/types/lodash/seq/prototype.toString.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashWrapper { /** * Produces the result of coercing the unwrapped value to a string. diff --git a/types/lodash/seq/prototype.value.d.ts b/types/lodash/seq/prototype.value.d.ts index 87caa46350..8a070267a5 100644 --- a/types/lodash/seq/prototype.value.d.ts +++ b/types/lodash/seq/prototype.value.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashWrapper { /** * Executes the chained sequence to extract the unwrapped value. diff --git a/types/lodash/seq/prototype.valueOf.d.ts b/types/lodash/seq/prototype.valueOf.d.ts index bfb28cbf67..4b24dcc831 100644 --- a/types/lodash/seq/prototype.valueOf.d.ts +++ b/types/lodash/seq/prototype.valueOf.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashWrapper { /** * @see _.value diff --git a/types/lodash/seq/tap.d.ts b/types/lodash/seq/tap.d.ts index 82902562ff..14bff06e0d 100644 --- a/types/lodash/seq/tap.d.ts +++ b/types/lodash/seq/tap.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method invokes interceptor and returns value. The interceptor is bound to thisArg and invoked with one diff --git a/types/lodash/seq/thru.d.ts b/types/lodash/seq/thru.d.ts index 3db6385be9..537431fee1 100644 --- a/types/lodash/seq/thru.d.ts +++ b/types/lodash/seq/thru.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.tap except that it returns the result of interceptor. diff --git a/types/lodash/string/camelCase.d.ts b/types/lodash/string/camelCase.d.ts index e6ad01c9c9..3e92da188f 100644 --- a/types/lodash/string/camelCase.d.ts +++ b/types/lodash/string/camelCase.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts string to camel case. diff --git a/types/lodash/string/capitalize.d.ts b/types/lodash/string/capitalize.d.ts index 41f2a7e935..0c4086db98 100644 --- a/types/lodash/string/capitalize.d.ts +++ b/types/lodash/string/capitalize.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts the first character of string to upper case and the remaining to lower case. diff --git a/types/lodash/string/deburr.d.ts b/types/lodash/string/deburr.d.ts index a0e89c64e7..8e01b0c13a 100644 --- a/types/lodash/string/deburr.d.ts +++ b/types/lodash/string/deburr.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Deburrs string by converting latin-1 supplementary letters to basic latin letters and removing combining diff --git a/types/lodash/string/endsWith.d.ts b/types/lodash/string/endsWith.d.ts index d8f76a0178..3261b90642 100644 --- a/types/lodash/string/endsWith.d.ts +++ b/types/lodash/string/endsWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if string ends with the given target string. diff --git a/types/lodash/string/escape.d.ts b/types/lodash/string/escape.d.ts index e18f0675be..4ef334a935 100644 --- a/types/lodash/string/escape.d.ts +++ b/types/lodash/string/escape.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts the characters "&", "<", ">", '"', "'", and "`" in string to their corresponding HTML entities. diff --git a/types/lodash/string/escapeRegExp.d.ts b/types/lodash/string/escapeRegExp.d.ts index f8e3790952..f21adb380e 100644 --- a/types/lodash/string/escapeRegExp.d.ts +++ b/types/lodash/string/escapeRegExp.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", diff --git a/types/lodash/string/kebabCase.d.ts b/types/lodash/string/kebabCase.d.ts index 00b9fd8421..9c8527f4e4 100644 --- a/types/lodash/string/kebabCase.d.ts +++ b/types/lodash/string/kebabCase.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts string to kebab case. diff --git a/types/lodash/string/lowerCase.d.ts b/types/lodash/string/lowerCase.d.ts index f71af2638b..25db8151db 100644 --- a/types/lodash/string/lowerCase.d.ts +++ b/types/lodash/string/lowerCase.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `string`, as space separated words, to lower case. diff --git a/types/lodash/string/lowerFirst.d.ts b/types/lodash/string/lowerFirst.d.ts index 323367c7ef..4dc55d3590 100644 --- a/types/lodash/string/lowerFirst.d.ts +++ b/types/lodash/string/lowerFirst.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts the first character of `string` to lower case. diff --git a/types/lodash/string/pad.d.ts b/types/lodash/string/pad.d.ts index 97b2cef838..2de1a43c36 100644 --- a/types/lodash/string/pad.d.ts +++ b/types/lodash/string/pad.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Pads string on the left and right sides if it’s shorter than length. Padding characters are truncated if diff --git a/types/lodash/string/padEnd.d.ts b/types/lodash/string/padEnd.d.ts index c9072bb59c..cb27815729 100644 --- a/types/lodash/string/padEnd.d.ts +++ b/types/lodash/string/padEnd.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Pads string on the right side if it’s shorter than length. Padding characters are truncated if they exceed diff --git a/types/lodash/string/padStart.d.ts b/types/lodash/string/padStart.d.ts index fff4aaf566..e73fbf9923 100644 --- a/types/lodash/string/padStart.d.ts +++ b/types/lodash/string/padStart.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Pads string on the left side if it’s shorter than length. Padding characters are truncated if they exceed diff --git a/types/lodash/string/parseInt.d.ts b/types/lodash/string/parseInt.d.ts index d481c1d750..ec786dadae 100644 --- a/types/lodash/string/parseInt.d.ts +++ b/types/lodash/string/parseInt.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts string to an integer of the specified radix. If radix is undefined or 0, a radix of 10 is used diff --git a/types/lodash/string/repeat.d.ts b/types/lodash/string/repeat.d.ts index ae965cf86b..f634895d94 100644 --- a/types/lodash/string/repeat.d.ts +++ b/types/lodash/string/repeat.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Repeats the given string n times. diff --git a/types/lodash/string/replace.d.ts b/types/lodash/string/replace.d.ts index d980e59b1d..30284543d8 100644 --- a/types/lodash/string/replace.d.ts +++ b/types/lodash/string/replace.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Replaces matches for pattern in string with replacement. diff --git a/types/lodash/string/snakeCase.d.ts b/types/lodash/string/snakeCase.d.ts index a38f964fa0..ffeb9ce551 100644 --- a/types/lodash/string/snakeCase.d.ts +++ b/types/lodash/string/snakeCase.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts string to snake case. diff --git a/types/lodash/string/split.d.ts b/types/lodash/string/split.d.ts index 43416dcf87..73c0084798 100644 --- a/types/lodash/string/split.d.ts +++ b/types/lodash/string/split.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Splits string by separator. diff --git a/types/lodash/string/startCase.d.ts b/types/lodash/string/startCase.d.ts index 6b053c48bd..dcb0ac8118 100644 --- a/types/lodash/string/startCase.d.ts +++ b/types/lodash/string/startCase.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts string to start case. diff --git a/types/lodash/string/startsWith.d.ts b/types/lodash/string/startsWith.d.ts index 8bd9a63d13..5185f48ac1 100644 --- a/types/lodash/string/startsWith.d.ts +++ b/types/lodash/string/startsWith.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks if string starts with the given target string. diff --git a/types/lodash/string/template.d.ts b/types/lodash/string/template.d.ts index 5ad7c00921..ed1f6444da 100644 --- a/types/lodash/string/template.d.ts +++ b/types/lodash/string/template.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface TemplateOptions extends TemplateSettings { /** * The sourceURL of the template's compiled source. diff --git a/types/lodash/string/toLower.d.ts b/types/lodash/string/toLower.d.ts index 4db3f2f585..3fd92d0ca7 100644 --- a/types/lodash/string/toLower.d.ts +++ b/types/lodash/string/toLower.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `string`, as a whole, to lower case. diff --git a/types/lodash/string/toUpper.d.ts b/types/lodash/string/toUpper.d.ts index 6ebd95081f..b2fd186b8a 100644 --- a/types/lodash/string/toUpper.d.ts +++ b/types/lodash/string/toUpper.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `string`, as a whole, to upper case. diff --git a/types/lodash/string/trim.d.ts b/types/lodash/string/trim.d.ts index f154162543..f9636c232e 100644 --- a/types/lodash/string/trim.d.ts +++ b/types/lodash/string/trim.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Removes leading and trailing whitespace or specified characters from string. diff --git a/types/lodash/string/trimEnd.d.ts b/types/lodash/string/trimEnd.d.ts index ae83e6641d..6f866e9a73 100644 --- a/types/lodash/string/trimEnd.d.ts +++ b/types/lodash/string/trimEnd.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Removes trailing whitespace or specified characters from string. diff --git a/types/lodash/string/trimStart.d.ts b/types/lodash/string/trimStart.d.ts index 3ce788f055..255a13f2e9 100644 --- a/types/lodash/string/trimStart.d.ts +++ b/types/lodash/string/trimStart.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Removes leading whitespace or specified characters from string. diff --git a/types/lodash/string/truncate.d.ts b/types/lodash/string/truncate.d.ts index 041ee6223b..98a67d4671 100644 --- a/types/lodash/string/truncate.d.ts +++ b/types/lodash/string/truncate.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface TruncateOptions { /** The maximum string length. */ length?: number; diff --git a/types/lodash/string/unescape.d.ts b/types/lodash/string/unescape.d.ts index f8f77bacd0..8a5c5e8cfc 100644 --- a/types/lodash/string/unescape.d.ts +++ b/types/lodash/string/unescape.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The inverse of _.escape; this method converts the HTML entities &, <, >, ", ', and ` diff --git a/types/lodash/string/upperCase.d.ts b/types/lodash/string/upperCase.d.ts index 5377337f0e..11e7354c60 100644 --- a/types/lodash/string/upperCase.d.ts +++ b/types/lodash/string/upperCase.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `string`, as space separated words, to upper case. diff --git a/types/lodash/string/upperFirst.d.ts b/types/lodash/string/upperFirst.d.ts index 38f88a7e94..f8f2e1ecd8 100644 --- a/types/lodash/string/upperFirst.d.ts +++ b/types/lodash/string/upperFirst.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts the first character of `string` to upper case. diff --git a/types/lodash/string/words.d.ts b/types/lodash/string/words.d.ts index 11fa80ee62..4ff9508d1b 100644 --- a/types/lodash/string/words.d.ts +++ b/types/lodash/string/words.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Splits `string` into an array of its words. diff --git a/types/lodash/util/attempt.d.ts b/types/lodash/util/attempt.d.ts index 70651b722d..6d8d140742 100644 --- a/types/lodash/util/attempt.d.ts +++ b/types/lodash/util/attempt.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Attempts to invoke func, returning either the result or the caught error object. Any additional arguments diff --git a/types/lodash/util/bindAll.d.ts b/types/lodash/util/bindAll.d.ts index 78b9726e63..6e78003bff 100644 --- a/types/lodash/util/bindAll.d.ts +++ b/types/lodash/util/bindAll.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Binds methods of an object to the object itself, overwriting the existing method. Method names may be diff --git a/types/lodash/util/cond.d.ts b/types/lodash/util/cond.d.ts index 92f5285d43..ec34302904 100644 --- a/types/lodash/util/cond.d.ts +++ b/types/lodash/util/cond.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that iterates over `pairs` and invokes the corresponding diff --git a/types/lodash/util/conforms.d.ts b/types/lodash/util/conforms.d.ts index 60887c45ad..9ffd984ffe 100644 --- a/types/lodash/util/conforms.d.ts +++ b/types/lodash/util/conforms.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { type ConformsPredicateObject = { [P in keyof T]?: (val: T[P]) => boolean; }; diff --git a/types/lodash/util/constant.d.ts b/types/lodash/util/constant.d.ts index 1083d4e460..a0f5742342 100644 --- a/types/lodash/util/constant.d.ts +++ b/types/lodash/util/constant.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that returns value. diff --git a/types/lodash/util/defaultTo.d.ts b/types/lodash/util/defaultTo.d.ts index 3bc4810f1b..1bb533f8cf 100644 --- a/types/lodash/util/defaultTo.d.ts +++ b/types/lodash/util/defaultTo.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Checks `value` to determine whether a default value should be returned in diff --git a/types/lodash/util/flow.d.ts b/types/lodash/util/flow.d.ts index 90837be794..49f28d0678 100644 --- a/types/lodash/util/flow.d.ts +++ b/types/lodash/util/flow.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that returns the result of invoking the provided functions with the this binding of the diff --git a/types/lodash/util/flowRight.d.ts b/types/lodash/util/flowRight.d.ts index d0a2faaa9f..358ea933a3 100644 --- a/types/lodash/util/flowRight.d.ts +++ b/types/lodash/util/flowRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like _.flow except that it creates a function that invokes the provided functions from right diff --git a/types/lodash/util/identity.d.ts b/types/lodash/util/identity.d.ts index 18ade4c0cf..9ecc96fd8d 100644 --- a/types/lodash/util/identity.d.ts +++ b/types/lodash/util/identity.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method returns the first argument provided to it. diff --git a/types/lodash/util/iteratee.d.ts b/types/lodash/util/iteratee.d.ts index 1777690492..d80d154e85 100644 --- a/types/lodash/util/iteratee.d.ts +++ b/types/lodash/util/iteratee.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes `func` with the arguments of the created diff --git a/types/lodash/util/matches.d.ts b/types/lodash/util/matches.d.ts index fb69121a13..d5147ccb78 100644 --- a/types/lodash/util/matches.d.ts +++ b/types/lodash/util/matches.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that performs a deep comparison between a given object and source, returning true if the diff --git a/types/lodash/util/matchesProperty.d.ts b/types/lodash/util/matchesProperty.d.ts index 36c64e4d7e..c96d2422a8 100644 --- a/types/lodash/util/matchesProperty.d.ts +++ b/types/lodash/util/matchesProperty.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that compares the property value of path on a given object to value. diff --git a/types/lodash/util/method.d.ts b/types/lodash/util/method.d.ts index 7377b17a60..23b1600bc9 100644 --- a/types/lodash/util/method.d.ts +++ b/types/lodash/util/method.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes the method at path on a given object. Any additional arguments are provided diff --git a/types/lodash/util/methodOf.d.ts b/types/lodash/util/methodOf.d.ts index 52d7343be5..acd9afa335 100644 --- a/types/lodash/util/methodOf.d.ts +++ b/types/lodash/util/methodOf.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The opposite of _.method; this method creates a function that invokes the method at a given path on object. diff --git a/types/lodash/util/mixin.d.ts b/types/lodash/util/mixin.d.ts index 01590b1929..230b355322 100644 --- a/types/lodash/util/mixin.d.ts +++ b/types/lodash/util/mixin.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface MixinOptions { chain?: boolean; } diff --git a/types/lodash/util/noConflict.d.ts b/types/lodash/util/noConflict.d.ts index d27b76819d..948ba75863 100644 --- a/types/lodash/util/noConflict.d.ts +++ b/types/lodash/util/noConflict.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Reverts the _ variable to its previous value and returns a reference to the lodash function. diff --git a/types/lodash/util/noop.d.ts b/types/lodash/util/noop.d.ts index a17e537d98..c6b0475f69 100644 --- a/types/lodash/util/noop.d.ts +++ b/types/lodash/util/noop.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * A no-operation function that returns undefined regardless of the arguments it receives. diff --git a/types/lodash/util/nthArg.d.ts b/types/lodash/util/nthArg.d.ts index d6b7b5a026..69a6087424 100644 --- a/types/lodash/util/nthArg.d.ts +++ b/types/lodash/util/nthArg.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that returns its nth argument. diff --git a/types/lodash/util/over.d.ts b/types/lodash/util/over.d.ts index 87b323c4b4..7b98d05618 100644 --- a/types/lodash/util/over.d.ts +++ b/types/lodash/util/over.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that invokes iteratees with the arguments provided to the created function and returns diff --git a/types/lodash/util/overEvery.d.ts b/types/lodash/util/overEvery.d.ts index b0f6275b4e..e88b3f2a27 100644 --- a/types/lodash/util/overEvery.d.ts +++ b/types/lodash/util/overEvery.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that checks if all of the predicates return truthy when invoked with the arguments diff --git a/types/lodash/util/overSome.d.ts b/types/lodash/util/overSome.d.ts index 8574eb8f49..b177805dc2 100644 --- a/types/lodash/util/overSome.d.ts +++ b/types/lodash/util/overSome.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that checks if any of the predicates return truthy when invoked with the arguments diff --git a/types/lodash/util/property.d.ts b/types/lodash/util/property.d.ts index 72d1d8511b..72658a89dc 100644 --- a/types/lodash/util/property.d.ts +++ b/types/lodash/util/property.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates a function that returns the property value at path on a given object. diff --git a/types/lodash/util/propertyOf.d.ts b/types/lodash/util/propertyOf.d.ts index a904424d70..2bfab04f86 100644 --- a/types/lodash/util/propertyOf.d.ts +++ b/types/lodash/util/propertyOf.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * The opposite of _.property; this method creates a function that returns the property value at a given path diff --git a/types/lodash/util/range.d.ts b/types/lodash/util/range.d.ts index ebd8266e4c..f92af4de75 100644 --- a/types/lodash/util/range.d.ts +++ b/types/lodash/util/range.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. diff --git a/types/lodash/util/rangeRight.d.ts b/types/lodash/util/rangeRight.d.ts index 119aa7d7aa..b63da90370 100644 --- a/types/lodash/util/rangeRight.d.ts +++ b/types/lodash/util/rangeRight.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method is like `_.range` except that it populates values in diff --git a/types/lodash/util/runInContext.d.ts b/types/lodash/util/runInContext.d.ts index 5c8acfb592..4bd523e96c 100644 --- a/types/lodash/util/runInContext.d.ts +++ b/types/lodash/util/runInContext.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Create a new pristine lodash function using the given context object. diff --git a/types/lodash/util/stubArray.d.ts b/types/lodash/util/stubArray.d.ts index ef5f8d32a1..92b1bbeba1 100644 --- a/types/lodash/util/stubArray.d.ts +++ b/types/lodash/util/stubArray.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method returns a new empty array. diff --git a/types/lodash/util/stubFalse.d.ts b/types/lodash/util/stubFalse.d.ts index eaea1c9a48..deb8d92543 100644 --- a/types/lodash/util/stubFalse.d.ts +++ b/types/lodash/util/stubFalse.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method returns `false`. diff --git a/types/lodash/util/stubObject.d.ts b/types/lodash/util/stubObject.d.ts index b8de585c96..2fa401fa75 100644 --- a/types/lodash/util/stubObject.d.ts +++ b/types/lodash/util/stubObject.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method returns a new empty object. diff --git a/types/lodash/util/stubString.d.ts b/types/lodash/util/stubString.d.ts index 8b4363f458..8badcdf7f6 100644 --- a/types/lodash/util/stubString.d.ts +++ b/types/lodash/util/stubString.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method returns an empty string. diff --git a/types/lodash/util/stubTrue.d.ts b/types/lodash/util/stubTrue.d.ts index 1c008fd0b7..1191db4cfb 100644 --- a/types/lodash/util/stubTrue.d.ts +++ b/types/lodash/util/stubTrue.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * This method returns `true`. diff --git a/types/lodash/util/times.d.ts b/types/lodash/util/times.d.ts index e059c588f4..9860d13ea6 100644 --- a/types/lodash/util/times.d.ts +++ b/types/lodash/util/times.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Invokes the iteratee function n times, returning an array of the results of each invocation. The iteratee diff --git a/types/lodash/util/toPath.d.ts b/types/lodash/util/toPath.d.ts index 4c5129a461..74905ff4ef 100644 --- a/types/lodash/util/toPath.d.ts +++ b/types/lodash/util/toPath.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Converts `value` to a property path array. diff --git a/types/lodash/util/uniqueId.d.ts b/types/lodash/util/uniqueId.d.ts index 49691cab85..7f1e8c252f 100644 --- a/types/lodash/util/uniqueId.d.ts +++ b/types/lodash/util/uniqueId.d.ts @@ -1,4 +1,5 @@ -declare namespace _ { +import * as _ from "../index"; +declare module "../index" { interface LoDashStatic { /** * Generates a unique ID. If prefix is provided the ID is appended to it. diff --git a/types/loopback/index.d.ts b/types/loopback/index.d.ts index 99fc4d4ccb..087ce2aadd 100644 --- a/types/loopback/index.d.ts +++ b/types/loopback/index.d.ts @@ -2653,7 +2653,7 @@ declare namespace l { * if a principal is in the specified role. * Should provide a callback or return a promise. */ - static registerResolver(role: string, resolver: () => void): void; + static registerResolver(role: string, resolver: (role: string, ctx: Context, callback?: (err: Error, resolved: boolean) => void) => Promise | void): void; } /** diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 327fe15ade..7229e45dc4 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -294,6 +294,7 @@ declare module 'luxon' { function eras(length?: EraLength, options?: InfoOptions): string[]; function features(): Features; function hasDST(zone: string | Zone): boolean; + function isValidIANAZone(zone: string): boolean; function meridiems(options?: InfoOptions): string[]; function months(length?: UnitLength, options?: UnitOptions): string[]; function monthsFormat(length?: UnitLength, options?: UnitOptions): string[]; diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 1f0edaf412..47f62556c3 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -26,8 +26,12 @@ declare namespace mapboxgl { constructor(options?: MapboxOptions); addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + + addControl(control: IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; removeControl(control: Control): this; + + removeControl(control: IControl): this; addClass(klass: string, options?: mapboxgl.StyleOptions): this; diff --git a/types/materialize-css/v0/index.d.ts b/types/materialize-css/v0/index.d.ts index a457c3ad1a..87629ed699 100644 --- a/types/materialize-css/v0/index.d.ts +++ b/types/materialize-css/v0/index.d.ts @@ -5,6 +5,7 @@ // Sukhdeep Singh // Jean-Francois Cere // Sebastien Cote +// Liad Idan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -475,11 +476,15 @@ declare namespace Materialize { } /** - * Declare Pickadate namespace again in order to add more Materialize specific properties to TimeOptions interface + * Declare Pickadate namespace again in order to add more Materialize specific properties to TimeOptions and DateOptions interfaces * * @see http://www.typescriptlang.org/docs/handbook/declaration-merging.html */ declare namespace Pickadate { + interface DateOptions { + weekdaysLetter?: string[]; + } + interface TimeOptions { /** * Set default time such as : 'now', '1:30AM', '16:30'. diff --git a/types/memcached/index.d.ts b/types/memcached/index.d.ts index fffbb57c82..8e330fa88d 100644 --- a/types/memcached/index.d.ts +++ b/types/memcached/index.d.ts @@ -280,5 +280,9 @@ declare namespace Memcached { * 5000, the idle timeout for the connections. */ idle ?: number; + /** + * '', sentinel to prepend to all memcache keys for namespacing the entries. + */ + namespace ?: string; } } diff --git a/types/moment-duration-format/index.d.ts b/types/moment-duration-format/index.d.ts index 402db8a75b..4506311ab6 100644 --- a/types/moment-duration-format/index.d.ts +++ b/types/moment-duration-format/index.d.ts @@ -1,7 +1,11 @@ -// Type definitions for moment-duration-format 1.3 +// Type definitions for moment-duration-format 2.2 // Project: https://github.com/jsmreese/moment-duration-format -// Definitions by: Swint De Coninck , Niklas Walter , Leonard Thieu +// Definitions by: Swint De Coninck +// Niklas Walter +// Leonard Thieu +// Lukasz Bendykowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as moment from "moment"; @@ -22,33 +26,66 @@ declare module "moment" { (settings?: DurationFormatSettings): string; } + type UnitOfTrimV1 = 'left' | 'right'; + type UnitOfTrim = ( + 'large' | 'small' | 'both' | + 'mid' | 'all' | 'final' + ); + interface DurationFormatSettings { - escape?: RegExp; - years?: RegExp; - months?: RegExp; - weeks?: RegExp; - days?: RegExp; - hours?: RegExp; - minutes?: RegExp; - seconds?: RegExp; - milliseconds?: RegExp; - general?: RegExp; + trim?: false | UnitOfTrimV1 | UnitOfTrim | string | Array; + largest?: number; + trunc?: true; + stopTrim?: string; - types?: string; + minValue?: number; + maxValue?: number; - // "left" - template tokens are trimmed from the left until the first moment token that has a value >= 1 - // "right" - template tokens are trimmed from the right until the first moment token that has a value >= 1 - // (the final moment token is not trimmed, regardless of value) - // `false` - template tokens are not trimmed - trim?: 'left' | 'right' | false; - - // number of decimal digits to include after (to the right of) the decimal point (positive integer) - // or the number of digits to truncate to 0 before (to the left of) the decimal point (negative integer) + useGrouping?: boolean; precision?: number; + decimalSeparator?: string; + groupingSeparator?: string; + grouping?: number[]; - // force first moment token with a value to render at full length even when template is trimmed and first moment token has length of 1 - forceLength?: boolean | null; + useSignificantDigits?: true; + + forceLength?: boolean; template?: string | TemplateFunction; + + userLocale?: string; + usePlural?: boolean; + useLeftUnits?: boolean; + useToLocaleString?: boolean; + } + + type DurationLabelType = "long" | "standard" | "short"; + type DurationTemplate = "HMS" | "HM" | "MS"; + type DurationToken = ( + "S" | "SS" | "SSS" | + "s" | "ss" | "sss" | + "m" | "mm" | "mmm" | + "h" | "hh" | "hhh" | + "d" | "dd" | "ddd" | + "w" | "ww" | "www" | + "M" | "MM" | "MMM" | + "y" | "yy" | "yyy" + ); + + type DurationLabelDef = {[duration in DurationToken]: string}; + type DurationTimeDef = {[template in DurationTemplate]: string}; + + interface DurationLabelTypeDef { + type: DurationLabelType; + string: string; + } + + interface LocaleSpecification { + durationLabelsLong: DurationLabelDef; + durationLabelsStandard: DurationLabelDef; + durationLabelsShort: DurationLabelDef; + durationTimeTemplates: DurationTimeDef; + durationLabelTypes: DurationLabelTypeDef[]; + durationPluralKey: (token: string, integerValue: number, decimalValue: number) => string; } type TemplateFunction = ((this: DurationFormatSettings) => string); diff --git a/types/moment-duration-format/moment-duration-format-tests.ts b/types/moment-duration-format/moment-duration-format-tests.ts index 52f313b9b4..135131ce71 100644 --- a/types/moment-duration-format/moment-duration-format-tests.ts +++ b/types/moment-duration-format/moment-duration-format-tests.ts @@ -43,30 +43,333 @@ moment.duration(123, "seconds").format("hh:mm:ss"); moment.duration(123, "seconds").format("h:mm:ss", { forceLength: true }); // "02:03" -moment.duration.fn.format.defaults.escape = /\((.+?)\)/; -moment.duration(123, "seconds").format("m (minutes)", 2); -// "2.04 minutes" +moment.duration(123, "minutes").format("d[d] h:mm:ss"); +// "2:03:00" -moment.duration.fn.format.defaults.years = /[Aa]+/; -moment.duration(123, "weeks").format("a [años]", 2); -// "2.35 años" +moment.duration(123, "minutes").format("s [seconds], m [minutes], h [hours], d [days]"); +// "0 seconds, 3 minutes, 2 hours" -moment.duration.fn.format.defaults.months = /m+/; -moment.duration(123, "weeks").format("m M", 2); -// "28.36 M" +moment.duration(123, "minutes").format("d[d] h:mm:ss", { + trim: false +}); +// "0d 2:03:00" -moment.duration.fn.format.defaults.weeks = /w+/; -moment.duration(123, "days").format("w W", 2); -// "17.57 W" +moment.duration(123, "minutes").format("d[d] h:mm:ss"); +// "2:03:00" -moment.duration.fn.format.defaults.days = /d+/; -moment.duration(123, "hours").format("d D", 2); -// "5.12 D" +moment.duration(123, "minutes").format("d[d] h:mm:ss", { + trim: "large" +}); +// "2:03:00" -moment.duration.fn.format.defaults.hours = /h+/; -moment.duration(123, "minutes").format("h H", 2); -// "2.04 H" +moment.duration(0, "minutes").format("d[d] h:mm:ss", { + trim: "large" +}); +// "0" -moment.duration.fn.format.defaults.minutes = /n+/; -moment.duration(123, "seconds").format("n:ss"); +moment.duration(123, "minutes").format("d[d] h:mm:ss", { + trim: "small" +}); +// "0d 2:03" + +moment.duration(0, "minutes").format("d[d] h:mm:ss", { + trim: "small" +}); +// "0d" + +moment.duration(123, "minutes").format("d[d] h[h] m[m] s[s]", { + trim: "both" +}); +// "2h 3m" + +moment.duration(0, "minutes").format("d[d] h[h] m[m] s[s]", { + trim: "both" +}); +// "0s" + +moment.duration(1441, "minutes").format("w[w] d[d] h[h] m[m] s[s]", { + trim: "mid" +}); +// "0w 1d 1m 0s" + +moment.duration(1441, "minutes").format("w[w] d[d] h[h] m[m] s[s]", { + trim: "large mid" +}); +// "1d 1m 0s" + +moment.duration(1441, "minutes").format("w[w] d[d] h[h] m[m] s[s]", { + trim: "small mid" +}); +// "0w 1d 1m" + +moment.duration(1441, "minutes").format("w[w] d[d] h[h] m[m] s[s]", { + trim: "both mid" +}); +// "1d 1m" + +moment.duration(0, "minutes").format("w[w] d[d] h[h] m[m] s[s]", { + trim: "both mid" +}); +// "0s" + +moment.duration(0, "minutes").format("d[d] h:mm:ss", { + trim: "large final" +}); +// "" + +moment.duration(0, "minutes").format("d[d] h:mm:ss", { + trim: "small final" +}); +// "" + +moment.duration(0, "minutes").format("d[d] h[h] m[m] s[s]", { + trim: "both final" +}); +// "" + +moment.duration(0, "minutes").format("d[d] h[h] m[m] s[s]", { + trim: "all" +}); +// "" + +moment.duration(7322, "seconds").format("d [days], h [hours], m [minutes], s [seconds]", { + largest: 2 +}); +// "2 hours, 2 minutes" + +moment.duration(1216922, "seconds").format("y [years], w [weeks], d [days], h [hours], m [minutes], s [seconds]", { + largest: 2 +}); +// "2 weeks, 2 hours" + +moment.duration(23, "minutes").format("d[d] h:mm:ss", { + stopTrim: "h" +}); +// "0:23:00" + +moment.duration(23, "minutes").format("d[d] *h:mm:ss"); +// "0:23:00" + +moment.duration(2, "hours").format("y [years], d [days], h [hours], m [minutes], s [seconds]", { + trim: "both", + stopTrim: "d m" +}); +// "0 days, 2 hours, 0 minutes" + +moment.duration(2, "hours").format("y [years], *d [days], h [hours], *m [minutes], s [seconds]", { + trim: "both" +}); +// "0 days, 2 hours, 0 minutes" + +moment.duration(2, "hours").format("y [years], d [days], h [hours], m [minutes], s [seconds]", { + trim: "both", + stopTrim: "d m", + largest: 2 +}); +// "2 hours" + +moment.duration(179, "seconds").format("m [minutes]"); +// "3 minutes" + +moment.duration(3780, "seconds").format("h [hours]", 1); +// "1.1 hours" + +moment.duration(179, "seconds").format("m [minutes]", { + trunc: true +}); +// "2 minutes" + +moment.duration(3780, "seconds").format("h [hours]", 1, { + trunc: true +}); +// "1.0 hours" + +moment.duration(59, "seconds").format("d [days], h [hours], m [minutes]", { + trunc: true, + trim: "both" +}); +// "0 minutes" + +moment.duration(59, "seconds").format("d [days], h [hours], m [minutes]", { + trunc: true, + trim: "all" +}); +// "" + +moment.duration(59, "seconds").format("d [days], h [hours], m [minutes]", { + trunc: true, + largest: 1 +}); +// "" + +moment.duration(59, "seconds").format("h [hours], m [minutes]", { + minValue: 1 +}); +// "< 1 minute" + +moment.duration(59, "seconds").format("h [hours], m [minutes]", { + minValue: 1, + trim: "both" +}); +// "< 1 minute" + +moment.duration(7229, "seconds").format("h [hours], m [minutes]", { + minValue: 1, + trim: "both" +}); +// "2 hours" + +moment.duration(59, "seconds").format("h [hours], m [minutes]", { + minValue: 1, + trunc: true, + trim: "all" +}); +// "" + +moment.duration(-59, "seconds").format("h [hours], m [minutes]", { + minValue: 1 +}); +// "> -1 minute" + +moment.duration(59, "seconds").format("h [hours], m [minutes]", { + minValue: 1, + trim: false, + largest: 2 +}); +// "< 1 minute" + +moment.duration(15, "days").format("w [weeks]", { + maxValue: 2 +}); +// "> 2 weeks" + +moment.duration(-15, "days").format("w [weeks]]", { + maxValue: 2 +}); +// "< -2 weeks" + +moment.duration(15, "days").format("w [weeks], d [days]", { + maxValue: 2, + trim: false, + largest: 2 +}); +// "> 2 weeks" + +moment.duration(123, "seconds").format("h:mm:ss"); // "2:03" + +moment.duration(123, "seconds").format("hh:mm:ss"); +// "02:03" + +moment.duration(123, "seconds").format("h:mm:ss", { + forceLength: true +}); +// "02:03" + +moment.duration(99999, "seconds").format("d [days], h [hours], m [minutes], s [seconds]", { + useSignificantDigits: true, + precision: 3 +}); +// "1 day, 3 hours, 50 minutes" + +moment.duration(99999, "seconds").format("d [days], h [hours], m [minutes], s [seconds]", { + useSignificantDigits: true, + precision: 3, + trunc: true +}); +// "1 day, 3 hours, 40 minutes" + +moment.duration(99999, "seconds").format("d [days], h [hours], m [minutes], s [seconds]", { + useSignificantDigits: true, + precision: 5 +}); +// "1 day, 3 hours, 46 minutes, 40 seconds" + +moment.duration(99999, "seconds").format("d [days], h [hours], m [minutes], s [seconds]", { + useSignificantDigits: true, + trunc: true, + precision: 5 +}); +// "1 day, 3 hours, 46 minutes, 30 seconds" + +moment.duration(99999, "seconds").format("d [days], h [hours], m [minutes], s [seconds]", { + useSignificantDigits: true, + precision: 6 +}); +// "1 day, 3 hours, 46 minutes, 39 seconds" + +moment.duration(1234567, "seconds").format("m [minutes]", 3); +// "20,576.117 minutes" + +moment.duration(1234567, "seconds").format("m [minutes]", 3, { + userLocale: "de-DE" +}); +// "20.576,117 minutes" + +moment.duration(2, "minutes").format("m _"); +// "2 mins" + +moment.duration(2, "minutes").format("m __"); +// "2 minutes" + +moment.duration(3661, "seconds").format("_HMS_"); +// "1:01:01" + +moment.duration(3661, "seconds").format("_HM_"); +// "1:01" + +moment.duration(61, "seconds").format("_MS_"); +// "1:01" + +moment.duration(1, "minutes").format("m [minutes]"); +// "1 minute" + +moment.duration(1, "minutes").format("m [mins]"); +// "1 min" + +moment.duration(2, "minutes").format("m [minute]"); +// "2 minutes" + +moment.duration(2, "minutes").format("m [min]"); +// "2 mins" + +moment.duration(1, "minutes").format("m [minutes]", { + usePlural: false +}); +// "1 minutes" + +moment.duration(1, "minutes").format("m [mins]", { + usePlural: false +}); +// "1 mins" + +moment.duration(2, "minutes").format("m [minute]", { + usePlural: false +}); +// "2 minute" + +moment.duration(2, "minutes").format("m [min]", { + usePlural: false +}); +// "2 min" + +moment.duration(1, "minutes").format("m [minutes]", 2); +// "1.00 minutes" + +moment.duration(7322, "seconds").format("_ h, _ m, _ s", { + useLeftUnits: true +}); +// "hrs 2, mins 2, secs 2" + +moment.duration(1234, "seconds").format("s [seconds]"); +// "1,234 seconds" + +moment.duration(1234, "seconds").format("s [seconds]", { + useGrouping: false +}); +// "1234 seconds" + +moment.duration(1234567, "seconds").format("m [minutes]", 3, { + userLocale: "de-DE" +}); +// "20.576,117 minutes" diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 08aeceb5d8..dd4f44f38a 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1457,8 +1457,8 @@ export interface ChangeStreamOptions { type GridFSBucketWriteStreamId = string | number | Object | ObjectID; export interface LoggerOptions { - loggerLevel: string // Custom logger function - logger: log // Override default global log level. + loggerLevel?: string // Custom logger function + logger?: log // Override default global log level. } export type log = (message?: string, state?: LoggerState) => void @@ -1473,7 +1473,7 @@ export interface LoggerState { /** http://mongodb.github.io/node-mongodb-native/3.0/api/Logger.html */ export class Logger{ - constructor(className: string,options: LoggerOptions) + constructor(className: string, options?: LoggerOptions) // Log a message at the debug level debug(message: string, state: LoggerState):void // Log a message at the warn level @@ -1497,7 +1497,7 @@ export class Logger{ //Set the current logger function static setCurrentLogger(log: log):void // Set what classes to log. - static filter(type: string,values: string[]):void + static filter(type: string, values: string[]):void // Set the current log level static setLevel(level: string):void } diff --git a/types/mongoose-deep-populate/tsconfig.json b/types/mongoose-deep-populate/tsconfig.json index eb2e278299..40544f37a1 100644 --- a/types/mongoose-deep-populate/tsconfig.json +++ b/types/mongoose-deep-populate/tsconfig.json @@ -12,6 +12,11 @@ "typeRoots": [ "../" ], + "paths": { + "mongoose": [ + "mongoose/v4" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index ee703de783..7ac3ee7e41 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Mongoose 4.7.1 +// Type definitions for Mongoose 5.0.1 // Project: http://mongoosejs.com/ -// Definitions by: simonxca , horiuchi , sindrenm , lukasz-zak +// Definitions by: simonxca , horiuchi , sindrenm , lukasz-zak , Alorel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -25,45 +25,6 @@ * changes just copy/paste them into here. * - Check the files off as you go. Some files below might not have anything in them. That's ok, this * is just a simple heuristic to keep track of our progress. - * - * TODO for version 4.x [updated][tested]: - * [x][x] index.js - * [x][x] querystream.js - * [x][x] connection.js - * [x][x] utils.js - * [x][x] browser.js - * [x][x] drivers/node-mongodb-native/collection.js - * [x][x] drivers/node-mongodb-native/connection.js - * [x][x] error/messages.js - * [x][x] error/validation.js - * [x][x] error.js - * [x][x] querycursor.js - * [x][x] virtualtype.js - * [x][x] schema.js - * [x][x] document.js - * [x][x] types/subdocument.js - * [x][x] types/array.js - * [x][x] types/documentarray.js - * [x][x] types/buffer.js - * [x][x] types/objectid.js - * [x][x] types/embedded.js - * [x][x] query.js - * [x][x] schema/array.js - * [x][x] schema/string.js - * [x][x] schema/documentarray.js - * [x][x] schema/number.js - * [x][x] schema/date.js - * [x][x] schema/buffer.js - * [x][x] schema/boolean.js - * [x][x] schema/objectid.js - * [x][x] schema/mixed.js - * [x][x] schema/embedded.js - * [x][x] aggregate.js - * [x][x] schematype.js - * [x][x] promise.js - * [x][x] ES6Promise.js - * [x][x] model.js - * [x][x] collection.js */ /* @@ -80,6 +41,9 @@ declare module "mongoose" { import stream = require('stream'); import mongoose = require('mongoose'); + /** Pluralises the given name */ + export function pluralize(str: string): string; + /* * Some mongoose classes have the same name as the native JS classes * Keep references to native classes using a "Native" prefix @@ -99,7 +63,7 @@ declare module "mongoose" { export var SchemaTypes: typeof Schema.Types; /** Expose connection states for user-land */ - export var STATES: Object; + export var STATES: any; /** The default connection of the mongoose module. */ export var connection: Connection; /** The node-mongodb-native driver Mongoose uses. */ @@ -112,11 +76,9 @@ declare module "mongoose" { * Options passed take precedence over options included in connection strings. * @returns pseudo-promise wrapper around this */ - export function connect(uris: string, - options?: ConnectionOptions, - callback?: (err: mongodb.MongoError) => void): MongooseThenable; - export function connect(uris: string, - callback?: (err: mongodb.MongoError) => void): MongooseThenable; + export function connect(uris: string, options: ConnectionOptions, callback: (err: mongodb.MongoError) => void): null; + export function connect(uris: string, callback: (err: mongodb.MongoError) => void): null; + export function connect(uris: string, options?: ConnectionOptions): Promise; /** * Creates a Connection instance. @@ -130,16 +92,14 @@ declare module "mongoose" { export function createConnection(uri: string, options?: ConnectionOptions ): Connection; - export function createConnection(host: string, database_name: string, port?: number, - options?: ConnectionOptions - ): Connection; /** * Disconnects all connections. * @param fn called after all connection close. - * @returns pseudo-promise wrapper around this */ - export function disconnect(fn?: (error: any) => void): MongooseThenable; + export function disconnect(fn: (error?: any) => void): null; + /** Disconnects all connections. */ + export function disconnect(): Promise; /** Gets mongoose options */ export function get(key: string): any; @@ -173,26 +133,11 @@ declare module "mongoose" { * @param fn plugin callback * @param opts optional options */ - export function plugin(fn: Function, opts?: Object): typeof mongoose; + export function plugin(fn: Function, opts?: any): typeof mongoose; /** Sets mongoose options */ export function set(key: string, value: any): void; - type MongooseThenable = typeof mongoose & { - /** - * Ability to use mongoose object as a pseudo-promise so .connect().then() - * and .disconnect().then() are viable. - */ - then(onFulfill?: () => void | TRes | PromiseLike, - onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; - - /** - * Ability to use mongoose object as a pseudo-promise so .connect().then() - * and .disconnect().then() are viable. - */ - catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; - } - class CastError extends Error { /** * The Mongoose CastError constructor @@ -204,49 +149,6 @@ declare module "mongoose" { constructor(type: string, value: any, path: string, reason?: NativeError); } - /* - * section querystream.js - * http://mongoosejs.com/docs/api.html#querystream-js - * - * QueryStream can only be accessed using query#stream(), we only - * expose its interface here. - */ - interface QueryStream extends stream.Stream { - /** - * Provides a Node.js 0.8 style ReadStream interface for Queries. - * @event data emits a single Mongoose document - * @event error emits when an error occurs during streaming. This will emit before the close event. - * @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream - * is manually destroyed. After this event, no more events are emitted. - */ - constructor(query: Query, options?: { - /** - * optional function which accepts a mongoose document. The return value - * of the function will be emitted on data. - */ - transform?: Function; - [other: string]: any; - }): QueryStream; - - /** - * Destroys the stream, closing the underlying cursor, which emits the close event. - * No more events will be emitted after the close event. - */ - destroy(err?: NativeError): void; - - /** Pauses this stream. */ - pause(): void; - /** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */ - pipe(destination: T, options?: { end?: boolean; }): T; - /** Resumes this stream. */ - resume(): void; - - /** Flag stating whether or not this stream is paused. */ - paused: boolean; - /** Flag stating whether or not this stream is readable. */ - readable: boolean; - } - /* * section connection.js * http://mongoosejs.com/docs/api.html#connection-js @@ -288,7 +190,13 @@ declare module "mongoose" { options?: ConnectionOpenOptions, callback?: (err: any) => void): any; /** Helper for dropDatabase() */ - dropDatabase(callback?: (err: any) => void): Promise; + dropDatabase(callback?: (err: any) => void): Promise; + + /** Helper for creating a collection */ + createCollection(name: string, options?: mongodb.CollectionCreateOptions, cb?: (err: any, collection: mongodb.Collection) => void): Promise; + + /** Helper for dropCollection() */ + dropCollection(name: string, callback?: (err: any) => void): Promise; /** * Opens the connection to a replica set. @@ -308,7 +216,7 @@ declare module "mongoose" { * @param name name of the collection * @param options optional collection options */ - collection(name: string, options?: Object): Collection; + collection(name: string, options?: any): Collection; /** * Defines or retrieves a model. @@ -332,7 +240,7 @@ declare module "mongoose" { modelNames(): string[]; /** A hash of the global options that are associated with this connection */ - config: Object; + config: any; /** The mongodb.Db instance, set when the connection is opened */ db: mongodb.Db; @@ -445,6 +353,9 @@ declare module "mongoose" { /** See http://mongoosejs.com/docs/connections.html#use-mongo-client **/ useMongoClient?: boolean; + + /** See http://mongoosejs.com/docs/guide.html#bufferCommands */ + bufferCommands?: boolean; } interface ConnectionOptions extends @@ -463,7 +374,7 @@ declare module "mongoose" { * @param conn A MongooseConnection instance * @param opts optional collection options */ - new(name: string, conn: Connection, opts?: Object): Collection; + new(name: string, conn: Connection, opts?: any): Collection; /** Formatter for debug print args */ $format(arg: any): string; /** Debug print helper */ @@ -485,7 +396,7 @@ declare module "mongoose" { useDb(name: string): Connection; /** Expose the possible connection states. */ - static STATES: Object; + static STATES: any; } /* @@ -517,10 +428,10 @@ declare module "mongoose" { * {MIN} is replaced with the declared min value for the Number.min validator * {MAX} is replaced with the declared max value for the Number.max validator */ - static messages: Object; + static messages: any; /** For backwards compatibility. Same as mongoose.Error.messages */ - static Messages: Object; + static Messages: any; } interface EachAsyncOptions { @@ -550,7 +461,7 @@ declare module "mongoose" { * @event data Emitted when the stream is flowing and the next doc is ready * @event end Emitted when the stream is exhausted */ - constructor(query: Query, options: Object): QueryCursor; + constructor(query: Query, options: any): QueryCursor; /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ close(callback?: (error: any, result: any) => void): Promise; @@ -593,11 +504,11 @@ declare module "mongoose" { */ class VirtualType { /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */ - constructor(options: Object, name: string); + constructor(options: any, name: string); /** Applies getters to value using optional scope. */ - applyGetters(value: Object, scope: Object): any; + applyGetters(value: any, scope: any): any; /** Applies setters to value using optional scope. */ - applySetters(value: Object, scope: Object): any; + applySetters(value: any, scope: any): any; /** Defines a getter. */ get(fn: Function): this; /** Defines a setter. */ @@ -620,6 +531,9 @@ declare module "mongoose" { /** Adds key path / schema type pairs to this schema. */ add(obj: SchemaDefinition, prefix?: string): void; + /** Return a deep copy of this schema */ + clone(): Schema; + /** * Iterates the schemas paths similar to Array.forEach. * @param fn callback function @@ -639,7 +553,7 @@ declare module "mongoose" { * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert * expires option into seconds for the expireAfterSeconds in the above link. */ - index(fields: Object, options?: { + index(fields: any, options?: { expires?: string; [other: string]: any; }): this; @@ -678,7 +592,7 @@ declare module "mongoose" { * Registers a plugin for this schema. * @param plugin callback */ - plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; + plugin(plugin: (schema: Schema, options?: any) => void, opts?: any): this; /** * Defines a post hook for the document @@ -734,7 +648,7 @@ declare module "mongoose" { static(nameObj: { [name: string]: Function }): this; /** Creates a virtual type with the given name. */ - virtual(name: string, options?: Object): VirtualType; + virtual(name: string, options?: any): VirtualType; /** Returns the virtual type with the given name. */ virtualpath(name: string): VirtualType; @@ -748,7 +662,7 @@ declare module "mongoose" { * b/c they conflict with mongoose functionality. Using these key name * will throw an error. */ - static reserved: Object; + static reserved: any; /** Object of currently defined methods on this schema. */ methods: any; @@ -760,25 +674,23 @@ declare module "mongoose" { // Hook functions: https://github.com/vkarpov15/hooks-fixed interface HookSyncCallback { - (next: HookNextFunction, ...hookArgs:any[]): any; + (next: HookNextFunction): any; } interface HookAsyncCallback { - (next: HookNextFunction, done: HookDoneFunction, ...hookArgs: any[]): any; + (next: HookNextFunction, done: HookDoneFunction): any; } interface HookErrorCallback { - (error: Error): any; + (error?: Error): any; } interface HookNextFunction { - (error: Error): any; - (...hookArgs: any[]): any; + (error?: Error): any; } interface HookDoneFunction { - (error: Error): any; - (...hookArgs: any[]): any; + (error?: Error): any; } interface SchemaOptions { @@ -788,12 +700,15 @@ declare module "mongoose" { bufferCommands?: boolean; /** defaults to false */ capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; }; + /** Sets a default collation for every query and aggregation. */ + collation?: CollationOptions; /** no default */ collection?: string; /** defaults to "__t" */ discriminatorKey?: string; /** defaults to false. */ emitIndexErrors?: boolean; + excludeIndexes?: any; /** defaults to true */ id?: boolean; /** defaults to true */ @@ -803,38 +718,40 @@ declare module "mongoose" { read?: string; /** defaults to true. */ safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean }; + /** defaults to null */ shardKey?: boolean; /** defaults to true */ strict?: boolean; /** no default */ - toJSON?: Object; + toJSON?: DocumentToObjectOptions; /** no default */ - toObject?: Object; + toObject?: DocumentToObjectOptions; /** defaults to 'type' */ typeKey?: string; /** defaults to false */ useNestedStrict?: boolean; - /** defaults to false */ - usePushEach?: boolean; /** defaults to true */ validateBeforeSave?: boolean; /** defaults to "__v" */ versionKey?: string|boolean; - /** defaults to false */ - retainKeyOrder?: boolean; /** * skipVersioning allows excluding paths from * versioning (the internal revision will not be * incremented even if these paths are updated). */ - skipVersioning?: Object; + skipVersioning?: any; /** * If set timestamps, mongoose assigns createdAt * and updatedAt fields to your schema, the type * assigned is Date. */ - timestamps?: Object; + timestamps?: boolean | SchemaTimestampsConfig; + } + + interface SchemaTimestampsConfig { + createdAt?: boolean | string; + updatedAt?: boolean | string; } /* @@ -870,6 +787,8 @@ declare module "mongoose" { * - http://mongoosejs.com/docs/api.html#schema_Schema.Types */ interface SchemaTypeOpts { + alias?: string; + /* Common Options for all schema types */ type?: T; @@ -880,7 +799,7 @@ declare module "mongoose" { * Getters allow you to transform the representation of the data as it travels * from the raw mongodb document to the value that you see. */ - get?: (value: T, schematype?: this) => T | Object; + get?: (value: T, schematype?: this) => T | any; /** Declares the index options for this schematype. */ index?: SchemaTypeOpts.IndexOpts | boolean | string; @@ -892,7 +811,7 @@ declare module "mongoose" { required?: SchemaTypeOpts.RequiredFn | boolean | [boolean, string] | string | [string, string] | - Object; + any; /** * Sets default select() behavior for this path. @@ -900,19 +819,19 @@ declare module "mongoose" { * if it should be excluded by default. This setting can be overridden at * the query level. */ - select?: boolean | Object; + select?: boolean | any; /** * Setters allow you to transform the data before it gets to the raw mongodb * document and is set as a value on an actual key. */ - set?: (value: T, schematype?: this) => T | Object; + set?: (value: T, schematype?: this) => T | any; /** Declares a sparse index. */ - sparse?: boolean | Object; + sparse?: boolean | any; /** Declares a full text index. */ - text?: boolean | Object; + text?: boolean | any; /** * Adds validator(s) for this document path. @@ -922,27 +841,27 @@ declare module "mongoose" { validate?: RegExp | [RegExp, string] | SchemaTypeOpts.ValidateFn | [SchemaTypeOpts.ValidateFn, string] | SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.ValidateOpts[] | - Object; + SchemaTypeOpts.AsyncValidateOpts | SchemaTypeOpts.AsyncValidateOpts[]; /** Declares an unique index. */ - unique?: boolean | Object; + unique?: boolean | any; /* Options for specific schema types (String, Number, Date, etc.) */ /** String only - Adds an enum validator */ - enum?: T[] | SchemaTypeOpts.EnumOpts | Object; + enum?: T[] | SchemaTypeOpts.EnumOpts | any; /** String only - Adds a lowercase setter. */ - lowercase?: boolean | Object; + lowercase?: boolean | any; /** String only - Sets a regexp validator. */ - match?: RegExp | [RegExp, string] | Object; + match?: RegExp | [RegExp, string] | any; /** String only - Sets a maximum length validator. */ - maxlength?: number | [number, string] | Object; + maxlength?: number | [number, string] | any; /** String only - Sets a minimum length validator. */ - minlength?: number | [number, string] | Object; + minlength?: number | [number, string] | any; /** String only - Adds a trim setter. */ - trim?: boolean | Object; + trim?: boolean | any; /** String only - Adds an uppercase setter. */ - uppercase?: boolean | Object; + uppercase?: boolean | any; /** * Date, Number only - Sets a minimum number validator. @@ -950,7 +869,7 @@ declare module "mongoose" { */ min?: number | [number, string] | Date | [Date, string] | - Object; + any; /** * Date, Number only - Sets a maximum number validator. @@ -958,16 +877,16 @@ declare module "mongoose" { */ max?: number | [number, string] | Date | [Date, string] | - Object; + any; /** * Date only - Declares a TTL index (rounded to the nearest second) * for Date types only. */ - expires?: number | string | Object; + expires?: number | string | any; /** ObjectId only - Adds an auto-generated ObjectId default if turnOn is true. */ - auto?: boolean | Object; + auto?: boolean | any; [other: string]: any; } @@ -983,13 +902,26 @@ declare module "mongoose" { } interface ValidateFn { - (obj: RegExp | Function, message?: string, type?: string): T; + (value: T): boolean; } - interface ValidateOpts { - validator?: RegExp | Function, - msg?: string, - type?: string + interface AsyncValidateFn { + (value: T, done: (result: boolean) => void): void; + } + + interface ValidateOptsBase { + msg?: string; + type?: string; + } + + interface ValidateOpts extends ValidateOptsBase { + isAsync?: false; + validator?: RegExp | ValidateFn; + } + + interface AsyncValidateOpts extends ValidateOptsBase { + isAsync: true; + validator: AsyncValidateFn; } interface EnumOpts { @@ -1019,7 +951,7 @@ declare module "mongoose" { * Takes a populated field and returns it to its unpopulated state. * If the path was not populated, this is a no-op. */ - depopulate(path: string): void; + depopulate(path: string): this; /** * Returns true if the Document stores the same data as doc. @@ -1036,6 +968,9 @@ declare module "mongoose" { */ execPopulate(): Promise; + /** Checks if path was explicitly selected. If no projection, always returns true. */ + isDirectSelected(path: string): boolean; + /** * Returns the value of a path. * @param type optionally specify a type for on-the-fly attributes @@ -1046,13 +981,12 @@ declare module "mongoose" { * Initializes the document without setters or marking anything modified. * Called internally after a document is returned from mongodb. * @param doc document returned by mongo - * @param fn callback + * @param opts Options */ - init(doc: MongooseDocument, fn?: () => void): this; - init(doc: MongooseDocument, opts: Object, fn?: () => void): this; + init(doc: MongooseDocument, opts?: any): this; /** Helper for console.log */ - inspect(options?: Object): any; + inspect(options?: any): any; /** * Marks a path as invalid, causing validation to fail. @@ -1118,9 +1052,9 @@ declare module "mongoose" { * @param type optionally specify a type for "on-the-fly" attributes * @param options optionally specify options that modify the behavior of the set */ - set(path: string, val: any, options?: Object): this; - set(path: string, val: any, type: any, options?: Object): this; - set(value: Object): this; + set(path: string, val: any, options?: any): this; + set(path: string, val: any, type: any, options?: any): this; + set(value: any): this; /** * The return value of this method is used in calls to JSON.stringify(doc). @@ -1128,13 +1062,13 @@ declare module "mongoose" { * options to every document of your schema by default, set your schemas * toJSON option to the same argument. */ - toJSON(options?: DocumentToObjectOptions): Object; + toJSON(options?: DocumentToObjectOptions): any; /** * Converts this document into a plain javascript object, ready for storage in MongoDB. * Buffers are converted to instances of mongodb.Binary for proper storage. */ - toObject(options?: DocumentToObjectOptions): Object; + toObject(options?: DocumentToObjectOptions): any; /** Helper for console.log */ toString(): string; @@ -1146,8 +1080,8 @@ declare module "mongoose" { unmarkModified(path: string): void; /** Sends an update command with this document _id as the query selector. */ - update(doc: Object, callback?: (err: any, raw: any) => void): Query; - update(doc: Object, options: ModelUpdateOptions, + update(doc: any, callback?: (err: any, raw: any) => void): Query; + update(doc: any, options: ModelUpdateOptions, callback?: (err: any, raw: any) => void): Query; /** @@ -1156,7 +1090,7 @@ declare module "mongoose" { * @param callback callback called after validation completes, passing an error if one occurred */ validate(callback?: (err: any) => void): Promise; - validate(optional: Object, callback?: (err: any) => void): Promise; + validate(optional: any, callback?: (err: any) => void): Promise; /** * Executes registered validation rules (skipping asynchronous validators) for this document. @@ -1167,7 +1101,7 @@ declare module "mongoose" { validateSync(pathsToValidate?: string | string[]): Error; /** Hash containing current validation errors. */ - errors: Object; + errors: any; /** This documents _id. */ _id: any; /** Boolean flag specifying if the document is new. */ @@ -1199,17 +1133,11 @@ declare module "mongoose" { * @param ret The plain object representation which has been converted * @param options The options in use (either schema options or the options passed inline) */ - transform?: (doc: any, ret: Object, options: Object) => any; + transform?: (doc: any, ret: any, options: any) => any; /** depopulate any populated paths, replacing them with their original refs (defaults to false) */ depopulate?: boolean; /** whether to include the version key (defaults to true) */ versionKey?: boolean; - /** - * keep the order of object keys. If this is set to true, - * Object.keys(new Doc({ a: 1, b: 2}).toObject()) will - * always produce ['a', 'b'] (defaults to false) - */ - retainKeyOrder?: boolean; } namespace Types { @@ -1226,7 +1154,7 @@ declare module "mongoose" { * @param callback optional callback for compatibility with Document.prototype.remove */ remove(callback?: (err: any) => void): void; - remove(options: Object, callback?: (err: any) => void): void; + remove(options: any, callback?: (err: any) => void): void; } /* @@ -1327,7 +1255,7 @@ declare module "mongoose" { splice(...args: any[]): T[]; /** Returns a native js Array. */ - toObject(options?: Object): T[]; + toObject(options?: any): T[]; /** * Wraps Array#unshift with proper change tracking. @@ -1348,7 +1276,7 @@ declare module "mongoose" { * This is the same subdocument constructor used for casting. * @param obj the value to cast to this arrays SubDocument schema */ - create(obj: Object): T; + create(obj: any): T; /** * Searches array items for the first document with a matching _id. @@ -1364,7 +1292,7 @@ declare module "mongoose" { * @param options optional options to pass to each documents toObject * method call during conversion */ - toObject(options?: Object): T[]; + toObject(options?: any): T[]; } /* @@ -1419,7 +1347,7 @@ declare module "mongoose" { */ class Embedded extends MongooseDocument { /** Helper for console.log */ - inspect(): Object; + inspect(): any; /** * Marks a path as invalid, causing validation to fail. @@ -1478,20 +1406,30 @@ declare module "mongoose" { * Specifies arguments for a $and condition. * @param array array of conditions */ - and(array: Object[]): this; + and(array: any[]): this; /** Specifies the batchSize option. Cannot be used with distinct() */ batchSize(val: number): this; + /** Get the current error flag value */ + error(): Error | null; + /** Unset the error flag set on this query */ + error(unset: null): this; + /** + * Set the error flag on this query + * @param err The error flag + */ + error(err: Error): this; + /** * Specifies a $box condition * @param Upper Right Coords */ - box(val: Object): this; + box(val: any): this; box(lower: number[], upper: number[]): this; /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/ - cast(model: any, obj?: Object): Object; + cast(model: any, obj?: any): any; /** * Executes the query returning a Promise which will be @@ -1505,19 +1443,18 @@ declare module "mongoose" { * Specifies a $center or $centerSphere condition. * @deprecated Use circle instead. */ - center(area: Object): this; - center(path: string, area: Object): this; - + center(area: any): this; + center(path: string, area: any): this; /** * DEPRECATED Specifies a $centerSphere condition * @deprecated Use circle instead. */ - centerSphere(path: string, val: Object): this; - centerSphere(val: Object): this; + centerSphere(path: string, val: any): this; + centerSphere(val: any): this; /** Specifies a $center or $centerSphere condition. */ - circle(area: Object): this; - circle(path: string, area: Object): this; + circle(area: any): this; + circle(path: string, area: any): this; /** Adds a collation to this op (MongoDB 3.4 and up) */ collation(value: CollationOptions): this; @@ -1530,28 +1467,28 @@ declare module "mongoose" { * @param criteria mongodb selector */ count(callback?: (err: any, count: number) => void): Query; - count(criteria: Object, callback?: (err: any, count: number) => void): Query; + count(criteria: any, callback?: (err: any, count: number) => void): Query; /** * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a * Streams3-compatible interface, as well as a .next() function. */ - cursor(options?: Object): QueryCursor; + cursor(options?: any): QueryCursor; /** Declares or executes a distict() operation. Passing a callback executes the query. */ distinct(callback?: (err: any, res: any[]) => void): Query; distinct(field: string, callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, criteria: Object | Query, + distinct(field: string, criteria: any | Query, callback?: (err: any, res: any[]) => void): Query; /** Specifies an $elemMatch condition */ elemMatch(criteria: (elem: Query) => void): this; - elemMatch(criteria: Object): this; - elemMatch(path: string | Object | Function, criteria: (elem: Query) => void): this; - elemMatch(path: string | Object | Function, criteria: Object): this; + elemMatch(criteria: any): this; + elemMatch(path: string | any | Function, criteria: (elem: Query) => void): this; + elemMatch(path: string | any | Function, criteria: any): this; /** Specifies the complementary comparison value for paths specified with where() */ - equals(val: Object): this; + equals(val: any): this; /** Executes the query */ exec(callback?: (err: any, res: T) => void): Promise; @@ -1567,7 +1504,7 @@ declare module "mongoose" { * @param criteria mongodb selector */ find(callback?: (err: any, res: DocType[]) => void): DocumentQuery; - find(criteria: Object, + find(criteria: any, callback?: (err: any, res: DocType[]) => void): DocumentQuery; /** @@ -1578,7 +1515,7 @@ declare module "mongoose" { * @param projection optional fields to return */ findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery; - findOne(criteria: Object, + findOne(criteria: any, callback?: (err: any, res: DocType | null) => void): DocumentQuery; /** @@ -1587,9 +1524,9 @@ declare module "mongoose" { * callback. Executes immediately if callback is passed. */ findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; - findOneAndRemove(conditions: Object, + findOneAndRemove(conditions: any, callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; - findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, + findOneAndRemove(conditions: any, options: QueryFindOneAndRemoveOptions, callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; /** @@ -1598,11 +1535,11 @@ declare module "mongoose" { * the found document (if any) to the callback. The query executes immediately if callback is passed. */ findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery; - findOneAndUpdate(update: Object, + findOneAndUpdate(update: any, callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; - findOneAndUpdate(query: Object | Query, update: Object, + findOneAndUpdate(query: any | Query, update: any, callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; - findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, + findOneAndUpdate(query: any | Query, update: any, options: QueryFindOneAndUpdateOptions, callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; /** @@ -1642,7 +1579,7 @@ declare module "mongoose" { * Sets query hints. * @param val a hint object */ - hint(val: Object): this; + hint(val: any): this; /** * Specifies an $in query condition. @@ -1652,7 +1589,7 @@ declare module "mongoose" { in(path: string, val: any[]): this; /** Declares an intersects query for geometry(). MUST be used after where(). */ - intersects(arg?: Object): this; + intersects(arg?: any): this; /** * Sets the lean option. @@ -1696,7 +1633,7 @@ declare module "mongoose" { * Merges another Query or conditions object into this one. * When a Query is passed, conditions, field selection and options are merged. */ - merge(source: Object | Query): this; + merge(source: any | Query): this; /** Specifies a $mod condition */ mod(val: number[]): this; @@ -1710,15 +1647,15 @@ declare module "mongoose" { ne(path: string, val: any): this; /** Specifies a $near or $nearSphere condition. */ - near(val: Object): this; - near(path: string, val: Object): this; + near(val: any): this; + near(path: string, val: any): this; /** * DEPRECATED Specifies a $nearSphere condition * @deprecated Use query.near() instead with the spherical option set to true. */ - nearSphere(val: Object): this; - nearSphere(path: string, val: Object): this; + nearSphere(val: any): this; + nearSphere(path: string, val: any): this; /** * Specifies a $nin query condition. @@ -1731,13 +1668,13 @@ declare module "mongoose" { * Specifies arguments for a $nor condition. * @param array array of conditions */ - nor(array: Object[]): this; + nor(array: any[]): this; /** * Specifies arguments for an $or condition. * @param array array of conditions */ - or(array: Object[]): this; + or(array: any[]): this; /** Specifies a $polygon condition */ polygon(...coordinatePairs: number[][]): this; @@ -1755,8 +1692,8 @@ declare module "mongoose" { * @param match Conditions for the population query * @param options Options for the population query (sort, etc) */ - populate(path: string | Object, select?: string | Object, model?: any, - match?: Object, options?: Object): this; + populate(path: string | any, select?: string | any, model?: any, + match?: any, options?: any): this; populate(options: ModelPopulateOptions | ModelPopulateOptions[]): this; /** @@ -1764,7 +1701,7 @@ declare module "mongoose" { * @param pref one of the listed preference options or aliases * @tags optional tags for this query */ - read(pref: string, tags?: Object[]): this; + read(pref: string, tags?: any[]): this; /** * Specifies a $regex query condition. @@ -1779,11 +1716,11 @@ declare module "mongoose" { * you must first call remove() and then execute it by using the exec() method. * @param criteria mongodb selector */ - remove(callback?: (err: any) => void): Query; - remove(criteria: Object | Query, callback?: (err: any) => void): Query; + remove(callback?: (err: any) => void): Query; + remove(criteria: any | Query, callback?: (err: any) => void): Query; /** Specifies which document fields to include or exclude (also known as the query "projection") */ - select(arg: string | Object): this; + select(arg: string | any): this; /** Determines if field selection has been made. */ selected(): boolean; /** Determines if exclusive field selection has been made.*/ @@ -1791,7 +1728,7 @@ declare module "mongoose" { /** Determines if inclusive field selection has been made. */ selectedInclusively(): boolean; /** Sets query options. */ - setOptions(options: Object): this; + setOptions(options: any): this; /** * Specifies a $size query condition. @@ -1827,10 +1764,7 @@ declare module "mongoose" { * sort order of each path is ascending unless the path name is prefixed with - * which will be treated as descending. */ - sort(arg: string | Object): this; - - /** Returns a Node.js 0.8 style read stream interface. */ - stream(options?: { transform?: Function; }): QueryStream; + sort(arg: string | any): this; /** * Sets the tailable option (for use with capped collections). Cannot be used with distinct() @@ -1861,17 +1795,17 @@ declare module "mongoose" { * @param doc the update command */ update(callback?: (err: any, affectedRows: number) => void): Query; - update(doc: Object, callback?: (err: any, affectedRows: number) => void): Query; - update(criteria: Object, doc: Object, + update(doc: any, callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: any, doc: any, callback?: (err: any, affectedRows: number) => void): Query; - update(criteria: Object, doc: Object, options: QueryUpdateOptions, + update(criteria: any, doc: any, options: QueryUpdateOptions, callback?: (err: any, affectedRows: number) => void): Query; /** Specifies a path for use with chaining. */ - where(path?: string | Object, val?: any): this; + where(path?: string | any, val?: any): this; /** Defines a $within or $geoWithin argument for geo-spatial queries. */ - within(val?: Object): this; + within(val?: any): this; within(coordinate: number[], ...coordinatePairs: number[][]): this; /** Flag to opt out of using $geoWithin. */ @@ -1889,7 +1823,7 @@ declare module "mongoose" { /** puts a time limit on the query - requires mongodb >= 2.6.0 */ maxTimeMS?: number; /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - passRawResult?: boolean; + rawResult?: boolean; } interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { @@ -1898,7 +1832,7 @@ declare module "mongoose" { /** creates the object if it doesn't exist. defaults to false. */ upsert?: boolean; /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: Object | string; + fields?: any | string; /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ runValidators?: boolean; /** @@ -1941,7 +1875,7 @@ declare module "mongoose" { */ class Array extends SchemaType { /** Array SchemaType constructor */ - constructor(key: string, cast?: SchemaType, options?: Object); + constructor(key: string, cast?: SchemaType, options?: any); /** * Check if the given value satisfies a required validator. The given value @@ -1959,7 +1893,7 @@ declare module "mongoose" { */ class String extends SchemaType { /** String SchemaType constructor. */ - constructor(key: string, options?: Object); + constructor(key: string, options?: any); /** Check if the given value satisfies a required validator. */ checkRequired(value: any, doc: MongooseDocument): boolean; @@ -1968,7 +1902,7 @@ declare module "mongoose" { * Adds an enum validator * @param args enumeration values */ - enum(args: string | string[] | Object): this; + enum(args: string | string[] | any): this; /** Adds a lowercase setter. */ lowercase(): this; @@ -2010,7 +1944,7 @@ declare module "mongoose" { */ class DocumentArray extends Array { /** SubdocsArray SchemaType constructor */ - constructor(key: string, schema: Schema, options?: Object); + constructor(key: string, schema: Schema, options?: any); /** This schema type's name, to defend against minifiers that mangle function names. */ static schemaName: string; @@ -2022,7 +1956,7 @@ declare module "mongoose" { */ class Number extends SchemaType { /** Number SchemaType constructor. */ - constructor(key: string, options?: Object); + constructor(key: string, options?: any); /** Check if the given value satisfies a required validator. */ checkRequired(value: any, doc: MongooseDocument): boolean; @@ -2051,7 +1985,7 @@ declare module "mongoose" { */ class Date extends SchemaType { /** Date SchemaType constructor. */ - constructor(key: string, options?: Object); + constructor(key: string, options?: any); /** * Check if the given value satisfies a required validator. To satisfy @@ -2086,7 +2020,7 @@ declare module "mongoose" { */ class Buffer extends SchemaType { /** Buffer SchemaType constructor */ - constructor(key: string, options?: Object); + constructor(key: string, options?: any); /** * Check if the given value satisfies a required validator. To satisfy a @@ -2106,7 +2040,7 @@ declare module "mongoose" { */ class Boolean extends SchemaType { /** Boolean SchemaType constructor. */ - constructor(path: string, options?: Object); + constructor(path: string, options?: any); /** * Check if the given value satisfies a required validator. For a @@ -2125,7 +2059,7 @@ declare module "mongoose" { */ class ObjectId extends SchemaType { /** ObjectId SchemaType constructor. */ - constructor(key: string, options?: Object); + constructor(key: string, options?: any); /** * Adds an auto-generated ObjectId default if turnOn is true. @@ -2145,7 +2079,7 @@ declare module "mongoose" { */ class Decimal128 extends SchemaType { /** Decimal128 SchemaType constructor. */ - constructor(key: string, options?: Object); + constructor(key: string, options?: any); /** Check if the given value satisfies a required validator. */ checkRequired(value: any, doc: MongooseDocument): boolean; @@ -2160,7 +2094,7 @@ declare module "mongoose" { */ class Mixed extends SchemaType { /** Mixed SchemaType constructor. */ - constructor(path: string, options?: Object); + constructor(path: string, options?: any); /** This schema type's name, to defend against minifiers that mangle function names. */ static schemaName: string; @@ -2172,7 +2106,7 @@ declare module "mongoose" { */ class Embedded extends SchemaType { /** Sub-schema schematype constructor */ - constructor(schema: Schema, key: string, options?: Object); + constructor(schema: Schema, key: string, options?: any); } } } @@ -2187,11 +2121,17 @@ declare module "mongoose" { * Returned when calling Model.aggregate(). * @param ops aggregation operator(s) or operator array */ - constructor(ops?: Object | any[], ...args: any[]); + constructor(ops?: any | any[], ...args: any[]); /** Adds a cursor flag */ addCursorFlag(flag: string, value: boolean): this; + /** + * Appends a new $addFields operator to this aggregate pipeline. Requires MongoDB v3.4+ to work + * @param arg field specification + */ + addFields(arg: any): this; + /** * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) * @param value Should tell server it can use hard drive to store data during aggregation. @@ -2203,7 +2143,7 @@ declare module "mongoose" { * Appends new operators to this aggregate pipeline * @param ops operator(s) to append */ - append(...ops: Object[]): this; + append(...ops: any[]): this; /** Adds a collation. */ collation(options: CollationOptions): this; @@ -2214,7 +2154,7 @@ declare module "mongoose" { * is necessary. * @param options set the cursor batch size */ - cursor(options: Object): this; + cursor(options: any): this; // If cursor option is on, could return an object /** Executes the aggregate pipeline on the currently bound Model. */ @@ -2227,7 +2167,7 @@ declare module "mongoose" { * Appends a new custom $group operator to this aggregate pipeline. * @param arg $group operator contents */ - group(arg: Object): this; + group(arg: any): this; /** * Appends a new $limit operator to this aggregate pipeline. @@ -2239,13 +2179,13 @@ declare module "mongoose" { * Appends new custom $lookup operator(s) to this aggregate pipeline. * @param options to $lookup as described in the above link */ - lookup(options: Object): this; + lookup(options: any): this; /** * Appends a new custom $match operator to this aggregate pipeline. * @param arg $match operator contents */ - match(arg: Object): this; + match(arg: any): this; /** * Binds this aggregate to a model. @@ -2253,25 +2193,41 @@ declare module "mongoose" { */ model(model: any): this; + /** + * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. + * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if { allowDiskUse: true } is specified. + * @param options options to $graphLookup + */ + graphLookup(options: any): this; + /** * Appends a new $geoNear operator to this aggregate pipeline. * MUST be used as the first operator in the pipeline. */ - near(parameters: Object): this; + near(parameters: any): this; + + /** + * Lets you set arbitrary options, for middleware or plugins. + * @param value keys to merge into current options + */ + option(value: any): this; + + /** Returns the current pipeline */ + pipeline(): any[]; /** * Appends a new $project operator to this aggregate pipeline. * Mongoose query selection syntax is also supported. * @param arg field specification */ - project(arg: string | Object): this; + project(arg: string | any): this; /** * Sets the readPreference option for the aggregation query. * @param pref one of the listed preference options or their aliases * @param tags optional tags for this query */ - read(pref: string, tags?: Object[]): this; + read(pref: string, tags?: any[]): this; /** * Appends new custom $sample operator(s) to this aggregate pipeline. @@ -2292,7 +2248,7 @@ declare module "mongoose" { * of each path is ascending unless the path name is prefixed with - which will be treated * as descending. */ - sort(arg: string | Object): this; + sort(arg: string | any): this; /** Provides promise for aggregate. */ then(resolve?: (val: T) => void | TRes | PromiseLike, @@ -2318,7 +2274,7 @@ declare module "mongoose" { */ class SchemaType { /** SchemaType constructor */ - constructor(path: string, options?: Object, instance?: string); + constructor(path: string, options?: any, instance?: string); /** * Sets a default value for this SchemaType. @@ -2336,7 +2292,7 @@ declare module "mongoose" { * Declares the index options for this schematype. * Indexes are created in the background by default. Specify background: false to override. */ - index(options: Object | boolean | string): this; + index(options: any | boolean | string): this; /** * Adds a required validator to this SchemaType. The validator gets added @@ -2365,7 +2321,7 @@ declare module "mongoose" { * @param errorMsg optional error message * @param type optional validator type */ - validate(obj: RegExp | Function | Object, errorMsg?: string, + validate(obj: RegExp | Function | any, errorMsg?: string, type?: string): this; } @@ -2426,7 +2382,31 @@ declare module "mongoose" { * Model#ensureIndexes. If an error occurred it is passed with the event. * The fields, options, and index name are also passed. */ - new(doc?: Object): T; + new(doc?: any): T; + + /** + * Requires a replica set running MongoDB >= 3.6.0. Watches the underlying collection for changes using MongoDB change streams. + * This function does not trigger any middleware. In particular, it does not trigger aggregate middleware. + * @param options See https://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch + */ + watch(options?: mongodb.ChangeStreamOptions & {session?: any}): mongodb.ChangeStream; + + /** + * Translate any aliases fields/conditions so the final query or document object is pure + * @param raw fields/conditions that may contain aliased keys + * @return the translated 'pure' fields/conditions + */ + translateAliases(raw: any): any; + + /** + * Sends multiple insertOne, updateOne, updateMany, replaceOne, deleteOne, and/or deleteMany operations to the MongoDB server in one command. This is faster than sending multiple independent operations (like) if you use create()) because with bulkWrite() there is only one round trip to MongoDB. + * Mongoose will perform casting on all operations you provide. + * This function does not trigger any middleware, not save() nor update(). If you need to trigger save() middleware for every document use create() instead. + * @param writes Operations + * @param cb callback + * @return `BulkWriteOpResult` if the operation succeeds + */ + bulkWrite(writes: any[], cb?: (err: any, res: mongodb.BulkWriteOpResultObject) => void): Promise; /** * Finds a single document by its _id field. findById(id) is almost* @@ -2434,11 +2414,11 @@ declare module "mongoose" { * @param id value of _id to query by * @param projection optional fields to return */ - findById(id: Object | string | number, + findById(id: any | string | number, callback?: (err: any, res: T | null) => void): DocumentQuery; - findById(id: Object | string | number, projection: Object, + findById(id: any | string | number, projection: any, callback?: (err: any, res: T | null) => void): DocumentQuery; - findById(id: Object | string | number, projection: Object, options: Object, + findById(id: any | string | number, projection: any, options: any, callback?: (err: any, res: T | null) => void): DocumentQuery; model(name: string): Model; @@ -2453,13 +2433,13 @@ declare module "mongoose" { * Performs aggregations on the models collection. * If a callback is passed, the aggregate is executed and a Promise is returned. * If a callback is not passed, the aggregate itself is returned. - * @param ... aggregation pipeline operator(s) or operator array + * @param aggregations pipeline operator(s) or operator array */ - aggregate(...aggregations: Object[]): Aggregate; - aggregate(...aggregationsWithCallback: Object[]): Promise; + aggregate(aggregations: any[]): Aggregate; + aggregate(aggregations: any[], cb: Function): Promise; /** Counts number of matching documents in a database collection. */ - count(conditions: Object, callback?: (err: any, count: number) => void): Query; + count(conditions: any, callback?: (err: any, count: number) => void): Query; /** * Shortcut for saving one or more documents to the database. MyModel.create(docs) @@ -2467,8 +2447,8 @@ declare module "mongoose" { * Triggers the save() hook. */ create(docs: any[], callback?: (err: any, res: T[]) => void): Promise; - create(...docs: Object[]): Promise; - create(...docsWithCallback: Object[]): Promise; + create(...docs: any[]): Promise; + create(...docsWithCallback: any[]): Promise; /** * Adds a discriminator type. @@ -2479,7 +2459,7 @@ declare module "mongoose" { /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ distinct(field: string, callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, conditions: Object, + distinct(field: string, conditions: any, callback?: (err: any, res: any[]) => void): Query; /** @@ -2488,17 +2468,23 @@ declare module "mongoose" { * @param cb optional callback */ ensureIndexes(callback?: (err: any) => void): Promise; - ensureIndexes(options: Object, callback?: (err: any) => void): Promise; + ensureIndexes(options: any, callback?: (err: any) => void): Promise; + + /** + * Similar to ensureIndexes(), except for it uses the createIndex function. The ensureIndex() function checks to see if an index with that name already exists, and, if not, does not attempt to create the index. createIndex() bypasses this check. + * @param cb Optional callback + */ + createIndexes(cb?: (err: any) => void): Promise; /** * Finds documents. * @param projection optional fields to return */ find(callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: Object, callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: Object, projection?: Object | null, + find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery; + find(conditions: any, projection?: any | null, callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: Object, projection?: Object | null, options?: Object | null, + find(conditions: any, projection?: any | null, options?: any | null, callback?: (err: any, res: T[]) => void): DocumentQuery; @@ -2511,13 +2497,13 @@ declare module "mongoose" { * @param id value of _id to query by */ findByIdAndRemove(): DocumentQuery; - findByIdAndRemove(id: Object | number | string, + findByIdAndRemove(id: any | number | string, callback?: (err: any, res: T | null) => void): DocumentQuery; - findByIdAndRemove(id: Object | number | string, options: { + findByIdAndRemove(id: any | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: Object; + sort?: any; /** sets the document fields to return */ - select?: Object; + select?: any; }, callback?: (err: any, res: T | null) => void): DocumentQuery; /** @@ -2526,9 +2512,9 @@ declare module "mongoose" { * @param id value of _id to query by */ findByIdAndUpdate(): DocumentQuery; - findByIdAndUpdate(id: Object | number | string, update: Object, + findByIdAndUpdate(id: any | number | string, update: any, callback?: (err: any, res: T | null) => void): DocumentQuery; - findByIdAndUpdate(id: Object | number | string, update: Object, + findByIdAndUpdate(id: any | number | string, update: any, options: ModelFindByIdAndUpdateOptions, callback?: (err: any, res: T | null) => void): DocumentQuery; @@ -2537,11 +2523,11 @@ declare module "mongoose" { * The conditions are cast to their respective SchemaTypes before the command is sent. * @param projection optional fields to return */ - findOne(conditions?: Object, + findOne(conditions?: any, callback?: (err: any, res: T | null) => void): DocumentQuery; - findOne(conditions: Object, projection: Object, + findOne(conditions: any, projection: any, callback?: (err: any, res: T | null) => void): DocumentQuery; - findOne(conditions: Object, projection: Object, options: Object, + findOne(conditions: any, projection: any, options: any, callback?: (err: any, res: T | null) => void): DocumentQuery; /** @@ -2550,18 +2536,18 @@ declare module "mongoose" { * Executes immediately if callback is passed else a Query object is returned. */ findOneAndRemove(): DocumentQuery; - findOneAndRemove(conditions: Object, + findOneAndRemove(conditions: any, callback?: (err: any, res: T | null) => void): DocumentQuery; - findOneAndRemove(conditions: Object, options: { + findOneAndRemove(conditions: any, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose * which doc to update */ - sort?: Object; + sort?: any; /** puts a time limit on the query - requires mongodb >= 2.6.0 */ maxTimeMS?: number; /** sets the document fields to return */ - select?: Object; + select?: any; }, callback?: (err: any, res: T | null) => void): DocumentQuery; /** @@ -2571,34 +2557,19 @@ declare module "mongoose" { * if callback is passed else a Query object is returned. */ findOneAndUpdate(): DocumentQuery; - findOneAndUpdate(conditions: Object, update: Object, + findOneAndUpdate(conditions: any, update: any, callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; - findOneAndUpdate(conditions: Object, update: Object, + findOneAndUpdate(conditions: any, update: any, options: ModelFindOneAndUpdateOptions, callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; - /** - * geoNear support for Mongoose - * @param GeoJSON point or legacy coordinate pair [x,y] to search near - * @param options for the qurery - * @param callback optional callback for the query - */ - geoNear(point: number[] | { - type: string; - coordinates: number[] - }, options: { - /** return the raw object */ - lean?: boolean; - [other: string]: any; - }, callback?: (err: any, res: T[], stats: any) => void): DocumentQuery; - /** * Implements $geoSearch functionality for Mongoose * @param conditions an object that specifies the match condition (required) * @param options for the geoSearch, some (near, maxDistance) are required * @param callback optional callback */ - geoSearch(conditions: Object, options: { + geoSearch(conditions: any, options: { /** x,y point to search for */ near: number[]; /** the maximum distance from the point near that a result can be */ @@ -2614,7 +2585,7 @@ declare module "mongoose" { * pre-saved in the DB. The document returned has no paths marked * as modified initially. */ - hydrate(obj: Object): T; + hydrate(obj: any): T; /** * Shortcut for validating an array of documents and inserting them into @@ -2625,7 +2596,7 @@ declare module "mongoose" { */ insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): Promise; insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise; - insertMany(...docsWithCallback: Object[]): Promise; + insertMany(...docsWithCallback: any[]): Promise; /** * Executes a mapReduce command. @@ -2643,35 +2614,41 @@ declare module "mongoose" { * @param options A hash of key/val (path, options) used for population. * @param callback Optional callback, executed upon completion. Receives err and the doc(s). */ - populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], + populate(docs: any[], options: ModelPopulateOptions | ModelPopulateOptions[], callback?: (err: any, res: T[]) => void): Promise; - populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], + populate(docs: any, options: ModelPopulateOptions | ModelPopulateOptions[], callback?: (err: any, res: T) => void): Promise; /** Removes documents from the collection. */ - remove(conditions: Object, callback?: (err: any) => void): Query; - deleteOne(conditions: Object, callback?: (err: any) => void): Query; - deleteMany(conditions: Object, callback?: (err: any) => void): Query; + remove(conditions: any, callback?: (err: any) => void): Query; + deleteOne(conditions: any, callback?: (err: any) => void): Query; + deleteMany(conditions: any, callback?: (err: any) => void): Query; + + /** + * Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set). + * This function triggers the following middleware: replaceOne + */ + replaceOne(conditions: any, replacement: any, callback?: (err: any, raw: any) => void): Query; /** * Updates documents in the database without returning them. * All update values are cast to their appropriate SchemaTypes before being sent. */ - update(conditions: Object, doc: Object, + update(conditions: any, doc: any, callback?: (err: any, raw: any) => void): Query; - update(conditions: Object, doc: Object, options: ModelUpdateOptions, + update(conditions: any, doc: any, options: ModelUpdateOptions, callback?: (err: any, raw: any) => void): Query; - updateOne(conditions: Object, doc: Object, + updateOne(conditions: any, doc: any, callback?: (err: any, raw: any) => void): Query; - updateOne(conditions: Object, doc: Object, options: ModelUpdateOptions, + updateOne(conditions: any, doc: any, options: ModelUpdateOptions, callback?: (err: any, raw: any) => void): Query; - updateMany(conditions: Object, doc: Object, + updateMany(conditions: any, doc: any, callback?: (err: any, raw: any) => void): Query; - updateMany(conditions: Object, doc: Object, options: ModelUpdateOptions, + updateMany(conditions: any, doc: any, options: ModelUpdateOptions, callback?: (err: any, raw: any) => void): Query; /** Creates a Query, applies the passed conditions, and returns the Query. */ - where(path: string, val?: Object): Query; + where(path: string, val?: any): Query; } interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties { @@ -2684,6 +2661,11 @@ declare module "mongoose" { */ model(name: string): Model; + /** Override whether mongoose thinks this doc is deleted or not */ + isDeleted(isDeleted: boolean): void; + /** whether mongoose thinks this doc is deleted. */ + isDeleted(): boolean; + /** * Removes this document from the db. * @param fn optional callback @@ -2697,8 +2679,8 @@ declare module "mongoose" { * @param options.validateBeforeSave set to false to save without validating. * @param fn optional callback */ - save(options?: SaveOptions, fn?: (err: any, product: this, numAffected: number) => void): Promise; - save(fn?: (err: any, product: this, numAffected: number) => void): Promise; + save(options?: SaveOptions, fn?: (err: any, product: this) => void): Promise; + save(fn?: (err: any, product: this) => void): Promise; /** * Version using default version key. See http://mongoosejs.com/docs/guide.html#versionKey @@ -2765,27 +2747,22 @@ declare module "mongoose" { */ setDefaultsOnInsert?: boolean; /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: Object; + sort?: any; /** sets the document fields to return */ - select?: Object; + select?: any; /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - passRawResult?: boolean; + rawResult?: boolean; /** overwrites the schema's strict mode option for this update */ strict?: boolean; - /** - * if true, run all setters defined on the associated model's schema for all fields - * defined in the query and the update. - */ - runSettersOnQuery?: boolean; } interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: Object | string; + fields?: any | string; /** puts a time limit on the query - requires mongodb >= 2.6.0 */ maxTimeMS?: number; /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - passRawResult?: boolean; + rawResult?: boolean; } interface ModelPopulateOptions { @@ -2794,11 +2771,11 @@ declare module "mongoose" { /** optional fields to select */ select?: any; /** optional query conditions to match */ - match?: Object; + match?: any; /** optional name of the model to use for population */ model?: string; /** optional query options like sort, limit, etc */ - options?: Object; + options?: any; /** deep populate */ populate?: ModelPopulateOptions | ModelPopulateOptions[]; } @@ -2833,9 +2810,9 @@ declare module "mongoose" { map: Function | string; reduce: (key: Key, vals: T[]) => Val; /** query filter object. */ - query?: Object; + query?: any; /** sort input objects using this key */ - sort?: Object; + sort?: any; /** max number of documents */ limit?: number; /** keep temporary data default: false */ @@ -2843,7 +2820,7 @@ declare module "mongoose" { /** finalize function */ finalize?: (key: Key, val: Val) => Val; /** scope variables exposed to map/reduce/finalize during execution */ - scope?: Object; + scope?: any; /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ jsMode?: boolean; /** provide statistics on job execution time. default: false */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 92adb61d83..e63a0e612d 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -20,33 +20,31 @@ var cb = function () {}; * http://mongoosejs.com/docs/api.html#index-js */ var connectUri = 'mongodb://user:pass@localhost:port/database'; -mongoose.connect(connectUri).then(cb).catch(cb); -mongoose.connect(connectUri, { +const connection1: Promise = mongoose.connect(connectUri); +const connection2: Promise = mongoose.connect(connectUri, { user: 'larry', pass: 'housan', config: { autoIndex: true }, - mongos: true -}).then(cb); -mongoose.connect(connectUri, function (error) { + mongos: true, + bufferCommands: false +}); +const connection3: null = mongoose.connect(connectUri, function (error) { error.stack; }); + var mongooseConnection: mongoose.Connection = mongoose.createConnection(); +mongooseConnection.dropDatabase().then(()=>{}); +mongooseConnection.dropCollection('foo').then(()=>{}); mongoose.createConnection(connectUri).open(''); mongoose.createConnection(connectUri, { db: { native_parser: true } }).open(''); -mongoose.createConnection('localhost', 'database', 3000).open(''); -mongoose.createConnection('localhost', 'database', 3000, { - user: 'larry', - config: { - autoIndex: false - } -}).open(''); -mongoose.disconnect(cb).then(cb); +const dcWithCallback: null = mongoose.disconnect(cb); +const dcPromise: Promise = mongoose.disconnect(); mongoose.get('test'); mongoose.model('Actor', new mongoose.Schema({ name: String @@ -67,29 +65,6 @@ mongoose.Types.ObjectId; mongoose.Types.Decimal128; mongoose.version.toLowerCase(); -/* - * section querystream.js - * http://mongoosejs.com/docs/api.html#querystream-js - */ -var querystream = {}; -querystream.destroy(new Error()); -querystream.pause(); -querystream.pipe(process.stdout, {end: true}).end(); -querystream.resume(); -querystream.paused; -querystream.readable; -/* inherited properties */ -querystream.getMaxListeners(); -/* practical examples */ -var QSModel = {}; -var QSStream: mongoose.QueryStream = QSModel.find().stream(); -QSStream.on('data', function (doc: any) { - doc.save(); -}).on('error', function (err: any) { - throw err; -}).on('close', cb); -QSModel.where('created').gte(20000).stream().pipe(process.stdout); - /* * section collection.js * http://mongoosejs.com/docs/api.html#collection-js @@ -174,6 +149,8 @@ mongooseError.stack; mongoose.Error.messages.hasOwnProperty(''); mongoose.Error.Messages.hasOwnProperty(''); +const plural: string = mongoose.pluralize('foo'); + /* * section querycursor.js * http://mongoosejs.com/docs/api.html#querycursor-js @@ -209,6 +186,16 @@ querycursor.map(function (doc) { console.log(doc.foo); }); +QCModel.watch().once('change', (change: any) => { + console.log(change); +}); + +QCModel.watch({ + maxAwaitTimeMS: 10 +}).once('change', (change: any) => { + console.log(change); +}); + /* * section virtualtype.js * http://mongoosejs.com/docs/api.html#virtualtype-js @@ -369,7 +356,22 @@ new mongoose.Schema({ integerOnly: { type: Number, get: (v: number) => Math.round(v), - set: (v: number) => Math.round(v) + set: (v: number) => Math.round(v), + validate: { + isAsync: false, + validator: (val: number): boolean => { + return false; + } + } + }, + asyncValidated: { + type: Number, + validate: { + isAsync: true, + validator: (val: number, done): void => { + setImmediate(done, true); + } + } } }); new mongoose.Schema({ name: { type: String, validate: [ @@ -431,8 +433,8 @@ new mongoose.Schema({ }); export default function(schema: mongoose.Schema) { - schema.pre('init', function(this: mongoose.Document, next: (err?: Error) => void, data: any): void { - data.name = 'Hello world'; + schema.pre('init', function(this: mongoose.Document, next: (err?: Error) => void): void { + console.log('success!'); }); } @@ -442,13 +444,13 @@ export default function(schema: mongoose.Schema) { */ var doc = {}; doc.$isDefault('path').valueOf(); -doc.depopulate('path'); +const docDotDepopulate: mongoose.MongooseDocument = doc.depopulate('path'); doc.equals(doc).valueOf(); doc.execPopulate().then(function (arg) { arg.execPopulate(); }).catch(function (err) {}); doc.get('path', Number); -doc.init(doc, cb).init(doc, {}, cb); +doc.init(doc).init(doc, {}); doc.inspect(); doc.invalidate('path', new Error('hi'), 999).toString(); doc.isDirectModified('path').valueOf(); @@ -491,6 +493,7 @@ doc.validateSync(['path1', 'path2']).stack; var MyModel = mongoose.model('test', new mongoose.Schema({ name: { type: String, + alias: 'foo', default: 'Val ' } })); @@ -501,6 +504,14 @@ MyModel.findOne().populate('author').exec(function (err, doc) { doc.depopulate('author'); } }); +MyModel.replaceOne({foo: 'bar'}, {qux: 'baz'}).where(); +MyModel.replaceOne({foo: 'bar'}, {qux: 'baz'}, (err, raw) => {}) +MyModel.bulkWrite([{foo:'bar'}]).then(r => { + console.log(r.deletedCount); +}); +MyModel.bulkWrite([], (err, res) => { + console.log(res.modifiedCount) +}) doc.populate('path'); doc.populate({path: 'hello'}); doc.populate('path', cb) @@ -514,6 +525,8 @@ const ImageSchema = new mongoose.Schema({ id: {type: Number, unique: true, required: true, index: true}, }, { id: false }); +const clonedSchema: mongoose.Schema = new mongoose.Schema().clone(); + interface ImageDoc extends mongoose.Document { name: string, id: number @@ -731,7 +744,7 @@ query.findOne(function (err, res) { res.execPopulate(); }).findOne(); query.findOneAndRemove({name: 'aa'}, { - passRawResult: true + rawResult: true }, function (err, doc) { doc.execPopulate(); }).findOneAndRemove(); @@ -739,7 +752,7 @@ query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { }); query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { - passRawResult: true + rawResult: true }, cb); query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, cb); query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}); @@ -842,10 +855,6 @@ query.where('comments').slice([-10, 5]); query.snapshot().snapshot(true); query.sort({ field: 'asc', test: -1 }); query.sort('field -test'); -query.stream().on('data', function (doc: any) { -}).on('error', function (err: any) { -}).on('close', function () { -}); query.tailable().tailable(false); query.then(cb).catch(cb); (new (query.toConstructor())(1, 2, 3)).toConstructor(); @@ -1023,7 +1032,7 @@ schemaembedded.sparse(true); * http://mongoosejs.com/docs/api.html#aggregate-js */ var aggregate: mongoose.Aggregate; -aggregate = mongoose.model('ex').aggregate({ $match: { age: { $gte: 21 }}}); +aggregate = mongoose.model('ex').aggregate([{ $match: { age: { $gte: 21 }}}]); aggregate = new mongoose.Aggregate(); aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); @@ -1035,6 +1044,8 @@ aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); aggregate.collation({ locale: 'en_US', strength: 1 }); aggregate.cursor({ batchSize: 1000 }).exec().each(cb); aggregate.exec().then(cb).catch(cb); +aggregate.option({foo: 'bar'}).exec(); +const aggregateDotPipeline: any[] = aggregate.pipeline(); aggregate.explain(cb).then(cb).catch(cb); aggregate.group({ _id: "$department" }).group({ _id: "$department" }); aggregate.limit(10).limit(10); @@ -1241,7 +1252,7 @@ mongoose.model('').findOne({}) str.toLowerCase; }); -mongoose.model('').aggregate() +mongoose.model('').aggregate([]) .then(function (arg) { return 2; }).then(function (num) { @@ -1278,7 +1289,7 @@ MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { docs[0].__v; }); MongoModel.findById(999, function (err, doc) { - var handleSave = function(err: Error, product: mongoose.Document, numAffected: number) {}; + var handleSave = function(err: Error, product: mongoose.Document) {}; if (!doc) { return; } @@ -1290,9 +1301,9 @@ MongoModel.findById(999, function (err, doc) { doc.save({ safe: { w: 'majority', wtimeout: 10000 } }, handleSave).then(cb).catch(cb); // test if Typescript can infer the types of (err, product, numAffected) - doc.save(function(err, product, numAffected) { product.save(); }) + doc.save(function(err, product) { product.save(); }) .then(function(p) { p.save() }).catch(cb); - doc.save({ validateBeforeSave: false }, function(err, product, numAffected) { + doc.save({ validateBeforeSave: false }, function(err, product) { product.save(); }).then(function(p) { p.save() }).catch(cb); }); @@ -1311,10 +1322,13 @@ mongoModel.save().then(function (product) { product.save().then(cb).catch(cb); }); MongoModel.aggregate( - { $group: { _id: null, maxBalance: { $max: '$balance' }}} - , { $project: { _id: 0, maxBalance: 1 }} - , cb); -MongoModel.aggregate() + [ + { $group: { _id: null, maxBalance: { $max: '$balance' }}}, + { $project: { _id: 0, maxBalance: 1 }} + ], + cb +); +MongoModel.aggregate([]) .group({ _id: null, maxBalance: { $max: '$balance' } }) .exec(cb); MongoModel.count({ type: 'jungle' }, function (err, count) { @@ -1402,14 +1416,6 @@ MongoModel.findOneAndUpdate({}, {}, {}); MongoModel.findOneAndUpdate({}, {}, cb); MongoModel.findOneAndUpdate({}, {}); MongoModel.findOneAndUpdate(); -MongoModel.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { - results[0].on('data', cb); -}); -MongoModel.geoNear({ type : "Point", coordinates : [9,9] }, { - maxDistance : 5, spherical : true -}, function(err, results, stats) { - console.log(results); -}); MongoModel.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, function(err, res) { @@ -1649,3 +1655,47 @@ const x = new extended({ username: 'hi', // required in baseSchema email: 'beddiw', // required in extededSchema }); + +new mongoose.Schema({}, { + timestamps: { + createdAt: 'foo', + updatedAt: 'bar' + } +}); + +new mongoose.Schema({}, { + collation: { + strength: 1, + locale: 'en_US' + } +}); + +new mongoose.Schema({}, { + toObject: { + versionKey: false + }, + toJSON: { + depopulate: true + } +}) + +const aggregatePrototypeGraphLookup: mongoose.Aggregate = MyModel.aggregate([]).graphLookup({}); +const addFieldsAgg: mongoose.Aggregate = aggregatePrototypeGraphLookup.addFields({}) + +MyModel.findById('foo').then((doc: mongoose.Document) => { + const a: boolean = doc.isDirectSelected('bar'); + const b: boolean = doc.isDeleted(); + doc.isDeleted(true); +}); + +MyModel.translateAliases({}); + +const queryPrototypeError: Error | null = MyModel.findById({}).error(); +const queryProrotypeErrorSetUnset: mongoose.Query = MyModel.findById({}).error(null).error(new Error('foo')); + +MyModel.createIndexes().then(() => {}); +MyModel.createIndexes((err: any): void => {}).then(() => {}); + +mongoose.connection.createCollection('foo').then(() => {}); +mongoose.connection.createCollection('foo', {wtimeout: 5}).then(() => {}); +mongoose.connection.createCollection('foo', {wtimeout: 5}, (err: Error, coll): void => {coll.collectionName}).then(() => {}); diff --git a/types/mongoose/v4/README.md b/types/mongoose/v4/README.md new file mode 100644 index 0000000000..0ba91612e2 --- /dev/null +++ b/types/mongoose/v4/README.md @@ -0,0 +1,233 @@ +## MongooseJS Typescript Docs +Below are some examples of how to use these Definitions.
+Scenarios where the Typescript code is identical to plain Javascript code are omitted. + +### Table of Contents +* [Mongoose Methods, Properties, Constructors](#mongoose-methods-properties-constructors) +* [Creating and Saving Documents](#creating-and-saving-documents) +* [Promises](#promises) +* [Instance Methods, Virtual Properties](#instance-methods-and-virtual-properties) +* [Static Methods](#static-methods) +* [Plugins](#plugins) +* [FAQ and Common Mistakes](#faq-and-common-mistakes) + +#### Mongoose Methods, Properties, Constructors +You can call methods from the mongoose instance using: +```typescript +import * as mongoose from 'mongoose'; +var MyModel = mongoose.model(...); +var MySchema: mongoose.Schema = new mongoose.Schema(...); +``` + +Alternatively, you can import individual names and call them: +```typescript +import { model, Schema } from 'mongoose'; +var MyModel = model(...); +var MySchema: Schema = new Schema(...): +``` +[top](#mongoosejs-typescript-docs) + +#### Creating and Saving Documents +```typescript +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema: Schema = new Schema({ + username: { + type: String, + required: true, + unique: true + }, + age: Number, + friends: [String], + data: [Schema.Types.Mixed] +}); + +interface IUser extends Document { + username: string; + age: number; + friends: string[]; + data: any[]; +} + +var UserModel: Model = model('User', UserSchema); + +var user = new UserModel({name: 'Jane'}); +user.username; // IUser properties are available +user.save(); // mongoose Document methods are available + +UserModel.findOne({}, (err: any, user: IUser) => { + user.username; // IUser properties are available + user.save(); // mongoose Document methods are available +}); +``` +[top](#mongoosejs-typescript-docs) + +#### Promises +These definitions use `global.Promise` by default. If you would like to use mongoose's own mpromise +definition (which is deprecated), you can install definitions for [mongoose-promise](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/mongoose-promise). + +If you'd like to use something other than `global.Promise`, you'll need to create a simple `.d.ts` file: +```typescript +// promise-bluebird.d.ts +import * as Bluebird from 'bluebird'; + +declare module 'mongoose' { + type Promise = Bluebird; +} + +// promise-q.d.ts +import * as Q from 'q'; + +declare module 'mongoose' { + type Promise = Q.Promise; +} + +// another-promise.d.ts +... +``` +To use it, you will need to `/// ` in one of your source code files, +or include the `.d.ts` file in your compile. + +To assign the new promise library in your code, you will need to use one of the following options (since +Typescript does not allow assigning properties of imported modules): + +* `(mongoose).Promise = YOUR_PROMISE;` +* `require('mongoose').Promise = YOUR_PROMISE;` +* `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;` + +[top](#mongoosejs-typescript-docs) + +#### Instance Methods and Virtual Properties +```typescript +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema: Schema = new Schema({ + name: String +}); + +UserSchema.methods.method1 = function () { return '' }; + +UserSchema.virtual('nameInCaps').get(function () { + return this.name.toUpperCase(); +}); +UserSchema.virtual('nameInCaps').set(function (caps) { + this.name = caps.toLowerCase(); +}); + +interface IUser extends Document { + name: string; + method1: () => string; + nameInCaps: string; +} + +var UserModel: Model = model('User', UserSchema); +var user = new UserModel({name: 'Billy'}); + +user.method1(); // IUser methods are available +user.nameInCaps; // virtual properties can be used + +UserModel.findOne({}, (err: any, user: IUser) => { + user.method1(); // IUser methods are available + user.nameInCaps; // virtual properties can be used +}); +``` +[top](#mongoosejs-typescript-docs) + +#### Static Methods +```typescript +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema = new Schema({}); +UserSchema.statics.static1 = function () { return '' }; + +interface IUserDocument extends Document {...} +interface IUserModel extends Model { + static1: () => string; +} + +var UserModel: IUserModel = model('User', UserSchema); +UserModel.static1(); // static methods are available +``` +[top](#mongoosejs-typescript-docs) + +#### Plugins +To write definitions for plugins, extend the mongoose module and create a simple plugin module: +```typescript +// plugin.d.ts +declare module 'mongoose' { + export interface PassportLocalDocument {...} + export interface PassportLocalSchema extends Schema {...} + export interface PassportLocalModel extends Model {...} + ... +} + +declare module 'passport-local-mongoose' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema, options?: Object) => void; + export = _; +} + +// user.ts +import { + model, + PassportLocalDocument, + PassportLocalSchema, + PassportLocalModel + Schema +} from 'mongoose'; +import * as passportLocalMongoose from 'passport-local-mongoose'; + +var UserSchema: PassportLocalSchema = new Schema({}); +UserSchema.plugin(passportLocalMongoose, options); + +interface IUser extends PassportLocalDocument {...} +interface IUserModel extends PassportLocalModel {...} + +var UserModel: IUserModel = model('User', UserSchema); +``` +Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts)
+[top](#mongoosejs-typescript-docs) + +#### FAQ and Common Mistakes +**Q: When to use `mongoose.Schema.Types.ObjectId` and `mongoose.Types.ObjectId`**
+When creating schemas in code use `mongoose.Schema.Types.ObjectId`. This is not a type, this is an instance +of `SchemaType` containing metadata for the ObjectId type: +```typescript +var UserSchema = new mongoose.Schema({ + id: mongoose.Schema.Types.ObjectId +}); +``` +When defining your interface, you should use the type definition `mongoose.Types.ObjectId`: +```typescript +interface IUser extends mongoose.Document { + id: mongoose.Types.ObjectId; // for type-checking, doesn't affect code behaviour +} + +var UserSchema = new UserSchema({ + id: mongoose.Schema.Types.ObjectId; // for creating the schema only +}); + +var User = mongoose.model('User', UserSchema); +var user = new User({}); +user.id = new mongoose.Types.ObjectId(); +``` +[top](#mongoosejs-typescript-docs) + +**Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?**
+People have been using this for a long time: +```typescript +interface IUser extends mongoose.Document { + ... +} +``` +When it should really be this: +```typescript +interface IUser extends mongoose.model { + ... +} +``` +For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
+And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
+At some point in the future this may get fixed, which would require fixing your code. +
+[top](#mongoosejs-typescript-docs) diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts new file mode 100644 index 0000000000..5f416b513a --- /dev/null +++ b/types/mongoose/v4/index.d.ts @@ -0,0 +1,2905 @@ +// Type definitions for Mongoose 4.7.1 +// Project: http://mongoosejs.com/ +// Definitions by: simonxca , horiuchi , sindrenm , lukasz-zak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// +/// + + +/* + * Guidelines for maintaining these definitions: + * - If you spot an error here or there, please submit a PR. + * Give some examples/links to documentation if you can. + * + * For patches and minor releases: + * - Browse the changelog at https://github.com/Automattic/mongoose/blob/master/History.md + * and make necessary changes. Afterwards, update the version number at the top so we know + * which version we are on. + * + * For major releases: + * - Refer to the updated docs at http://mongoosejs.com/docs/api.html + * - On the left-hand side of the docs is a list of .js files. Reset and update the TODO list below + * then go through one-by-one, making any updates to params list, return type, etc. For documentation + * changes just copy/paste them into here. + * - Check the files off as you go. Some files below might not have anything in them. That's ok, this + * is just a simple heuristic to keep track of our progress. + * + * TODO for version 4.x [updated][tested]: + * [x][x] index.js + * [x][x] querystream.js + * [x][x] connection.js + * [x][x] utils.js + * [x][x] browser.js + * [x][x] drivers/node-mongodb-native/collection.js + * [x][x] drivers/node-mongodb-native/connection.js + * [x][x] error/messages.js + * [x][x] error/validation.js + * [x][x] error.js + * [x][x] querycursor.js + * [x][x] virtualtype.js + * [x][x] schema.js + * [x][x] document.js + * [x][x] types/subdocument.js + * [x][x] types/array.js + * [x][x] types/documentarray.js + * [x][x] types/buffer.js + * [x][x] types/objectid.js + * [x][x] types/embedded.js + * [x][x] query.js + * [x][x] schema/array.js + * [x][x] schema/string.js + * [x][x] schema/documentarray.js + * [x][x] schema/number.js + * [x][x] schema/date.js + * [x][x] schema/buffer.js + * [x][x] schema/boolean.js + * [x][x] schema/objectid.js + * [x][x] schema/mixed.js + * [x][x] schema/embedded.js + * [x][x] aggregate.js + * [x][x] schematype.js + * [x][x] promise.js + * [x][x] ES6Promise.js + * [x][x] model.js + * [x][x] collection.js + */ + +/* +For easier searching, add a header to each section like so: +To find a section, CTRL+F and type "section ___.js" +/* + * section filename.js + * http://mongoosejs.com/docs/api.html#filename-js + */ + +declare module "mongoose" { + import events = require('events'); + import mongodb = require('mongodb'); + import stream = require('stream'); + import mongoose = require('mongoose'); + + /* + * Some mongoose classes have the same name as the native JS classes + * Keep references to native classes using a "Native" prefix + */ + class NativeBuffer extends global.Buffer {} + class NativeDate extends global.Date {} + class NativeError extends global.Error {} + + /* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + */ + export var DocumentProvider: any; + // recursive constructor + export var Mongoose: new(...args: any[]) => typeof mongoose; + type Mongoose = typeof mongoose; + export var SchemaTypes: typeof Schema.Types; + + /** Expose connection states for user-land */ + export var STATES: any; + /** The default connection of the mongoose module. */ + export var connection: Connection; + /** The node-mongodb-native driver Mongoose uses. */ + export var mongo: typeof mongodb; + /** The Mongoose version */ + export var version: string; + + /** + * Opens the default mongoose connection. + * Options passed take precedence over options included in connection strings. + * @returns pseudo-promise wrapper around this + */ + export function connect(uris: string, + options?: ConnectionOptions, + callback?: (err: mongodb.MongoError) => void): MongooseThenable; + export function connect(uris: string, + callback?: (err: mongodb.MongoError) => void): MongooseThenable; + + /** + * Creates a Connection instance. + * Each connection instance maps to a single database. This method is helpful + * when mangaging multiple db connections. + * @param uri a mongodb:// URI + * @param options options to pass to the driver + * @returns the created Connection object + */ + export function createConnection(): Connection; + export function createConnection(uri: string, + options?: ConnectionOptions + ): Connection; + export function createConnection(host: string, database_name: string, port?: number, + options?: ConnectionOptions + ): Connection; + + /** + * Disconnects all connections. + * @param fn called after all connection close. + * @returns pseudo-promise wrapper around this + */ + export function disconnect(fn?: (error: any) => void): MongooseThenable; + + /** Gets mongoose options */ + export function get(key: string): any; + + /** + * Defines a model or retrieves it. + * Models defined on the mongoose instance are available to all connection + * created by the same mongoose instance. + * @param name model name + * @param collection (optional, induced from model name) + * @param skipInit whether to skip initialization (defaults to false) + */ + export function model(name: string, schema?: Schema, collection?: string, + skipInit?: boolean): Model; + export function model>( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean + ): U; + + /** + * Returns an array of model names created on this instance of Mongoose. + * Does not include names of models created using connection.model(). + */ + export function modelNames(): string[]; + + /** + * Declares a global plugin executed on all Schemas. + * Equivalent to calling .plugin(fn) on each Schema you create. + * @param fn plugin callback + * @param opts optional options + */ + export function plugin(fn: Function, opts?: any): typeof mongoose; + + /** Sets mongoose options */ + export function set(key: string, value: any): void; + + type MongooseThenable = typeof mongoose & { + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + then(onFulfill?: () => void | TRes | PromiseLike, + onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; + + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; + } + + class CastError extends Error { + /** + * The Mongoose CastError constructor + * @param type The name of the type + * @param value The value that failed to cast + * @param path The path a.b.c in the doc where this cast error occurred + * @param reason The original error that was thrown + */ + constructor(type: string, value: any, path: string, reason?: NativeError); + } + + /* + * section querystream.js + * http://mongoosejs.com/docs/api.html#querystream-js + * + * QueryStream can only be accessed using query#stream(), we only + * expose its interface here. + */ + interface QueryStream extends stream.Stream { + /** + * Provides a Node.js 0.8 style ReadStream interface for Queries. + * @event data emits a single Mongoose document + * @event error emits when an error occurs during streaming. This will emit before the close event. + * @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream + * is manually destroyed. After this event, no more events are emitted. + */ + constructor(query: Query, options?: { + /** + * optional function which accepts a mongoose document. The return value + * of the function will be emitted on data. + */ + transform?: Function; + [other: string]: any; + }): QueryStream; + + /** + * Destroys the stream, closing the underlying cursor, which emits the close event. + * No more events will be emitted after the close event. + */ + destroy(err?: NativeError): void; + + /** Pauses this stream. */ + pause(): void; + /** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */ + pipe(destination: T, options?: { end?: boolean; }): T; + /** Resumes this stream. */ + resume(): void; + + /** Flag stating whether or not this stream is paused. */ + paused: boolean; + /** Flag stating whether or not this stream is readable. */ + readable: boolean; + } + + /* + * section connection.js + * http://mongoosejs.com/docs/api.html#connection-js + * + * The Connection class exposed by require('mongoose') + * is actually the driver's NativeConnection class. + * connection.js defines a base class that the native + * versions extend. See: + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + abstract class ConnectionBase extends events.EventEmitter { + /** + * For practical reasons, a Connection equals a Db. + * @param base a mongoose instance + * @event connecting Emitted when connection.{open,openSet}() is executed on this connection. + * @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios. + * @event open Emitted after we connected and onOpen is executed on all of this connections models. + * @event disconnecting Emitted when connection.close() was executed. + * @event disconnected Emitted after getting disconnected from the db. + * @event close Emitted after we disconnected and onClose executed on all of this connections models. + * @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection. + * @event error Emitted when an error occurs on this connection. + * @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. + * @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. + */ + constructor(base: typeof mongoose); + + /** + * Opens the connection to MongoDB. + * @param mongodb://uri or the host to which you are connecting + * @param database database name + * @param port database port + * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. + * Mongoose defaults the server auto_reconnect options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * Options passed take precedence over options included in connection strings. + */ + open(connection_string: string, database?: string, port?: number, + options?: ConnectionOpenOptions, callback?: (err: any) => void): any; + + /** Helper for dropDatabase() */ + dropDatabase(callback?: (err: any) => void): Promise; + + /** + * Opens the connection to a replica set. + * @param uris comma-separated mongodb:// URIs + * @param database database name if not included in uris + * @param options passed to the internal driver + */ + openSet(uris: string, database?: string, options?: ConnectionOpenSetOptions, + callback?: (err: any) => void): any; + + /** Closes the connection */ + close(callback?: (err: any) => void): Promise; + + /** + * Retrieves a collection, creating it if not cached. + * Not typically needed by applications. Just talk to your collection through your model. + * @param name name of the collection + * @param options optional collection options + */ + collection(name: string, options?: any): Collection; + + /** + * Defines or retrieves a model. + * When no collection argument is passed, Mongoose produces a collection name by passing + * the model name to the utils.toCollectionName method. This method pluralizes the name. + * If you don't like this behavior, either pass a collection name or set your schemas + * collection name option. + * @param name the model name + * @param schema a schema. necessary when defining a model + * @param collection name of mongodb collection (optional) if not given it will be induced from model name + * @returns The compiled model + */ + model(name: string, schema?: Schema, collection?: string): Model; + model>( + name: string, + schema?: Schema, + collection?: string + ): U; + + /** Returns an array of model names created on this connection. */ + modelNames(): string[]; + + /** A hash of the global options that are associated with this connection */ + config: any; + + /** The mongodb.Db instance, set when the connection is opened */ + db: mongodb.Db; + + /** A hash of the collections associated with this connection */ + collections: { [index: string]: Collection }; + + /** + * Connection ready state + * 0 = disconnected + * 1 = connected + * 2 = connecting + * 3 = disconnecting + * Each state change emits its associated event name. + */ + readyState: number; + } + + interface ConnectionOptionsBase { + /** passed to the connection db instance */ + db?: any; + /** passed to the connection server instance(s) */ + server?: any; + /** passed to the connection ReplSet instance */ + replset?: any; + /** username for authentication */ + user?: string; + /** password for authentication */ + pass?: string; + /** options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) */ + auth?: any; + /** Use ssl connection (needs to have a mongod server with ssl support) (default: true) */ + ssl?: boolean; + /** Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) */ + sslValidate?: object; + /** Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. */ + poolSize?: number; + /** Reconnect on error (default: true) */ + autoReconnect?: boolean; + /** TCP KeepAlive on the socket with a X ms delay before start (default: 0). */ + keepAlive?: number; + /** TCP Connection timeout setting (default: 0) */ + connectTimeoutMS?: number; + /** TCP Socket timeout setting (default: 0) */ + socketTimeoutMS?: number; + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** If you're connected to a single server or mongos proxy (as opposed to a replica set), + * the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries + * times, and give up afterward. When the driver gives up, the mongoose connection emits a + * reconnectFailed event. (default: 30) */ + reconnectTries?: number; + /** Will wait # milliseconds between retries (default: 1000) */ + reconnectInterval?: number; + /** The name of the replicaset to connect to. */ + replicaSet?: string; + /** The current value of the parameter native_parser */ + nativeParser?: boolean; + /** Auth mechanism */ + authMechanism?: any; + /** Specify a journal write concern (default: false). */ + journal?: boolean; + /** The write concern */ + w?: number|string; + /** The write concern timeout. */ + wTimeoutMS?: number; + /** The ReadPreference mode as listed here: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */ + readPreference?: string; + /** An object representing read preference tags, see: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */ + readPreferencetags?: object; + /** Triggers the server instance to call ismaster (default: true). */ + monitoring?: boolean; + /** The interval of calling ismaster when monitoring is enabled (default: 10000). */ + haInterval?: number; + /** Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit (default: false). */ + domainsEnabled?: boolean; + /** How long driver keeps waiting for servers to come back up (default: Number.MAX_VALUE) */ + bufferMaxEntries?: number; + + // TODO + safe?: any; + fsync?: any; + rs_name?: any; + slaveOk?: any; + authdb?: any; + } + + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenOptions extends ConnectionOptionsBase { + /** mongoose-specific options */ + config?: { + /** + * set to false to disable automatic index creation for all + * models associated with this connection. + */ + autoIndex?: boolean; + }; + } + + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenSetOptions extends ConnectionOptionsBase { + /** + * If true, enables High Availability support for mongos + * If connecting to multiple mongos servers, set the mongos option to true. + */ + mongos?: boolean; + + /** sets the underlying driver's promise library (see http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html) */ + promiseLibrary?: any; + + /** See http://mongoosejs.com/docs/connections.html#use-mongo-client **/ + useMongoClient?: boolean; + } + + interface ConnectionOptions extends + ConnectionOpenOptions, + ConnectionOpenSetOptions {} + + /* + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ + var Collection: Collection; + interface Collection extends CollectionBase { + /** + * Collection constructor + * @param name name of the collection + * @param conn A MongooseConnection instance + * @param opts optional collection options + */ + new(name: string, conn: Connection, opts?: any): Collection; + /** Formatter for debug print args */ + $format(arg: any): string; + /** Debug print helper */ + $print(name: any, i: any, args: any[]): void; + /** Retreives information about this collections indexes. */ + getIndexes(): any; + } + + /* + * section drivers/node-mongodb-native/connection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + class Connection extends ConnectionBase { + /** + * Switches to a different database using the same connection pool. + * @param name The database name + * @returns New Connection Object + */ + useDb(name: string): Connection; + + /** Expose the possible connection states. */ + static STATES: any; + } + + /* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ + class ValidationError extends Error { + /** Console.log helper */ + toString(): string; + } + + /* + * section error.js + * http://mongoosejs.com/docs/api.html#error-js + */ + class Error extends global.Error { + /** + * MongooseError constructor + * @param msg Error message + */ + constructor(msg: string); + + /** + * The default built-in validator error messages. These may be customized. + * As you might have noticed, error messages support basic templating + * {PATH} is replaced with the invalid document path + * {VALUE} is replaced with the invalid value + * {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined" + * {MIN} is replaced with the declared min value for the Number.min validator + * {MAX} is replaced with the declared max value for the Number.max validator + */ + static messages: any; + + /** For backwards compatibility. Same as mongoose.Error.messages */ + static Messages: any; + } + + interface EachAsyncOptions { + /** defaults to 1 */ + parallel?: number; + } + + /* + * section querycursor.js + * http://mongoosejs.com/docs/api.html#querycursor-js + * + * Callback signatures are from: http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + * QueryCursor can only be accessed by query#cursor(), we only + * expose its interface to enable type-checking. + */ + interface QueryCursor extends stream.Readable { + /** + * A QueryCursor is a concurrency primitive for processing query results + * one document at a time. A QueryCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * Unless you're an advanced user, do not instantiate this class directly. + * Use Query#cursor() instead. + * @param options query options passed to .find() + * @event cursor Emitted when the cursor is created + * @event error Emitted when an error occurred + * @event data Emitted when the stream is flowing and the next doc is ready + * @event end Emitted when the stream is exhausted + */ + constructor(query: Query, options: any): QueryCursor; + + /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ + close(callback?: (error: any, result: any) => void): Promise; + + /** + * Execute fn for every document in the cursor. If fn returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * @param fn Function to be executed for every document in the cursor + * @param callback Executed when all docs have been processed + */ + eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise; + + /** + * Execute fn for every document in the cursor. If fn returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * @param fn Function to be executed for every document in the cursor + * @param options Async options (e. g. parallel function execution) + * @param callback Executed when all docs have been processed + */ + eachAsync(fn: (doc: T) => any, options: EachAsyncOptions, callback?: (err: any) => void): Promise; + + /** + * Registers a transform function which subsequently maps documents retrieved + * via the streams interface or .next() + */ + map(fn: (doc: T) => T): this; + + /** + * Get the next document from this cursor. Will return null when there are + * no documents left. + */ + next(callback?: (err: any, doc?: T) => void): Promise; + } + + /* + * section virtualtype.js + * http://mongoosejs.com/docs/api.html#virtualtype-js + */ + class VirtualType { + /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */ + constructor(options: any, name: string); + /** Applies getters to value using optional scope. */ + applyGetters(value: any, scope: any): any; + /** Applies setters to value using optional scope. */ + applySetters(value: any, scope: any): any; + /** Defines a getter. */ + get(fn: Function): this; + /** Defines a setter. */ + set(fn: Function): this; + } + + /* + * section schema.js + * http://mongoosejs.com/docs/api.html#schema-js + */ + class Schema extends events.EventEmitter { + /** + * Schema constructor. + * When nesting schemas, (children in the example above), always declare + * the child schema first before passing it into its parent. + * @event init Emitted after the schema is compiled into a Model. + */ + constructor(definition?: SchemaDefinition, options?: SchemaOptions); + + /** Adds key path / schema type pairs to this schema. */ + add(obj: SchemaDefinition, prefix?: string): void; + + /** + * Iterates the schemas paths similar to Array.forEach. + * @param fn callback function + * @returns this + */ + eachPath(fn: (path: string, type: SchemaType) => void): this; + + /** + * Gets a schema option. + * @param key option name + */ + get(key: string): any; + + /** + * Defines an index (most likely compound) for this schema. + * @param options Options to pass to MongoDB driver's createIndex() function + * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert + * expires option into seconds for the expireAfterSeconds in the above link. + */ + index(fields: any, options?: { + expires?: string; + [other: string]: any; + }): this; + + /** Compiles indexes from fields and schema-level indexes */ + indexes(): any[]; + + /** + * Loads an ES6 class into a schema. Maps setters + getters, static methods, and + * instance methods to schema virtuals, statics, and methods. + */ + loadClass(model: Function): this; + + /** + * Adds an instance method to documents constructed from Models compiled from this schema. + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + */ + method(method: string, fn: Function): this; + method(methodObj: { [name: string]: Function }): this; + + /** + * Gets/sets schema paths. + * Sets a path (if arity 2) + * Gets a path (if arity 1) + */ + path(path: string): SchemaType; + path(path: string, constructor: any): this; + + /** + * Returns the pathType of path for this schema. + * @returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + */ + pathType(path: string): string; + + /** + * Registers a plugin for this schema. + * @param plugin callback + */ + plugin(plugin: (schema: Schema, options?: any) => void, opts?: any): this; + + /** + * Defines a post hook for the document + * Post hooks fire on the event emitted from document instances of Models compiled + * from this schema. + * @param method name of the method to hook + * @param fn callback + */ + post(method: string, fn: ( + error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void + ) => void): this; + + post(method: string, fn: ( + doc: T, next: (err?: NativeError) => void + ) => void): this; + + /** + * Defines a pre hook for the document. + */ + pre(method: string, parallel: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback): this; + pre(method: string, fn: HookSyncCallback, errorCb?: HookErrorCallback): this; + + /** + * Adds a method call to the queue. + * @param name name of the document method to call later + * @param args arguments to pass to the method + */ + queue(name: string, args: any[]): this; + + /** + * Removes the given path (or [paths]). + */ + remove(path: string | string[]): void; + + /** + * @param invalidate refresh the cache + * @returns an Array of path strings that are required by this schema. + */ + requiredPaths(invalidate?: boolean): string[]; + + /** + * Sets/gets a schema option. + * @param key option name + * @param value if not passed, the current option value is returned + */ + set(key: string): any; + set(key: string, value: any): this; + + /** + * Adds static "class" methods to Models compiled from this schema. + */ + static(name: string, fn: Function): this; + static(nameObj: { [name: string]: Function }): this; + + /** Creates a virtual type with the given name. */ + virtual(name: string, options?: any): VirtualType; + + /** Returns the virtual type with the given name. */ + virtualpath(name: string): VirtualType; + + /** The allowed index types */ + static indexTypes: string[]; + + /** + * Reserved document keys. + * Keys in this object are names that are rejected in schema declarations + * b/c they conflict with mongoose functionality. Using these key name + * will throw an error. + */ + static reserved: any; + + /** Object of currently defined methods on this schema. */ + methods: any; + /** Object of currently defined statics on this schema. */ + statics: any; + /** The original object passed to the schema constructor */ + obj: any; + } + + // Hook functions: https://github.com/vkarpov15/hooks-fixed + interface HookSyncCallback { + (next: HookNextFunction, ...hookArgs:any[]): any; + } + + interface HookAsyncCallback { + (next: HookNextFunction, done: HookDoneFunction, ...hookArgs: any[]): any; + } + + interface HookErrorCallback { + (error: Error): any; + } + + interface HookNextFunction { + (error: Error): any; + (...hookArgs: any[]): any; + } + + interface HookDoneFunction { + (error: Error): any; + (...hookArgs: any[]): any; + } + + interface SchemaOptions { + /** defaults to null (which means use the connection's autoIndex option) */ + autoIndex?: boolean; + /** defaults to true */ + bufferCommands?: boolean; + /** defaults to false */ + capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; }; + /** no default */ + collection?: string; + /** defaults to "__t" */ + discriminatorKey?: string; + /** defaults to false. */ + emitIndexErrors?: boolean; + /** defaults to true */ + id?: boolean; + /** defaults to true */ + _id?: boolean; + /** controls document#toObject behavior when called manually - defaults to true */ + minimize?: boolean; + read?: string; + /** defaults to true. */ + safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean }; + /** defaults to null */ + shardKey?: boolean; + /** defaults to true */ + strict?: boolean; + /** no default */ + toJSON?: any; + /** no default */ + toObject?: any; + /** defaults to 'type' */ + typeKey?: string; + /** defaults to false */ + useNestedStrict?: boolean; + /** defaults to false */ + usePushEach?: boolean; + /** defaults to true */ + validateBeforeSave?: boolean; + /** defaults to "__v" */ + versionKey?: string|boolean; + /** defaults to false */ + retainKeyOrder?: boolean; + /** + * skipVersioning allows excluding paths from + * versioning (the internal revision will not be + * incremented even if these paths are updated). + */ + skipVersioning?: any; + /** + * If set timestamps, mongoose assigns createdAt + * and updatedAt fields to your schema, the type + * assigned is Date. + */ + timestamps?: any; + } + + /* + * Intellisense for Schema definitions + */ + interface SchemaDefinition { + [path: string]: SchemaTypeOpts | Schema | SchemaType; + } + + /* + * The standard options available when configuring a schema type: + * new Schema({ + * name: { + * type: String, + * required: true, + * ... + * } + * }); + * + * Note: the properties have Object as a fallback type: | Object + * because this interface does not apply to a schematype that + * does not have a type property. Ex: + * new Schema({ + * name: { + * first: String, // since name does not have a "type" property + * last: String // first and last can have any valid type + * ... + * } + * }); + * + * References: + * - http://mongoosejs.com/docs/schematypes.html + * - http://mongoosejs.com/docs/api.html#schema_Schema.Types + */ + interface SchemaTypeOpts { + /* Common Options for all schema types */ + type?: T; + + /** Sets a default value for this SchemaType. */ + default?: SchemaTypeOpts.DefaultFn | T; + + /** + * Getters allow you to transform the representation of the data as it travels + * from the raw mongodb document to the value that you see. + */ + get?: (value: T, schematype?: this) => T | any; + + /** Declares the index options for this schematype. */ + index?: SchemaTypeOpts.IndexOpts | boolean | string; + + /** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using unshift(). + */ + required?: SchemaTypeOpts.RequiredFn | + boolean | [boolean, string] | + string | [string, string] | + any; + + /** + * Sets default select() behavior for this path. + * Set to true if this path should always be included in the results, false + * if it should be excluded by default. This setting can be overridden at + * the query level. + */ + select?: boolean | any; + + /** + * Setters allow you to transform the data before it gets to the raw mongodb + * document and is set as a value on an actual key. + */ + set?: (value: T, schematype?: this) => T | any; + + /** Declares a sparse index. */ + sparse?: boolean | any; + + /** Declares a full text index. */ + text?: boolean | any; + + /** + * Adds validator(s) for this document path. + * Validators always receive the value to validate as their first argument + * and must return Boolean. Returning false means validation failed. + */ + validate?: RegExp | [RegExp, string] | + SchemaTypeOpts.ValidateFn | [SchemaTypeOpts.ValidateFn, string] | + SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.ValidateOpts[] | + any; + + /** Declares an unique index. */ + unique?: boolean | any; + + + /* Options for specific schema types (String, Number, Date, etc.) */ + /** String only - Adds an enum validator */ + enum?: T[] | SchemaTypeOpts.EnumOpts | any; + /** String only - Adds a lowercase setter. */ + lowercase?: boolean | any; + /** String only - Sets a regexp validator. */ + match?: RegExp | [RegExp, string] | any; + /** String only - Sets a maximum length validator. */ + maxlength?: number | [number, string] | any; + /** String only - Sets a minimum length validator. */ + minlength?: number | [number, string] | any; + /** String only - Adds a trim setter. */ + trim?: boolean | any; + /** String only - Adds an uppercase setter. */ + uppercase?: boolean | any; + + /** + * Date, Number only - Sets a minimum number validator. + * Sets a minimum date validator. + */ + min?: number | [number, string] | + Date | [Date, string] | + any; + + /** + * Date, Number only - Sets a maximum number validator. + * Sets a maximum date validator. + */ + max?: number | [number, string] | + Date | [Date, string] | + any; + + /** + * Date only - Declares a TTL index (rounded to the nearest second) + * for Date types only. + */ + expires?: number | string | any; + + /** ObjectId only - Adds an auto-generated ObjectId default if turnOn is true. */ + auto?: boolean | any; + + [other: string]: any; + } + + // Interfaces specific to schema type options should be scoped in this namespace + namespace SchemaTypeOpts { + interface DefaultFn { + (...args: any[]): T; + } + + interface RequiredFn { + (required: boolean, message?: string): T; + } + + interface ValidateFn { + (obj: RegExp | Function, message?: string, type?: string): T; + } + + interface ValidateOpts { + validator?: RegExp | Function, + msg?: string, + type?: string + } + + interface EnumOpts { + values?: T[]; + message?: string; + } + + interface IndexOpts { + background?: boolean, + expires?: number | string + sparse?: boolean, + type?: string, + unique?: boolean, + } + } + + /* + * section document.js + * http://mongoosejs.com/docs/api.html#document-js + */ + interface MongooseDocument extends MongooseDocumentOptionals { } + class MongooseDocument { + /** Checks if a path is set to its default. */ + $isDefault(path?: string): boolean; + + /** + * Takes a populated field and returns it to its unpopulated state. + * If the path was not populated, this is a no-op. + */ + depopulate(path: string): void; + + /** + * Returns true if the Document stores the same data as doc. + * Documents are considered equal when they have matching _ids, unless neither document + * has an _id, in which case this function falls back to usin deepEqual(). + * @param doc a document to compare + */ + equals(doc: MongooseDocument): boolean; + + /** + * Explicitly executes population and returns a promise. + * Useful for ES2015 integration. + * @returns promise that resolves to the document when population is done + */ + execPopulate(): Promise; + + /** + * Returns the value of a path. + * @param type optionally specify a type for on-the-fly attributes + */ + get(path: string, type?: any): any; + + /** + * Initializes the document without setters or marking anything modified. + * Called internally after a document is returned from mongodb. + * @param doc document returned by mongo + * @param fn callback + */ + init(doc: MongooseDocument, fn?: () => void): this; + init(doc: MongooseDocument, opts: any, fn?: () => void): this; + + /** Helper for console.log */ + inspect(options?: any): any; + + /** + * Marks a path as invalid, causing validation to fail. + * The errorMsg argument will become the message of the ValidationError. + * The value argument (if passed) will be available through the ValidationError.value property. + * @param path the field to invalidate + * @param errorMsg the error which states the reason path was invalid + * @param value optional invalid value + * @param kind optional kind property for the error + * @returns the current ValidationError, with all currently invalidated paths + */ + invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + + /** Returns true if path was directly set and modified, else false. */ + isDirectModified(path: string): boolean; + + /** Checks if path was initialized */ + isInit(path: string): boolean; + + /** + * Returns true if this document was modified, else false. + * If path is given, checks if a path or any full path containing path as part of its path + * chain has been modified. + */ + isModified(path?: string): boolean; + + /** Checks if path was selected in the source query which initialized this document. */ + isSelected(path: string): boolean; + + /** + * Marks the path as having pending changes to write to the db. + * Very helpful when using Mixed types. + * @param path the path to mark modified + */ + markModified(path: string): void; + + /** Returns the list of paths that have been modified. */ + modifiedPaths(): string[]; + + /** + * Populates document references, executing the callback when complete. + * If you want to use promises instead, use this function with + * execPopulate() + * Population does not occur unless a callback is passed or you explicitly + * call execPopulate(). Passing the same path a second time will overwrite + * the previous path options. See Model.populate() for explaination of options. + * @param path The path to populate or an options object + * @param names The properties to fetch from the populated document + * @param callback When passed, population is invoked + */ + populate(callback: (err: any, res: this) => void): this; + populate(path: string, callback?: (err: any, res: this) => void): this; + populate(path: string, names: string, callback?: (err: any, res: this) => void): this; + populate(options: ModelPopulateOptions | ModelPopulateOptions[], callback?: (err: any, res: this) => void): this; + + /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ + populated(path: string): any; + + /** + * Sets the value of a path, or many paths. + * @param path path or object of key/vals to set + * @param val the value to set + * @param type optionally specify a type for "on-the-fly" attributes + * @param options optionally specify options that modify the behavior of the set + */ + set(path: string, val: any, options?: any): this; + set(path: string, val: any, type: any, options?: any): this; + set(value: any): this; + + /** + * The return value of this method is used in calls to JSON.stringify(doc). + * This method accepts the same options as Document#toObject. To apply the + * options to every document of your schema by default, set your schemas + * toJSON option to the same argument. + */ + toJSON(options?: DocumentToObjectOptions): any; + + /** + * Converts this document into a plain javascript object, ready for storage in MongoDB. + * Buffers are converted to instances of mongodb.Binary for proper storage. + */ + toObject(options?: DocumentToObjectOptions): any; + + /** Helper for console.log */ + toString(): string; + + /** + * Clears the modified state on the specified path. + * @param path the path to unmark modified + */ + unmarkModified(path: string): void; + + /** Sends an update command with this document _id as the query selector. */ + update(doc: any, callback?: (err: any, raw: any) => void): Query; + update(doc: any, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** + * Executes registered validation rules for this document. + * @param optional options internal options + * @param callback callback called after validation completes, passing an error if one occurred + */ + validate(callback?: (err: any) => void): Promise; + validate(optional: any, callback?: (err: any) => void): Promise; + + /** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * This method is useful if you need synchronous validation. + * @param pathsToValidate only validate the given paths + * @returns MongooseError if there are errors during validation, or undefined if there is no error. + */ + validateSync(pathsToValidate?: string | string[]): Error; + + /** Hash containing current validation errors. */ + errors: any; + /** This documents _id. */ + _id: any; + /** Boolean flag specifying if the document is new. */ + isNew: boolean; + /** The documents schema. */ + schema: Schema; + } + + interface MongooseDocumentOptionals { + /** + * Virtual getter that by default returns the document's _id field cast to a string, + * or in the case of ObjectIds, its hexString. This id getter may be disabled by + * passing the option { id: false } at schema construction time. If disabled, id + * behaves like any other field on a document and can be assigned any value. + */ + id?: any; + } + + interface DocumentToObjectOptions { + /** apply all getters (path and virtual getters) */ + getters?: boolean; + /** apply virtual getters (can override getters option) */ + virtuals?: boolean; + /** remove empty objects (defaults to true) */ + minimize?: boolean; + /** + * A transform function to apply to the resulting document before returning + * @param doc The mongoose document which is being converted + * @param ret The plain object representation which has been converted + * @param options The options in use (either schema options or the options passed inline) + */ + transform?: (doc: any, ret: any, options: any) => any; + /** depopulate any populated paths, replacing them with their original refs (defaults to false) */ + depopulate?: boolean; + /** whether to include the version key (defaults to true) */ + versionKey?: boolean; + /** + * keep the order of object keys. If this is set to true, + * Object.keys(new Doc({ a: 1, b: 2}).toObject()) will + * always produce ['a', 'b'] (defaults to false) + */ + retainKeyOrder?: boolean; + } + + namespace Types { + /* + * section types/subdocument.js + * http://mongoosejs.com/docs/api.html#types-subdocument-js + */ + class Subdocument extends MongooseDocument { + /** Returns the top level document of this sub-document. */ + ownerDocument(): MongooseDocument; + + /** + * Null-out this subdoc + * @param callback optional callback for compatibility with Document.prototype.remove + */ + remove(callback?: (err: any) => void): void; + remove(options: any, callback?: (err: any) => void): void; + } + + /* + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ + class Array extends global.Array { + /** + * Atomically shifts the array at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. + */ + $shift(): T; + + /** Alias of pull */ + remove(...args: any[]): this; + + /** + * Pops the array atomically at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. + */ + $pop(): T; + + /** + * Adds values to the array if not already present. + * @returns the values that were added + */ + addToSet(...args: any[]): T[]; + + /** + * Return the index of obj or -1 if not found. + * @param obj he item to look for + */ + indexOf(obj: any): number; + + /** Helper for console.log */ + inspect(): any; + + /** + * Marks the entire array as modified, which if saved, will store it as a $set + * operation, potentially overwritting any changes that happen between when you + * retrieved the object and when you save it. + * @returns new length of the array + */ + nonAtomicPush(...args: any[]): number; + + /** + * Wraps Array#pop with proper change tracking. + * marks the entire array as modified which will pass the entire thing to $set + * potentially overwritting any changes that happen between when you retrieved + * the object and when you save it. + */ + pop(): T; + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * the Document.equals() function. + */ + pull(...args: any[]): this; + + /** + * Wraps Array#push with proper change tracking. + * @returns new length of the array + */ + push(...args: any[]): number; + + /** Sets the casted val at index i and marks the array modified. */ + set(i: number, val: any): this; + + /** + * Wraps Array#shift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + shift(): T; + + /** + * Wraps Array#sort with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + // some lib.d.ts have return type "this" and others have return type "T[]" + // which causes errors. Let the inherited array provide the sort() method. + //sort(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Wraps Array#splice with proper change tracking and casting. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + splice(...args: any[]): T[]; + + /** Returns a native js Array. */ + toObject(options?: any): T[]; + + /** + * Wraps Array#unshift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + unshift(...args: any[]): number; + } + + /* + * section types/documentarray.js + * http://mongoosejs.com/docs/api.html#types-documentarray-js + */ + class DocumentArray extends Types.Array { + /** + * Creates a subdocument casted to this schema. + * This is the same subdocument constructor used for casting. + * @param obj the value to cast to this arrays SubDocument schema + */ + create(obj: any): T; + + /** + * Searches array items for the first document with a matching _id. + * @returns the subdocument or null if not found. + */ + id(id: ObjectId | string | number | NativeBuffer): T; + + /** Helper for console.log */ + inspect(): T[]; + + /** + * Returns a native js Array of plain js objects + * @param options optional options to pass to each documents toObject + * method call during conversion + */ + toObject(options?: any): T[]; + } + + /* + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ + class Buffer extends global.Buffer { + /** + * Copies the buffer. + * Buffer#copy does not mark target as modified so you must copy + * from a MongooseBuffer for it to work as expected. This is a + * work around since copy modifies the target, not this. + */ + copy(target: NativeBuffer, ...nodeBufferArgs: any[]): number; + + /** Determines if this buffer is equals to other buffer */ + equals(other: NativeBuffer): boolean; + + /** Sets the subtype option and marks the buffer modified. */ + subtype(subtype: number): void; + + /** Converts this buffer to its Binary type representation. */ + toObject(subtype?: number): mongodb.Binary; + + /** Writes the buffer. */ + write(string: string, ...nodeBufferArgs: any[]): number; + } + + /* + * section types/objectid.js + * http://mongoosejs.com/docs/api.html#types-objectid-js + */ + var ObjectId: ObjectIdConstructor; + + // mongodb.ObjectID does not allow mongoose.Types.ObjectId(id). This is + // commonly used in mongoose and is found in an example in the docs: + // http://mongoosejs.com/docs/api.html#aggregate_Aggregate + // constructor exposes static methods of mongodb.ObjectID and ObjectId(id) + type ObjectIdConstructor = typeof mongodb.ObjectID & { + (s?: string | number): mongodb.ObjectID; + }; + + // var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not + // the ObjectIdConstructor, so we add the interface below + interface ObjectId extends mongodb.ObjectID {} + + class Decimal128 extends mongodb.Decimal128 {} + + /* + * section types/embedded.js + * http://mongoosejs.com/docs/api.html#types-embedded-js + */ + class Embedded extends MongooseDocument { + /** Helper for console.log */ + inspect(): any; + + /** + * Marks a path as invalid, causing validation to fail. + * @param path the field to invalidate + * @param err error which states the reason path was invalid + */ + invalidate(path: string, err: string | NativeError): boolean; + + /** Returns the top level document of this sub-document. */ + ownerDocument(): MongooseDocument; + /** Returns this sub-documents parent document. */ + parent(): MongooseDocument; + /** Returns this sub-documents parent array. */ + parentArray(): DocumentArray; + + /** Removes the subdocument from its parent array. */ + remove(options?: { + noop?: boolean; + }, fn?: (err: any) => void): this; + + /** + * Marks the embedded doc modified. + * @param path the path which changed + */ + markModified(path: string): void; + } + } + + /* + * section query.js + * http://mongoosejs.com/docs/api.html#query-js + * + * Query is for backwards compatibility. Example: Query.find() returns Query. + * If later in the query chain a method returns Query, we will need to know type T. + * So we save this type as the second type parameter in DocumentQuery. Since people have + * been using Query, we set it as an alias of DocumentQuery. + */ + class Query extends DocumentQuery {} + class DocumentQuery extends mquery { + /** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * Only use $where when you have a condition that cannot be met using other MongoDB + * operators like $lt. Be sure to read about all of its caveats before using. + * @param js javascript string or function + */ + $where(js: string | Function): this; + + /** + * Specifies an $all query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + all(val: number): this; + all(path: string, val: number): this; + + /** + * Specifies arguments for a $and condition. + * @param array array of conditions + */ + and(array: any[]): this; + + /** Specifies the batchSize option. Cannot be used with distinct() */ + batchSize(val: number): this; + + /** + * Specifies a $box condition + * @param Upper Right Coords + */ + box(val: any): this; + box(lower: number[], upper: number[]): this; + + /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/ + cast(model: any, obj?: any): any; + + /** + * Executes the query returning a Promise which will be + * resolved with either the doc(s) or rejected with the error. + * Like .then(), but only takes a rejection handler. + */ + catch(reject?: (err: any) => void | TRes | PromiseLike): Promise; + + /** + * DEPRECATED Alias for circle + * Specifies a $center or $centerSphere condition. + * @deprecated Use circle instead. + */ + center(area: any): this; + center(path: string, area: any): this; + + /** + * DEPRECATED Specifies a $centerSphere condition + * @deprecated Use circle instead. + */ + centerSphere(path: string, val: any): this; + centerSphere(val: any): this; + + /** Specifies a $center or $centerSphere condition. */ + circle(area: any): this; + circle(path: string, area: any): this; + + /** Adds a collation to this op (MongoDB 3.4 and up) */ + collation(value: CollationOptions): this; + + /** Specifies the comment option. Cannot be used with distinct() */ + comment(val: string): this; + + /** + * Specifying this query as a count query. Passing a callback executes the query. + * @param criteria mongodb selector + */ + count(callback?: (err: any, count: number) => void): Query; + count(criteria: any, callback?: (err: any, count: number) => void): Query; + + /** + * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a + * Streams3-compatible interface, as well as a .next() function. + */ + cursor(options?: any): QueryCursor; + + /** Declares or executes a distict() operation. Passing a callback executes the query. */ + distinct(callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, criteria: any | Query, + callback?: (err: any, res: any[]) => void): Query; + + /** Specifies an $elemMatch condition */ + elemMatch(criteria: (elem: Query) => void): this; + elemMatch(criteria: any): this; + elemMatch(path: string | any | Function, criteria: (elem: Query) => void): this; + elemMatch(path: string | any | Function, criteria: any): this; + + /** Specifies the complementary comparison value for paths specified with where() */ + equals(val: any): this; + + /** Executes the query */ + exec(callback?: (err: any, res: T) => void): Promise; + exec(operation: string | Function, callback?: (err: any, res: T) => void): Promise; + + /** Specifies an $exists condition */ + exists(val?: boolean): this; + exists(path: string, val?: boolean): this; + + /** + * Finds documents. When no callback is passed, the query is not executed. When the + * query is executed, the result will be an array of documents. + * @param criteria mongodb selector + */ + find(callback?: (err: any, res: DocType[]) => void): DocumentQuery; + find(criteria: any, + callback?: (err: any, res: DocType[]) => void): DocumentQuery; + + /** + * Declares the query a findOne operation. When executed, the first found document is + * passed to the callback. Passing a callback executes the query. The result of the query + * is a single document. + * @param criteria mongodb selector + * @param projection optional fields to return + */ + findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery; + findOne(criteria: any, + callback?: (err: any, res: DocType | null) => void): DocumentQuery; + + /** + * Issues a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the + * callback. Executes immediately if callback is passed. + */ + findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + findOneAndRemove(conditions: any, + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + findOneAndRemove(conditions: any, options: QueryFindOneAndRemoveOptions, + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, and returns + * the found document (if any) to the callback. The query executes immediately if callback is passed. + */ + findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery; + findOneAndUpdate(update: any, + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + findOneAndUpdate(query: any | Query, update: any, + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + findOneAndUpdate(query: any | Query, update: any, options: QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + + /** + * Specifies a $geometry condition. geometry() must come after either intersects() or within(). + * @param object Must contain a type property which is a String and a coordinates property which + * is an Array. See the examples. + */ + geometry(object: { type: string, coordinates: any[] }): this; + + /** + * Returns the current query conditions as a JSON object. + * @returns current query conditions + */ + getQuery(): any; + + /** + * Returns the current update operations as a JSON object. + * @returns current update operations + */ + getUpdate(): any; + + /** + * Specifies a $gt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gt(val: number): this; + gt(path: string, val: number): this; + + /** + * Specifies a $gte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gte(val: number): this; + gte(path: string, val: number): this; + + /** + * Sets query hints. + * @param val a hint object + */ + hint(val: any): this; + + /** + * Specifies an $in query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + in(val: any[]): this; + in(path: string, val: any[]): this; + + /** Declares an intersects query for geometry(). MUST be used after where(). */ + intersects(arg?: any): this; + + /** + * Sets the lean option. + * Documents returned from queries with the lean option enabled are plain + * javascript objects, not MongooseDocuments. They have no save method, + * getters/setters or other Mongoose magic applied. + * @param bool defaults to true + */ + lean(bool?: boolean): Query; + + /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ + limit(val: number): this; + + /** + * Specifies a $lt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lt(val: number): this; + lt(path: string, val: number): this; + + /** + * Specifies a $lte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lte(val: number): this; + lte(path: string, val: number): this; + + /** + * Specifies a $maxDistance query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + maxDistance(val: number): this; + maxDistance(path: string, val: number): this; + + /** @deprecated Alias of maxScan */ + maxscan(val: number): this; + /** Specifies the maxScan option. Cannot be used with distinct() */ + maxScan(val: number): this; + + /** + * Merges another Query or conditions object into this one. + * When a Query is passed, conditions, field selection and options are merged. + */ + merge(source: any | Query): this; + + /** Specifies a $mod condition */ + mod(val: number[]): this; + mod(path: string, val: number[]): this; + + /** + * Specifies a $ne query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + ne(val: any): this; + ne(path: string, val: any): this; + + /** Specifies a $near or $nearSphere condition. */ + near(val: any): this; + near(path: string, val: any): this; + + /** + * DEPRECATED Specifies a $nearSphere condition + * @deprecated Use query.near() instead with the spherical option set to true. + */ + nearSphere(val: any): this; + nearSphere(path: string, val: any): this; + + /** + * Specifies a $nin query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + nin(val: any[]): this; + nin(path: string, val: any[]): this; + + /** + * Specifies arguments for a $nor condition. + * @param array array of conditions + */ + nor(array: any[]): this; + + /** + * Specifies arguments for an $or condition. + * @param array array of conditions + */ + or(array: any[]): this; + + /** Specifies a $polygon condition */ + polygon(...coordinatePairs: number[][]): this; + polygon(path: string, ...coordinatePairs: number[][]): this; + + /** + * Specifies paths which should be populated with other documents. + * Paths are populated after the query executes and a response is received. A separate + * query is then executed for each path specified for population. After a response for + * each query has also been returned, the results are passed to the callback. + * @param path either the path to populate or an object specifying all parameters + * @param select Field selection for the population query + * @param model The model you wish to use for population. If not specified, populate + * will look up the model by the name in the Schema's ref field. + * @param match Conditions for the population query + * @param options Options for the population query (sort, etc) + */ + populate(path: string | any, select?: string | any, model?: any, + match?: any, options?: any): this; + populate(options: ModelPopulateOptions | ModelPopulateOptions[]): this; + + /** + * Determines the MongoDB nodes from which to read. + * @param pref one of the listed preference options or aliases + * @tags optional tags for this query + */ + read(pref: string, tags?: any[]): this; + + /** + * Specifies a $regex query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + regex(val: RegExp): this; + regex(path: string, val: RegExp): this; + + /** + * Declare and/or execute this query as a remove() operation. + * The operation is only executed when a callback is passed. To force execution without a callback, + * you must first call remove() and then execute it by using the exec() method. + * @param criteria mongodb selector + */ + remove(callback?: (err: any) => void): Query; + remove(criteria: any | Query, callback?: (err: any) => void): Query; + + /** Specifies which document fields to include or exclude (also known as the query "projection") */ + select(arg: string | any): this; + /** Determines if field selection has been made. */ + selected(): boolean; + /** Determines if exclusive field selection has been made.*/ + selectedExclusively(): boolean; + /** Determines if inclusive field selection has been made. */ + selectedInclusively(): boolean; + /** Sets query options. */ + setOptions(options: any): this; + + /** + * Specifies a $size query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + size(val: number): this; + size(path: string, val: number): this; + + /** Specifies the number of documents to skip. Cannot be used with distinct() */ + skip(val: number): this; + + /** + * DEPRECATED Sets the slaveOk option. + * @param v defaults to true + * @deprecated in MongoDB 2.2 in favor of read preferences. + */ + slaveOk(v?: boolean): this; + + /** + * Specifies a $slice projection for an array. + * @param val number/range of elements to slice + */ + slice(val: number | number[]): this; + slice(path: string, val: number | number[]): this; + + /** Specifies this query as a snapshot query. Cannot be used with distinct() */ + snapshot(v?: boolean): this; + + /** + * Sets the sort order + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with - + * which will be treated as descending. + */ + sort(arg: string | any): this; + + /** Returns a Node.js 0.8 style read stream interface. */ + stream(options?: { transform?: Function; }): QueryStream; + + /** + * Sets the tailable option (for use with capped collections). Cannot be used with distinct() + * @param bool defaults to true + * @param opts options to set + * @param opts.numberOfRetries if cursor is exhausted, retry this many times before giving up + * @param opts.tailableRetryInterval if cursor is exhausted, wait this many milliseconds before retrying + */ + tailable(bool?: boolean, opts?: { + numberOfRetries?: number; + tailableRetryInterval?: number; + }): this; + + /** Executes this query and returns a promise */ + then(resolve?: (res: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): Promise; + + /** + * Converts this query to a customized, reusable query + * constructor with all arguments and options retained. + */ + toConstructor(): new(...args: any[]) => Query; + toConstructor(): new(...args: any[]) => DocumentQuery; + + /** + * Declare and/or execute this query as an update() operation. + * All paths passed that are not $atomic operations will become $set ops. + * @param doc the update command + */ + update(callback?: (err: any, affectedRows: number) => void): Query; + update(doc: any, callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: any, doc: any, + callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: any, doc: any, options: QueryUpdateOptions, + callback?: (err: any, affectedRows: number) => void): Query; + + /** Specifies a path for use with chaining. */ + where(path?: string | any, val?: any): this; + + /** Defines a $within or $geoWithin argument for geo-spatial queries. */ + within(val?: any): this; + within(coordinate: number[], ...coordinatePairs: number[][]): this; + + /** Flag to opt out of using $geoWithin. */ + static use$geoWithin: boolean; + } + + // https://github.com/aheckmann/mquery + // mquery currently does not have a type definition please + // replace it if one is ever created + class mquery {} + + interface QueryFindOneAndRemoveOptions { + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: any; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { + /** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: any | string; + /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document + * is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** + * if set to 'query' and runValidators is on, this will refer to the query in custom validator + * functions that update validation runs. Does nothing if runValidators is false. + */ + context?: string; + } + + interface QueryUpdateOptions extends ModelUpdateOptions { + /** + * if set to 'query' and runValidators is on, this will refer to the query + * in customvalidator functions that update validation runs. Does nothing + * if runValidators is false. + */ + context?: string; + } + + interface CollationOptions { + locale?: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + } + + namespace Schema { + namespace Types { + /* + * section schema/array.js + * http://mongoosejs.com/docs/api.html#schema-array-js + */ + class Array extends SchemaType { + /** Array SchemaType constructor */ + constructor(key: string, cast?: SchemaType, options?: any); + + /** + * Check if the given value satisfies a required validator. The given value + * must be not null nor undefined, and have a non-zero length. + */ + checkRequired(value: T): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/string.js + * http://mongoosejs.com/docs/api.html#schema-string-js + */ + class String extends SchemaType { + /** String SchemaType constructor. */ + constructor(key: string, options?: any); + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** + * Adds an enum validator + * @param args enumeration values + */ + enum(args: string | string[] | any): this; + + /** Adds a lowercase setter. */ + lowercase(): this; + + /** + * Sets a regexp validator. Any value that does not pass regExp.test(val) will fail validation. + * @param regExp regular expression to test against + * @param message optional custom error message + */ + match(regExp: RegExp, message?: string): this; + + /** + * Sets a maximum length validator. + * @param value maximum string length + * @param message optional custom error message + */ + maxlength(value: number, message?: string): this; + + /** + * Sets a minimum length validator. + * @param value minimum string length + * @param message optional custom error message + */ + minlength(value: number, message?: string): this; + + /** Adds a trim setter. The string value will be trimmed when set. */ + trim(): this; + /** Adds an uppercase setter. */ + uppercase(): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/documentarray.js + * http://mongoosejs.com/docs/api.html#schema-documentarray-js + */ + class DocumentArray extends Array { + /** SubdocsArray SchemaType constructor */ + constructor(key: string, schema: Schema, options?: any); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/number.js + * http://mongoosejs.com/docs/api.html#schema-number-js + */ + class Number extends SchemaType { + /** Number SchemaType constructor. */ + constructor(key: string, options?: any); + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** + * Sets a maximum number validator. + * @param maximum number + * @param message optional custom error message + */ + max(maximum: number, message?: string): this; + + /** + * Sets a minimum number validator. + * @param value minimum number + * @param message optional custom error message + */ + min(value: number, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/date.js + * http://mongoosejs.com/docs/api.html#schema-date-js + */ + class Date extends SchemaType { + /** Date SchemaType constructor. */ + constructor(key: string, options?: any); + + /** + * Check if the given value satisfies a required validator. To satisfy + * a required validator, the given value must be an instance of Date. + */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** Declares a TTL index (rounded to the nearest second) for Date types only. */ + expires(when: number | string): this; + + /** + * Sets a maximum date validator. + * @param maximum date + * @param message optional custom error message + */ + max(maximum: NativeDate, message?: string): this; + + /** + * Sets a minimum date validator. + * @param value minimum date + * @param message optional custom error message + */ + min(value: NativeDate, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/buffer.js + * http://mongoosejs.com/docs/api.html#schema-buffer-js + */ + class Buffer extends SchemaType { + /** Buffer SchemaType constructor */ + constructor(key: string, options?: any); + + /** + * Check if the given value satisfies a required validator. To satisfy a + * required validator, a buffer must not be null or undefined and have + * non-zero length. + */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/boolean.js + * http://mongoosejs.com/docs/api.html#schema-boolean-js + */ + class Boolean extends SchemaType { + /** Boolean SchemaType constructor. */ + constructor(path: string, options?: any); + + /** + * Check if the given value satisfies a required validator. For a + * boolean to satisfy a required validator, it must be strictly + * equal to true or to false. + */ + checkRequired(value: any): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/objectid.js + * http://mongoosejs.com/docs/api.html#schema-objectid-js + */ + class ObjectId extends SchemaType { + /** ObjectId SchemaType constructor. */ + constructor(key: string, options?: any); + + /** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param turnOn auto generated ObjectId defaults + */ + auto(turnOn: boolean): this; + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + /* + * section schema/decimal128.js + * http://mongoosejs.com/docs/api.html#schema-decimal128-js + */ + class Decimal128 extends SchemaType { + /** Decimal128 SchemaType constructor. */ + constructor(key: string, options?: any); + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/mixed.js + * http://mongoosejs.com/docs/api.html#schema-mixed-js + */ + class Mixed extends SchemaType { + /** Mixed SchemaType constructor. */ + constructor(path: string, options?: any); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/embedded.js + * http://mongoosejs.com/docs/api.html#schema-embedded-js + */ + class Embedded extends SchemaType { + /** Sub-schema schematype constructor */ + constructor(schema: Schema, key: string, options?: any); + } + } + } + + /* + * section aggregate.js + * http://mongoosejs.com/docs/api.html#aggregate-js + */ + class Aggregate { + /** + * Aggregate constructor used for building aggregation pipelines. + * Returned when calling Model.aggregate(). + * @param ops aggregation operator(s) or operator array + */ + constructor(ops?: any | any[], ...args: any[]); + + /** Adds a cursor flag */ + addCursorFlag(flag: string, value: boolean): this; + + /** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * @param value Should tell server it can use hard drive to store data during aggregation. + * @param tags optional tags for this query + */ + allowDiskUse(value: boolean, tags?: any[]): this; + + /** + * Appends new operators to this aggregate pipeline + * @param ops operator(s) to append + */ + append(...ops: any[]): this; + + /** Adds a collation. */ + collation(options: CollationOptions): this; + + /** + * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). + * Note the different syntax below: .exec() returns a cursor object, and no callback + * is necessary. + * @param options set the cursor batch size + */ + cursor(options: any): this; + + // If cursor option is on, could return an object + /** Executes the aggregate pipeline on the currently bound Model. */ + exec(callback?: (err: any, result: T) => void): Promise | any; + + /** Execute the aggregation with explain */ + explain(callback?: (err: any, result: T) => void): Promise; + + /** + * Appends a new custom $group operator to this aggregate pipeline. + * @param arg $group operator contents + */ + group(arg: any): this; + + /** + * Appends a new $limit operator to this aggregate pipeline. + * @param num maximum number of records to pass to the next stage + */ + limit(num: number): this; + + /** + * Appends new custom $lookup operator(s) to this aggregate pipeline. + * @param options to $lookup as described in the above link + */ + lookup(options: any): this; + + /** + * Appends a new custom $match operator to this aggregate pipeline. + * @param arg $match operator contents + */ + match(arg: any): this; + + /** + * Binds this aggregate to a model. + * @param model the model to which the aggregate is to be bound + */ + model(model: any): this; + + /** + * Appends a new $geoNear operator to this aggregate pipeline. + * MUST be used as the first operator in the pipeline. + */ + near(parameters: any): this; + + /** + * Appends a new $project operator to this aggregate pipeline. + * Mongoose query selection syntax is also supported. + * @param arg field specification + */ + project(arg: string | any): this; + + /** + * Sets the readPreference option for the aggregation query. + * @param pref one of the listed preference options or their aliases + * @param tags optional tags for this query + */ + read(pref: string, tags?: any[]): this; + + /** + * Appends new custom $sample operator(s) to this aggregate pipeline. + * @param size number of random documents to pick + */ + sample(size: number): this; + + /** + * Appends a new $skip operator to this aggregate pipeline. + * @param num number of records to skip before next stage + */ + skip(num: number): this; + + /** + * Appends a new $sort operator to this aggregate pipeline. + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The sort order + * of each path is ascending unless the path name is prefixed with - which will be treated + * as descending. + */ + sort(arg: string | any): this; + + /** Provides promise for aggregate. */ + then(resolve?: (val: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): Promise; + + /** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * Note that the $unwind operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * @param fields the field(s) to unwind + */ + unwind(...fields: string[]): this; + /** + * Appends new custom $unwind operator(s) to this aggregate pipeline + * new in mongodb 3.2 + */ + unwind(...opts: { path: string, includeArrayIndex?: string, preserveNullAndEmptyArrays?: boolean }[]): this; + } + + /* + * section schematype.js + * http://mongoosejs.com/docs/api.html#schematype-js + */ + class SchemaType { + /** SchemaType constructor */ + constructor(path: string, options?: any, instance?: string); + + /** + * Sets a default value for this SchemaType. + * Defaults can be either functions which return the value to use as the + * default or the literal value itself. Either way, the value will be cast + * based on its schema type before being set during document creation. + * @param val the default value + */ + default(val: any): any; + + /** Adds a getter to this schematype. */ + get(fn: Function): this; + + /** + * Declares the index options for this schematype. + * Indexes are created in the background by default. Specify background: false to override. + */ + index(options: any | boolean | string): this; + + /** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using unshift(). + * @param required enable/disable the validator + * @param message optional custom error message + */ + required(required: boolean, message?: string): this; + + /** Sets default select() behavior for this path. */ + select(val: boolean): this; + /** Adds a setter to this schematype. */ + set(fn: Function): this; + /** Declares a sparse index. */ + sparse(bool: boolean): this; + /** Declares a full text index. */ + text(bool: boolean): this; + /** Declares an unique index. */ + unique(bool: boolean): this; + + /** + * Adds validator(s) for this document path. + * Validators always receive the value to validate as their first argument + * and must return Boolean. Returning false means validation failed. + * @param obj validator + * @param errorMsg optional error message + * @param type optional validator type + */ + validate(obj: RegExp | Function | any, errorMsg?: string, + type?: string): this; + } + + /* + * section promise.js + * http://mongoosejs.com/docs/api.html#promise-js + */ + /** + * To assign your own promise library: + * + * 1. Typescript does not allow assigning properties of imported modules. + * To avoid compile errors use one of the options below in your code: + * + * - (mongoose).Promise = YOUR_PROMISE; + * - require('mongoose').Promise = YOUR_PROMISE; + * - import mongoose = require('mongoose'); + * mongoose.Promise = YOUR_PROMISE; + * + * 2. To assign type definitions for your promise library, you will need + * to have a .d.ts file with the following code when you compile: + * + * - import * as Q from 'q'; + * declare module 'mongoose' { + * type Promise = Q.promise; + * } + * + * - import * as Bluebird from 'bluebird'; + * declare module 'mongoose' { + * type Promise = Bluebird; + * } + * + * Uses global.Promise by default. If you would like to use mongoose default + * mpromise implementation (which is deprecated), you can omit step 1 and + * run npm install @types/mongoose-promise + */ + export var Promise: any; + export var PromiseProvider: any; + + /* + * section model.js + * http://mongoosejs.com/docs/api.html#model-js + */ + export var Model: Model; + interface Model extends NodeJS.EventEmitter, ModelProperties { + /** + * Model constructor + * Provides the interface to MongoDB collections as well as creates document instances. + * @param doc values with which to create the document + * @event error If listening to this event, it is emitted when a document + * was saved without passing a callback and an error occurred. If not + * listening, the event bubbles to the connection used to create this Model. + * @event index Emitted after Model#ensureIndexes completes. If an error + * occurred it is passed with the event. + * @event index-single-start Emitted when an individual index starts within + * Model#ensureIndexes. The fields and options being used to build the index + * are also passed with the event. + * @event index-single-done Emitted when an individual index finishes within + * Model#ensureIndexes. If an error occurred it is passed with the event. + * The fields, options, and index name are also passed. + */ + new(doc?: any): T; + + /** + * Finds a single document by its _id field. findById(id) is almost* + * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. + * @param id value of _id to query by + * @param projection optional fields to return + */ + findById(id: any | string | number, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findById(id: any | string | number, projection: any, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findById(id: any | string | number, projection: any, options: any, + callback?: (err: any, res: T | null) => void): DocumentQuery; + + model(name: string): Model; + + /** + * Creates a Query and specifies a $where condition. + * @param argument is a javascript string or anonymous function + */ + $where(argument: string | Function): DocumentQuery; + + /** + * Performs aggregations on the models collection. + * If a callback is passed, the aggregate is executed and a Promise is returned. + * If a callback is not passed, the aggregate itself is returned. + * @param ... aggregation pipeline operator(s) or operator array + */ + aggregate(...aggregations: any[]): Aggregate; + aggregate(...aggregationsWithCallback: any[]): Promise; + + /** Counts number of matching documents in a database collection. */ + count(conditions: any, callback?: (err: any, count: number) => void): Query; + + /** + * Shortcut for saving one or more documents to the database. MyModel.create(docs) + * does new MyModel(doc).save() for every doc in docs. + * Triggers the save() hook. + */ + create(docs: any[], callback?: (err: any, res: T[]) => void): Promise; + create(...docs: any[]): Promise; + create(...docsWithCallback: any[]): Promise; + + /** + * Adds a discriminator type. + * @param name discriminator model name + * @param schema discriminator model schema + */ + discriminator(name: string, schema: Schema): Model; + + /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, conditions: any, + callback?: (err: any, res: any[]) => void): Query; + + /** + * Sends ensureIndex commands to mongo for each index declared in the schema. + * @param options internal options + * @param cb optional callback + */ + ensureIndexes(callback?: (err: any) => void): Promise; + ensureIndexes(options: any, callback?: (err: any) => void): Promise; + + /** + * Finds documents. + * @param projection optional fields to return + */ + find(callback?: (err: any, res: T[]) => void): DocumentQuery; + find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery; + find(conditions: any, projection?: any | null, + callback?: (err: any, res: T[]) => void): DocumentQuery; + find(conditions: any, projection?: any | null, options?: any | null, + callback?: (err: any, res: T[]) => void): DocumentQuery; + + + + /** + * Issue a mongodb findAndModify remove command by a document's _id field. + * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed, else a Query object is returned. + * @param id value of _id to query by + */ + findByIdAndRemove(): DocumentQuery; + findByIdAndRemove(id: any | number | string, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findByIdAndRemove(id: any | number | string, options: { + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: any; + /** sets the document fields to return */ + select?: any; + }, callback?: (err: any, res: T | null) => void): DocumentQuery; + + /** + * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) + * is equivalent to findOneAndUpdate({ _id: id }, ...). + * @param id value of _id to query by + */ + findByIdAndUpdate(): DocumentQuery; + findByIdAndUpdate(id: any | number | string, update: any, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findByIdAndUpdate(id: any | number | string, update: any, + options: ModelFindByIdAndUpdateOptions, + callback?: (err: any, res: T | null) => void): DocumentQuery; + + /** + * Finds one document. + * The conditions are cast to their respective SchemaTypes before the command is sent. + * @param projection optional fields to return + */ + findOne(conditions?: any, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findOne(conditions: any, projection: any, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findOne(conditions: any, projection: any, options: any, + callback?: (err: any, res: T | null) => void): DocumentQuery; + + /** + * Issue a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed else a Query object is returned. + */ + findOneAndRemove(): DocumentQuery; + findOneAndRemove(conditions: any, + callback?: (err: any, res: T | null) => void): DocumentQuery; + findOneAndRemove(conditions: any, options: { + /** + * if multiple docs are found by the conditions, sets the sort order to choose + * which doc to update + */ + sort?: any; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** sets the document fields to return */ + select?: any; + }, callback?: (err: any, res: T | null) => void): DocumentQuery; + + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, + * and returns the found document (if any) to the callback. The query executes immediately + * if callback is passed else a Query object is returned. + */ + findOneAndUpdate(): DocumentQuery; + findOneAndUpdate(conditions: any, update: any, + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + findOneAndUpdate(conditions: any, update: any, + options: ModelFindOneAndUpdateOptions, + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + + /** + * geoNear support for Mongoose + * @param GeoJSON point or legacy coordinate pair [x,y] to search near + * @param options for the qurery + * @param callback optional callback for the query + */ + geoNear(point: number[] | { + type: string; + coordinates: number[] + }, options: { + /** return the raw object */ + lean?: boolean; + [other: string]: any; + }, callback?: (err: any, res: T[], stats: any) => void): DocumentQuery; + + /** + * Implements $geoSearch functionality for Mongoose + * @param conditions an object that specifies the match condition (required) + * @param options for the geoSearch, some (near, maxDistance) are required + * @param callback optional callback + */ + geoSearch(conditions: any, options: { + /** x,y point to search for */ + near: number[]; + /** the maximum distance from the point near that a result can be */ + maxDistance: number; + /** The maximum number of results to return */ + limit?: number; + /** return the raw object instead of the Mongoose Model */ + lean?: boolean; + }, callback?: (err: any, res: T[]) => void): DocumentQuery; + + /** + * Shortcut for creating a new Document from existing raw data, + * pre-saved in the DB. The document returned has no paths marked + * as modified initially. + */ + hydrate(obj: any): T; + + /** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than .create() + * because it only sends one operation to the server, rather than one for each + * document. + * This function does not trigger save middleware. + */ + insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): Promise; + insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise; + insertMany(...docsWithCallback: any[]): Promise; + + /** + * Executes a mapReduce command. + * @param o an object specifying map-reduce options + * @param callbackoptional callback + */ + mapReduce( + o: ModelMapReduceOption, + callback?: (err: any, res: any) => void + ): Promise; + + /** + * Populates document references. + * @param docs Either a single document or array of documents to populate. + * @param options A hash of key/val (path, options) used for population. + * @param callback Optional callback, executed upon completion. Receives err and the doc(s). + */ + populate(docs: any[], options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: T[]) => void): Promise; + populate(docs: any, options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: T) => void): Promise; + + /** Removes documents from the collection. */ + remove(conditions: any, callback?: (err: any) => void): Query; + deleteOne(conditions: any, callback?: (err: any) => void): Query; + deleteMany(conditions: any, callback?: (err: any) => void): Query; + + /** + * Updates documents in the database without returning them. + * All update values are cast to their appropriate SchemaTypes before being sent. + */ + update(conditions: any, doc: any, + callback?: (err: any, raw: any) => void): Query; + update(conditions: any, doc: any, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + updateOne(conditions: any, doc: any, + callback?: (err: any, raw: any) => void): Query; + updateOne(conditions: any, doc: any, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + updateMany(conditions: any, doc: any, + callback?: (err: any, raw: any) => void): Query; + updateMany(conditions: any, doc: any, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** Creates a Query, applies the passed conditions, and returns the Query. */ + where(path: string, val?: any): Query; + } + + interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties { + /** Signal that we desire an increment of this documents version. */ + increment(): this; + + /** + * Returns another Model instance. + * @param name model name + */ + model(name: string): Model; + + /** + * Removes this document from the db. + * @param fn optional callback + */ + remove(fn?: (err: any, product: this) => void): Promise; + + /** + * Saves this document. + * @param options options optional options + * @param options.safe overrides schema's safe option + * @param options.validateBeforeSave set to false to save without validating. + * @param fn optional callback + */ + save(options?: SaveOptions, fn?: (err: any, product: this, numAffected: number) => void): Promise; + save(fn?: (err: any, product: this, numAffected: number) => void): Promise; + + /** + * Version using default version key. See http://mongoosejs.com/docs/guide.html#versionKey + * If you're using another key, you will have to access it using []: doc[_myVersionKey] + */ + __v?: number; + } + + interface SaveOptions { + safe?: boolean | WriteConcern; + validateBeforeSave?: boolean; + } + + interface WriteConcern { + j?: boolean; + w?: number | 'majority' | TagSet; + wtimeout?: number; + } + + interface TagSet { + [k: string]: string; + } + + interface ModelProperties { + /** Base Mongoose instance the model uses. */ + base: typeof mongoose; + + /** + * If this is a discriminator model, baseModelName is the + * name of the base model. + */ + baseModelName: String; + + /** Collection the model uses. */ + collection: Collection; + + /** Connection the model uses. */ + db: Connection; + + /** Registered discriminators for this model. */ + discriminators: any; + + /** The name of the model */ + modelName: string; + + /** Schema the model uses. */ + schema: Schema; + } + + interface ModelFindByIdAndUpdateOptions { + /** true to return the modified document rather than the original. defaults to false */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** + * if true, runs update validators on this command. Update validators validate the + * update operation against the model's schema. + */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's + * schema if a new document is created. This option only works on MongoDB >= 2.4 because + * it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: any; + /** sets the document fields to return */ + select?: any; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + /** overwrites the schema's strict mode option for this update */ + strict?: boolean; + /** + * if true, run all setters defined on the associated model's schema for all fields + * defined in the query and the update. + */ + runSettersOnQuery?: boolean; + } + + interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: any | string; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface ModelPopulateOptions { + /** space delimited path(s) to populate */ + path: string; + /** optional fields to select */ + select?: any; + /** optional query conditions to match */ + match?: any; + /** optional name of the model to use for population */ + model?: string; + /** optional query options like sort, limit, etc */ + options?: any; + /** deep populate */ + populate?: ModelPopulateOptions | ModelPopulateOptions[]; + } + + interface ModelUpdateOptions { + /** safe mode (defaults to value set in schema (true)) */ + safe?: boolean; + /** whether to create the doc if it doesn't match (false) */ + upsert?: boolean; + /** whether multiple documents should be updated (false) */ + multi?: boolean; + /** + * If true, runs update validators on this command. Update validators validate + * the update operation against the model's schema. + */ + runValidators?: boolean; + /** + * If this and upsert are true, mongoose will apply the defaults specified in the + * model's schema if a new document is created. This option only works on MongoDB >= 2.4 + * because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** overrides the strict option for this update */ + strict?: boolean; + /** disables update-only mode, allowing you to overwrite the doc (false) */ + overwrite?: boolean; + /** other options */ + [other: string]: any; + } + + interface ModelMapReduceOption { + map: Function | string; + reduce: (key: Key, vals: T[]) => Val; + /** query filter object. */ + query?: any; + /** sort input objects using this key */ + sort?: any; + /** max number of documents */ + limit?: number; + /** keep temporary data default: false */ + keeptemp?: boolean; + /** finalize function */ + finalize?: (key: Key, val: Val) => Val; + /** scope variables exposed to map/reduce/finalize during execution */ + scope?: any; + /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ + jsMode?: boolean; + /** provide statistics on job execution time. default: false */ + verbose?: boolean; + readPreference?: string; + /** sets the output target for the map reduce job. default: {inline: 1} */ + out?: { + /** the results are returned in an array */ + inline?: number; + /** + * {replace: 'collectionName'} add the results to collectionName: the + * results replace the collection + */ + replace?: string; + /** + * {reduce: 'collectionName'} add the results to collectionName: if + * dups are detected, uses the reducer / finalize functions + */ + reduce?: string; + /** + * {merge: 'collectionName'} add the results to collectionName: if + * dups exist the new docs overwrite the old + */ + merge?: string; + }; + } + + interface MapReduceResult { + _id: Key; + value: Val; + } + + /* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + */ + interface CollectionBase extends mongodb.Collection { + /* + * Abstract methods. Some of these are already defined on the + * mongodb.Collection interface so they've been commented out. + */ + ensureIndex(...args: any[]): any; + //find(...args: any[]): any; + findAndModify(...args: any[]): any; + //findOne(...args: any[]): any; + getIndexes(...args: any[]): any; + //insert(...args: any[]): any; + //mapReduce(...args: any[]): any; + //save(...args: any[]): any; + //update(...args: any[]): any; + + /** The collection name */ + collectionName: string; + /** The Connection instance */ + conn: Connection; + /** The collection name */ + name: string; + } +} diff --git a/types/mongoose/v4/mongoose-tests.ts b/types/mongoose/v4/mongoose-tests.ts new file mode 100644 index 0000000000..92adb61d83 --- /dev/null +++ b/types/mongoose/v4/mongoose-tests.ts @@ -0,0 +1,1651 @@ +import * as mongoose from 'mongoose'; + +// test compatibility with other libraries +import * as _ from 'lodash'; +var fs = require('fs'); + +// dummy variables +var cb = function () {}; + +/* + * Most of these tests are taken directly from the examples + * in the Mongoose API documentation. + * + * http://mongoosejs.com/docs/guide.html + * http://mongoosejs.com/docs/api.html + */ + +/* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + */ +var connectUri = 'mongodb://user:pass@localhost:port/database'; +mongoose.connect(connectUri).then(cb).catch(cb); +mongoose.connect(connectUri, { + user: 'larry', + pass: 'housan', + config: { + autoIndex: true + }, + mongos: true +}).then(cb); +mongoose.connect(connectUri, function (error) { + error.stack; +}); +var mongooseConnection: mongoose.Connection = mongoose.createConnection(); +mongoose.createConnection(connectUri).open(''); +mongoose.createConnection(connectUri, { + db: { + native_parser: true + } +}).open(''); +mongoose.createConnection('localhost', 'database', 3000).open(''); +mongoose.createConnection('localhost', 'database', 3000, { + user: 'larry', + config: { + autoIndex: false + } +}).open(''); +mongoose.disconnect(cb).then(cb); +mongoose.get('test'); +mongoose.model('Actor', new mongoose.Schema({ + name: String +}), 'collectionName', true).find({}); +mongoose.model('Actor').find({}); +mongoose.modelNames()[0].toLowerCase(); +new (new mongoose.Mongoose(9, 8, 7)).Mongoose(1, 2, 3).connect(''); +mongoose.plugin(cb, {}).connect(''); +mongoose.set('test', 'value'); +mongoose.set('debug', function(collectionName: any, methodName: any, arg1: any, arg2: any) {}); +mongoose.STATES.hasOwnProperty(''); +mongoose.connection.on('error', cb); +new mongoose.mongo.MongoError('error').stack; +mongoose.SchemaTypes.String; +mongoose.SchemaTypes.ObjectId; +mongoose.SchemaTypes.Decimal128; +mongoose.Types.ObjectId; +mongoose.Types.Decimal128; +mongoose.version.toLowerCase(); + +/* + * section querystream.js + * http://mongoosejs.com/docs/api.html#querystream-js + */ +var querystream = {}; +querystream.destroy(new Error()); +querystream.pause(); +querystream.pipe(process.stdout, {end: true}).end(); +querystream.resume(); +querystream.paused; +querystream.readable; +/* inherited properties */ +querystream.getMaxListeners(); +/* practical examples */ +var QSModel = {}; +var QSStream: mongoose.QueryStream = QSModel.find().stream(); +QSStream.on('data', function (doc: any) { + doc.save(); +}).on('error', function (err: any) { + throw err; +}).on('close', cb); +QSModel.where('created').gte(20000).stream().pipe(process.stdout); + +/* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + * + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ +var coll1 = {}; +coll1.$format(999).toLowerCase(); +coll1.$print('name', 'i', [1, 2, 3]); +coll1.getIndexes(); +/* inherited properties */ +coll1.collectionName; +coll1.conn; +coll1.name; +coll1.ensureIndex(); +coll1.find({}); +coll1.insert({}, {}); + +var coll2 = new mongoose.Collection('', new mongoose.Connection(mongoose)); +coll2.$format(999).toLowerCase(); +/* inherited properties */ +coll2.initializeOrderedBulkOp; +coll2.indexExists; + +/* + * section connection.js + * http://mongoosejs.com/docs/api.html#connection-js + * + * section section drivers/node-mongodb-native/connection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ +var conn1: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); +conn1 = new mongoose.Connection(mongoose); +conn1.open('mongodb://localhost/test', 'myDb', 27017, { + replset: null, + config: { + autoIndex: false + } +}, function (err) {}).open(''); +conn1.openSet('mongodb://localhost/test', 'db', { + replset: null, + mongos: true +}, function (err) {}).then(cb).catch(cb); +conn1.close().catch(function (err) {}); +conn1.collection('name').$format(999); +conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +interface IStatics { + staticMethod1: (a: number) => string; +} +conn1.modelNames()[0].toLowerCase(); +conn1.config.hasOwnProperty(''); +conn1.db.bufferMaxEntries; +conn1.collections['coll'].$format(999); +conn1.readyState.toFixed(); +conn1.useDb('myDb').useDb(''); +mongoose.Connection.STATES.hasOwnProperty(''); +/* inherited properties */ +conn1.on('data', cb); +conn1.addListener('close', cb); + +/* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ +var validationError = {}; +validationError.toString().toLowerCase(); +/* inherited properties */ +validationError.stack; +validationError.message; + +/* + * section error.js + * http://mongoosejs.com/docs/api.html#error-js + */ +var mongooseError: mongoose.Error = new mongoose.Error('error'); +/* inherited properties */ +mongooseError.message; +mongooseError.name; +mongooseError.stack; +/* static properties */ +mongoose.Error.messages.hasOwnProperty(''); +mongoose.Error.Messages.hasOwnProperty(''); + +/* + * section querycursor.js + * http://mongoosejs.com/docs/api.html#querycursor-js + */ +var querycursor = > {}; +querycursor.close(function (error, result) { + result.execPopulate(); +}).catch(cb); +querycursor.eachAsync(function (doc) { + doc.execPopulate(); +}, function (err) {}).catch(cb); +querycursor.next(cb).catch(cb); +/* inherited properties */ +querycursor.pause(); +querycursor.pipe(process.stdout); +/* practical example */ +var QCModel = mongoose.model('QC', new mongoose.Schema({name: String})); +QCModel.find({}).cursor({}).on('data', function (doc: any) { + doc.depopulate('name'); +}).on('error', function (error: any) { + throw error; +}).close().then(cb).catch(cb); +querycursor.map(function (doc) { + doc.foo = "bar"; + return doc; +}).on('data', function (doc: any) { + console.log(doc.foo); +}); +querycursor.map(function (doc) { + doc.foo = "bar"; + return doc; +}).next(function (error, doc) { + console.log(doc.foo); +}); + +/* + * section virtualtype.js + * http://mongoosejs.com/docs/api.html#virtualtype-js + */ +var virtualtype: mongoose.VirtualType = new mongoose.VirtualType({}, 'hello'); +virtualtype.applyGetters({}, {}); +virtualtype.applySetters({}, {}); +virtualtype.get(cb).get(cb); +virtualtype.set(cb).set(cb); + +/* + * section schema.js + * http://mongoosejs.com/docs/api.html#schema-js + */ +var schema: mongoose.Schema = new mongoose.Schema({ + name: String, + binary: Buffer, + living: Boolean, + updated: { type: Date, default: Date.now }, + age: { type: Number, min: 18, max: 65 }, + mixed: mongoose.Schema.Types.Mixed, + _someId: mongoose.Schema.Types.ObjectId, + someDecimal:mongoose.Schema.Types.Decimal128, + array: [], + ofString: [String], + ofNumber: [Number], + ofDates: [Date], + ofBuffer: [Buffer], + ofBoolean: [Boolean], + ofMixed: [mongoose.Schema.Types.Mixed], + ofObjectId: [mongoose.Schema.Types.ObjectId], + nested: { + stuff: { type: String, lowercase: true, trim: true } + } +}); +schema.add({ + mixedArray: { + type: [mongoose.Schema.Types.Mixed], + required: true + } +}, 'prefix'); +schema.eachPath(function (path, type) { + path.toLowerCase(); + type.sparse(true); +}).eachPath(cb); +schema.get('path'); +schema.index({ + name: 1, + binary: -1 +}).index({}, {}); +schema.indexes().slice(); +schema.method('name', cb).method({ + m1: cb, + m2: cb +}); +schema.path('a', mongoose.Schema.Types.Buffer).path('a'); +schema.pathType('m1').toLowerCase(); +schema.plugin(function (schema, opts) { + schema.get('path'); + if (opts) { + opts.hasOwnProperty(''); + } +}).plugin(cb, {opts: true}); + +schema +.post('save', function (error, doc, next) { + error.stack; + doc.model; + next.apply; +}) +.post('save', function (doc: mongoose.Document, next: Function) { + doc.model; + next(new Error()); +}) +.post('save', function (doc: mongoose.Document) { + doc.model; +}); +schema.queue('m1', [1, 2, 3]).queue('m2', [[]]); +schema.remove('path'); +schema.remove(['path1', 'path2', 'path3']); +schema.requiredPaths(true)[0].toLowerCase(); +schema.set('key', 999).set('key'); +schema.static('static', cb).static({ + s1: cb, + s2: cb +}); +schema.virtual('virt', {}).applyGetters({}, {}); +schema.virtualpath('path').applyGetters({}, {}); +/* static properties */ +mongoose.Schema.indexTypes[0].toLowerCase(); +mongoose.Schema.reserved.hasOwnProperty(''); +/* inherited properties */ +schema.addListener('e', cb); +/* practical examples */ +var animalSchema = new mongoose.Schema({ + name: String, + type: String +}); +animalSchema.methods.findSimilarTypes = function (cb: any) { + return this.model('Aminal').find({ type: this.type }, cb); +}; +var Animal: any = mongoose.model('Animal', animalSchema); +var dog: any = new Animal({type: 'dog'}); +dog['findSimilarTypes'](function (err: any, dogs: any) { + console.log(dogs); +}); +new mongoose.Schema({ + title: String, + author: String, + body: String, + comments: [{ body: String, date: Date }], + date: { type: Date, default: Date.now }, + hidden: Boolean, + meta: { + votes: Number, + favs: Number, + text: String + }, + meta2: { + text: mongoose.Schema.Types.Number, + select: { + type: String + } + } +}); +new mongoose.Schema({ name: { type: String, index: true }}); +new mongoose.Schema({ loc: { type: [Number], index: 'hashed' }}); +new mongoose.Schema({ loc: { type: [Number], index: '2d', sparse: true }}); +new mongoose.Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}}); +new mongoose.Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}}); +new mongoose.Schema({ born: { type: Date, required: '{PATH} is required!' }}); +new mongoose.Schema({ born: { type: Date, required: function() { + return this.age >= 18; +}}}); +new mongoose.Schema({ state: { type: String, enum: ['opening', 'open', 'closing', 'closed'] }}); +new mongoose.Schema({ state: { type: String, enum: { + values: ['opening', 'open', 'closing', 'closed'], + message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' +}}}); +new mongoose.Schema({ name: { type: String, match: /^a/ }}); +new mongoose.Schema({ name: { type: String, match: [ + /\.html$/, "That file doesn't end in .html ({VALUE})" +]}}); +new mongoose.Schema({ + createdAt: {type: Date, expires: 60 * 60 * 24} +}); +new mongoose.Schema({ createdAt: { type: Date, expires: '1.5h' }}); +new mongoose.Schema({ d: { type: Date, max: new Date('2014-01-01') }}); +new mongoose.Schema({ d: { type: Date, max: [ + new Date('2014-01-01'), + 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).' +]}}); +new mongoose.Schema({d: {type: Date, min: [ + new Date('1970-01-01'), + 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).' +]}}); +new mongoose.Schema({ + integerOnly: { + type: Number, + get: (v: number) => Math.round(v), + set: (v: number) => Math.round(v) + } +}); +new mongoose.Schema({ name: { type: String, validate: [ + { validator: () => {return true}, msg: 'uh oh' }, + { validator: () => {return true}, msg: 'failed' } +]}}); +animalSchema.statics.findByName = function(name: any, cb: any) { + return this.find({ name: new RegExp(name, 'i') }, cb); +}; +Animal['findByName']('fido', function(err: any, animals: any) { + console.log(animals); +}); +animalSchema.virtual('name.full').get(function () { + return this.name.first + ' ' + this.name.last; +}); +var childSchema = new mongoose.Schema({ name: String }); +var parentSchema = new mongoose.Schema({ + children: [childSchema], + child: childSchema, + name: { + index: true, + required: true + } +}); +new mongoose.Schema({ + eggs: { + type: Number, + min: [6, 'Too few eggs'], + max: 12 + }, + bacon: { + type: Number, + required: [true, 'Why no bacon?'] + }, + drink: { + type: String, + enum: ['Coffee', 'Tea'] + } +}); + +(new mongoose.Schema({})).plugin(function (schema: any, options: any) { + schema.add({ lastMod: Date }) + schema.pre('save', function (next: Function) { + this.lastMod = new Date + next() + }) + if (options && options['index']) { + schema.path('lastMod').index(options['index']) + } +}, { index: true }).plugin(function (schema: any, options: any) { + schema.add({ lastMod: Date }) + schema.pre('save', function (next: Function) { + this.lastMod = new Date + next() + }) + if (options && options['index']) { + schema.path('lastMod').index(options['index']) + } +}); + +export default function(schema: mongoose.Schema) { + schema.pre('init', function(this: mongoose.Document, next: (err?: Error) => void, data: any): void { + data.name = 'Hello world'; + }); +} + +/* + * section document.js + * http://mongoosejs.com/docs/api.html#document-js + */ +var doc = {}; +doc.$isDefault('path').valueOf(); +doc.depopulate('path'); +doc.equals(doc).valueOf(); +doc.execPopulate().then(function (arg) { + arg.execPopulate(); +}).catch(function (err) {}); +doc.get('path', Number); +doc.init(doc, cb).init(doc, {}, cb); +doc.inspect(); +doc.invalidate('path', new Error('hi'), 999).toString(); +doc.isDirectModified('path').valueOf(); +doc.isInit('path').valueOf(); +doc.isModified('path').valueOf(); +doc.isSelected('path').valueOf(); +doc.markModified('path'); +doc.modifiedPaths()[0].toLowerCase(); +doc.populate(function (err, doc) { + doc.populate('path', function (err, doc) { + doc.populate({ + path: 'path', + select: 'path', + match: {} + }); + }); +}); +doc.populated('path'); +doc.set('path', 999, {}).set({ path: 999 }); +doc.toJSON({ + getters: true, + virtuals: false +}); +doc.toObject({ + transform: function (doc, ret, options) { + doc.toObject(); + } +}); +doc.toString().toLowerCase(); +doc.unmarkModified('path'); +doc.update(doc, cb).cursor(); +doc.update(doc, { + safe: true, + upsert: true +}, cb).cursor(); +doc.validate({}, function (err) {}); +doc.validate().then(null).catch(null); +doc.validateSync(['path1', 'path2']).stack; +/* practical examples */ +var MyModel = mongoose.model('test', new mongoose.Schema({ + name: { + type: String, + default: 'Val ' + } +})); +doc = new MyModel(); +doc.$isDefault('name'); +MyModel.findOne().populate('author').exec(function (err, doc) { + if (doc) { + doc.depopulate('author'); + } +}); +doc.populate('path'); +doc.populate({path: 'hello'}); +doc.populate('path', cb) +doc.populate({path: 'hello'}, cb); +doc.populate(cb); +doc.populate({path: 'hello'}).execPopulate().catch(cb); +doc.update({$inc: {wheels:1}}, { w: 1 }, cb); + +const ImageSchema = new mongoose.Schema({ + name: {type: String, required: true}, + id: {type: Number, unique: true, required: true, index: true}, +}, { id: false }); + +interface ImageDoc extends mongoose.Document { + name: string, + id: number +} + +const ImageModel = mongoose.model('image', ImageSchema); + +ImageModel.findOne({}, function(err, doc) { + if (doc) { + doc.name; + doc.id; + } +}); + +/* + * section types/subdocument.js + * http://mongoosejs.com/docs/api.html#types-subdocument-js + */ +// The constructor is private api, but we'll use it to test +var subdocument: mongoose.Types.Subdocument = new mongoose.Types.Subdocument(); +subdocument.ownerDocument().errors; +subdocument.remove({}, function (err) { + return 6; +}); +/* inherited properties */ +subdocument.execPopulate(); + +/* + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ +var mongooseArray: mongoose.Types.Array = new mongoose.Types.Array(); +mongooseArray.$shift().toLowerCase(); +mongooseArray.remove().$shift(); +mongooseArray.$pop().toLowerCase(); +mongooseArray.addToSet('hi', 9, 9, '4')[0].toLowerCase(); +mongooseArray.indexOf({name: 'obj'}).toFixed(); +mongooseArray.inspect(); +mongooseArray.nonAtomicPush(9, 8, 'hi').toFixed(); +mongooseArray.pop().toLowerCase(); +mongooseArray.pull(5, 4, 'hi').$shift(); +mongooseArray.push([]).toFixed(); +mongooseArray.set(1, 'hi').$shift(); +mongooseArray.shift().toLowerCase(); +mongooseArray.sort(function (a, b) { + return a.length - b.length; +}).unshift(); +mongooseArray.splice(4, 1).unshift(); +mongooseArray.toObject({depopulate: true}).unshift(); +mongooseArray.unshift(2, 4, 'hi').toFixed(); +/* inherited properties */ +mongooseArray.concat(); +mongooseArray.length; +/* practical examples */ +interface MySubEntity extends mongoose.Types.Subdocument { + property1: string; + property2: string; +} +interface MyEntity extends mongoose.Document { + sub: mongoose.Types.Array +} +var myEntity = {}; +var subDocArray = _.filter(myEntity.sub, function (sd) { + sd.property1; + sd.property2.toLowerCase(); + return true; +}); + + +/* + * section types/documentarray.js + * http://mongoosejs.com/docs/api.html#types-documentarray-js + */ +// The constructor is private api, but we'll use it to test +var documentArray: mongoose.Types.DocumentArray = + new mongoose.Types.DocumentArray(); +documentArray.create({}).errors; +documentArray.id(new Buffer('hi')); +documentArray.inspect(); +documentArray.toObject({}).length; +/* inherited from mongoose.Types.Array */ +documentArray.$shift(); +/* inherited from Native Array */ +documentArray.concat(); +/* practical example */ +interface MySubEntity1 extends mongoose.Types.Subdocument { + property1: string; + property2: string; +} +interface MyEntity1 extends mongoose.Document { + sub: mongoose.Types.DocumentArray +} +var newEnt = {}; +var newSub: MySubEntity1 = newEnt.sub.create({ property1: "example", property2: "example" }); + +/* + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ +var mongooseBuffer: mongoose.Types.Buffer = new mongoose.Types.Buffer('hello'); +mongooseBuffer.copy(mongooseBuffer, 1, 2, 3).toFixed(); +mongooseBuffer.copy(new Buffer('hi')).toFixed(); +mongooseBuffer.equals(new Buffer('hi')).valueOf(); +mongooseBuffer.subtype(123); +mongooseBuffer.toObject().value(); +mongooseBuffer.write('world', 3, 2, 1).toFixed(); +/* inherited properties */ +mongooseBuffer.compare(mongooseBuffer); +/* inherited static properties */ +mongoose.Types.Buffer.from([1, 2, 3]); + +/* + * section types/decimal128.js + * http://mongoosejs.com/docs/api.html#types-decimal128-js + */ +var decimal128: mongoose.Types.Decimal128 = mongoose.Types.Decimal128.fromString('123.45678901234567'); +decimal128 = new mongoose.Types.Decimal128(new Buffer('12345')); +/* practical examples */ +export interface ILargeValuesSchema extends mongoose.MongooseDocument { + sum: mongoose.Schema.Types.Decimal128; +} +export var LargeValuesSchema = new mongoose.Schema({ + sum: { + type: mongoose.Schema.Types.Decimal128, + required: true + } +}); + +/* + * section types/objectid.js + * http://mongoosejs.com/docs/api.html#types-objectid-js + */ +var objectId: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('0x1234'); +objectId = new mongoose.Types.ObjectId(12345); +objectId = mongoose.Types.ObjectId(12345); +objectId.getTimestamp(); +/* practical examples */ +export interface IManagerSchema extends mongoose.MongooseDocument { + user: mongoose.Schema.Types.ObjectId; +} +export var ManagerSchema = new mongoose.Schema({ + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true + } +}); + +/* + * section types/embedded.js + * http://mongoosejs.com/docs/api.html#types-embedded-js + */ +var embeddedDocument: mongoose.Types.Embedded = new mongoose.Types.Embedded(); +embeddedDocument.inspect().hasOwnProperty(''); +embeddedDocument.invalidate('hi', new Error('bleh')).valueOf(); +embeddedDocument.ownerDocument().execPopulate(); +embeddedDocument.parent().execPopulate(); +embeddedDocument.parentArray().$shift(); +embeddedDocument.remove().invalidate('hi', new Error('hi')); +embeddedDocument.markModified('path'); +/* inherited properties */ +embeddedDocument.execPopulate(); + +/* + * section query.js + * http://mongoosejs.com/docs/api.html#query-js + */ +var query = > {}; +query.$where('').$where(cb); +query.all(99).all('path', 99); +query.and([{ color: 'green' }, { status: 'ok' }]).and([]); +query.batchSize(100).batchSize(100); +var lowerLeft = [40.73083, -73.99756] +var upperRight = [40.741404, -73.988135] +query.where('loc').within().box(lowerLeft, upperRight) +query.box({ ll : lowerLeft, ur : upperRight }).box({}); +var queryModel = mongoose.model('QModel') +query.cast(new queryModel(), {}).hasOwnProperty(''); +query.catch(cb).catch(cb); +query.center({}).center({}); +query.centerSphere({ center: [50, 50], radius: 10 }).centerSphere('path', {}); +query.circle({ center: [50, 50], radius: 10 }).circle('path'); +query.collation({ locale: 'en_US', strength: 1 }); +query.comment('comment').comment('comment'); +query.where({color: 'black'}).count(function (err, count) { + count.toFixed(); +}).then(function (res) { + res.toFixed(); +}).catch(function (err) {}); +query.cursor().close(); +query.distinct('field', {}, cb); +query.distinct('field', {}); +query.distinct('field', cb); +query.distinct('field'); +query.distinct(cb); +query.distinct(); +query.elemMatch('comment', { + author: 'autobot', + votes: {$gte: 5} +}).elemMatch('comment', function (elem) { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}); +query.where('age').equals(49); +query.exec('find', function (err, res) { + res[0].execPopulate(); +}).then(function (arg) { + arg[0].execPopulate(); +}).catch(cb); +query.where('name').exists().exists('age', false); +query.find({name: 'aa'}, function (err, res) { + res[0].execPopulate(); +}).find(); +query.findOne(function (err, res) { + res.execPopulate(); +}).findOne(); +query.findOneAndRemove({name: 'aa'}, { + passRawResult: true +}, function (err, doc) { + doc.execPopulate(); +}).findOneAndRemove(); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { + +}); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { + passRawResult: true +}, cb); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, cb); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}); +query.findOneAndUpdate({name: 'bb'}, cb); +query.findOneAndUpdate({name: 'bb'}); +query.findOneAndUpdate(cb); +query.findOneAndUpdate().then(function (doc) { + doc.execPopulate(); +}).catch(cb); +var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] +query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) +var polyB = [[ 0, 0 ], [ 1, 1 ]] +query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) +var polyC = [ 0, 0 ] +query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) +query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) +query.getQuery(); +query.getUpdate(); +query.find().where('age').gt(21); +query.find().gt('age', 21); +query.find().where('age').gte(21); +query.find().gte('age', 21); +query.hint({ indexA: 1, indexB: -1}).hint({}); +query.in([1, 2, 3]).in('num', [1, 2, 3]); +query.where('path').intersects().geometry({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}); +query.where('path').intersects({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}); +query.find().lean().exec(function (err: any, docs: any) { + docs[0]; +}); +query.limit(20).limit(20); +query.find().where('age').lt(21); +query.find().lt('age', 21); +query.find().where('age').lte(21); +query.find().lte('age', 21); +query.maxDistance('path', 21).maxDistance(21); +query.maxscan(100).maxScan(100); +query.maxScan(100).maxScan(100); +query.merge(query).merge({}); +query.mod([1, 2]).mod([5, 6]); +query.find().where('age').ne(21); +query.find().ne('age', 21); +query.where('loc').near({ center: [10, 10] }); +query.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); +query.near('loc', { center: [10, 10], maxDistance: 5 }); +query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); +query.find().where('age').in([20, 21]); +query.find().in('age', [20, 21]); +query.nor([{ color: 'green' }, { status: 'ok' }]).nor([]); +query.or([{ color: 'red' }, { status: 'emergency' }]).or([]); +query.where('loc').within().polygon([10,20], [13, 25], [7,15]); +query.polygon('loc', [10,20], [13, 25], [7,15]); +query.findOne().populate('owner').exec(function (err, kitten) { + kitten.execPopulate(); +}); +query.find().populate({ + path: 'owner' + , select: 'name' + , match: { color: 'black' } + , options: { sort: { name: -1 }} +}).exec(function (err, kittens) { + kittens[0].execPopulate(); +}); +query.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { + kittens[0].execPopulate(); +}); +query.read('primary', []).read('primary'); +query.regex(/re/).regex('path', /re/); +query.remove({}, cb); +query.remove({}); +query.remove(cb); +query.remove(); +query.select('a b'); +query.select('-c -d'); +query.select({ a: 1, b: 1 }); +query.select({ c: 0, d: 0 }); +query.select('+path'); +query.selected(); +query.selectedExclusively(); +query.selectedInclusively(); +query.setOptions({ + tailable: true, + batchSize: true, + lean: false +}); +query.size(0).size('age', 0); +query.skip(100).skip(100); +query.slaveOk().slaveOk(false); +query.slice('comments', 5); +query.slice('comments', -5); +query.slice('comments', [10, 5]); +query.where('comments').slice(5); +query.where('comments').slice([-10, 5]); +query.snapshot().snapshot(true); +query.sort({ field: 'asc', test: -1 }); +query.sort('field -test'); +query.stream().on('data', function (doc: any) { +}).on('error', function (err: any) { +}).on('close', function () { +}); +query.tailable().tailable(false); +query.then(cb).catch(cb); +(new (query.toConstructor())(1, 2, 3)).toConstructor(); +query.update({}, doc, { + +}, cb); +query.update({}, doc, { + +}); +query.update({}, doc, cb); +query.update({}, doc); +query.update(doc, cb); +query.update(doc); +query.update(cb); +query.update(true); +query.update(); +query.where('age').gte(21).lte(65) + .where('name', /^vonderful/i) + .where('friends').slice(10) + .exec(cb); +query.where('path').within().box({}) +query.where('path').within().circle({}) +query.where('path').within().geometry({type: 'c', coordinates: []}); +query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +query.where('loc').within({ polygon: [[],[],[],[]] }); +query.where('loc').within([], [], []); +query.where('loc').within([], []); +query.where('loc').within({ type: 'LineString', coordinates: [] }); +mongoose.Query.use$geoWithin = false; +/* practical example */ +query. + find({ + occupation: /host/, + 'name.last': 'Ghost', + age: { $gt: 17, $lt: 66 }, + likes: { $in: ['vaporizing', 'talking'] } + }). + limit(10). + sort({ occupation: -1 }). + select({ name: 1, occupation: 1 }). + exec(cb).then(cb).catch(cb); +query. + find({ occupation: /host/ }). + where('name.last').equals('Ghost'). + where('age').gt(17).lt(66). + where('likes').in(['vaporizing', 'talking']). + limit(10). + sort('-occupation'). + select('name occupation'). + exec(cb).then(cb).catch(cb); + +/* + * section schema/array.js + * http://mongoosejs.com/docs/api.html#schema-array-js + */ +var schemaArray: mongoose.Schema.Types.Array = new mongoose.Schema.Types.Array('key', new mongoose.SchemaType('hi'), {}); +schemaArray.checkRequired('hello').valueOf(); +/** static properties */ +mongoose.Schema.Types.Array.schemaName.toLowerCase(); +/** inherited properties */ +schemaArray.sparse(true); + +/* + * section schema/string.js + * http://mongoosejs.com/docs/api.html#schema-string-js + */ +var MongoDocument = {}; +var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello'); +schemastring.checkRequired(234, MongoDocument).valueOf(); +schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({}); +schemastring.lowercase().lowercase(); +schemastring.match(/re/, 'error').match(/re/); +schemastring.maxlength(999, 'error').maxlength(999); +schemastring.minlength(999, 'error').minlength(999); +schemastring.trim().trim(); +schemastring.uppercase().uppercase(); +/* static properties */ +mongoose.Schema.Types.String.schemaName.toLowerCase(); +/* inherited properties */ +schemastring.sparse(true); + +/* + * section schema/documentarray.js + * http://mongoosejs.com/docs/api.html#schema-documentarray-js + */ +var documentarray: mongoose.Schema.Types.DocumentArray = new mongoose.Schema.Types.DocumentArray('key', new mongoose.Schema()); +/* static properties */ +mongoose.Schema.Types.DocumentArray.schemaName.toLowerCase(); +/* inherited properties */ +documentarray.sparse(true); + +/* + * section schema/number.js + * http://mongoosejs.com/docs/api.html#schema-number-js + */ +var schemanumber: mongoose.Schema.Types.Number = new mongoose.Schema.Types.Number('num', {}); +schemanumber.checkRequired(999, MongoDocument).valueOf(); +schemanumber.max(999, 'error').max(999); +schemanumber.min(999, 'error').min(999); +/* static properties */ +mongoose.Schema.Types.Number.schemaName.toLowerCase(); +/* inherited properties */ +schemanumber.sparse(true); + +/* + * section schema/date.js + * http://mongoosejs.com/docs/api.html#schema-date-js + */ +var schemadate: mongoose.Schema.Types.Date = new mongoose.Schema.Types.Date('99'); +schemadate.checkRequired([], MongoDocument).valueOf(); +schemadate.expires(99).expires('now'); +schemadate.max(new Date(), 'error').max(new Date('')); +schemadate.min(new Date(), 'error').min(new Date('')); +/* static properties */ +mongoose.Schema.Types.Date.schemaName.toLowerCase(); +/* inherited properties */ +schemadate.sparse(true); + +/* + * section schema/buffer.js + * http://mongoosejs.com/docs/api.html#schema-buffer-js + */ +var schemabuffer: mongoose.Schema.Types.Buffer = new mongoose.Schema.Types.Buffer('99'); +schemabuffer.checkRequired(999, MongoDocument).valueOf(); +/* static properties */ +mongoose.Schema.Types.Buffer.schemaName.toLowerCase(); +/* inherited properties */ +schemabuffer.sparse(true); + +/* + * section schema/boolean.js + * http://mongoosejs.com/docs/api.html#schema-boolean-js + */ +var schemaboolean: mongoose.Schema.Types.Boolean = new mongoose.Schema.Types.Boolean('99'); +schemaboolean.checkRequired(99).valueOf(); +/* static properties */ +mongoose.Schema.Types.Boolean.schemaName.toLowerCase(); +/* inherited properties */ +schemaboolean.sparse(true); + +/* + * section schema/objectid.js + * http://mongoosejs.com/docs/api.html#schema-objectid-js + */ +var schemaobjectid: mongoose.Schema.Types.ObjectId = new mongoose.Schema.Types.ObjectId('99'); +schemaobjectid.auto(true).auto(false); +schemaobjectid.checkRequired(99, MongoDocument).valueOf(); +/* static properties */ +mongoose.Schema.Types.ObjectId.schemaName.toLowerCase(); +/* inherited properties */ +schemaobjectid.sparse(true); + +/* + * section schema/mixed.js + * http://mongoosejs.com/docs/api.html#schema-mixed-js + */ +var schemamixed: mongoose.Schema.Types.Mixed = new mongoose.Schema.Types.Mixed('99'); +/* static properties */ +mongoose.Schema.Types.Mixed.schemaName.toLowerCase(); +/* inherited properties */ +schemamixed.sparse(true); + +/* + * section schema/embedded.js + * http://mongoosejs.com/docs/api.html#schema-embedded-js + */ +var schemaembedded: mongoose.Schema.Types.Embedded = + new mongoose.Schema.Types.Embedded(new mongoose.Schema(), '99'); +/* inherited properties */ +schemaembedded.sparse(true); + +/* + * section aggregate.js + * http://mongoosejs.com/docs/api.html#aggregate-js + */ +var aggregate: mongoose.Aggregate; +aggregate = mongoose.model('ex').aggregate({ $match: { age: { $gte: 21 }}}); +aggregate = new mongoose.Aggregate(); +aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); +aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); +aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +aggregate.addCursorFlag('flag', true).addCursorFlag('', false); +aggregate.allowDiskUse(true).allowDiskUse(false, []); +aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); +aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); +aggregate.collation({ locale: 'en_US', strength: 1 }); +aggregate.cursor({ batchSize: 1000 }).exec().each(cb); +aggregate.exec().then(cb).catch(cb); +aggregate.explain(cb).then(cb).catch(cb); +aggregate.group({ _id: "$department" }).group({ _id: "$department" }); +aggregate.limit(10).limit(10); +var lookupOpt = { + from: 'users', localField: + 'userId', foreignField: '_id', + as: 'users' +}; +aggregate.lookup(lookupOpt).lookup(lookupOpt); +aggregate.match({ + department: {$in: [ "sales", "engineering"]} +}); +aggregate.model(new (mongoose.model('xx'))()).model(null); +aggregate.near({ + near: [40.724, -73.997], + distanceField: "dist.calculated", + maxDistance: 0.008, + query: { type: "public" }, + includeLocs: "dist.location", + uniqueDocs: true, + num: 5 +}); +aggregate.project("a b -_id"); +aggregate.project({a: 1, b: 1, _id: 0}); +aggregate.project({ + newField: '$b.nested' + , plusTen: { $add: ['$val', 10]} + , sub: { + name: '$a' + } +}) +aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ]}}); +aggregate.read('primaryPreferred').read('pp'); +aggregate.sample(3).sample(3); +aggregate.skip(10).skip(10); +aggregate.sort({ field: 'asc', test: -1 }); +aggregate.sort('field -test'); +aggregate.then(cb).catch(cb); +aggregate.unwind("tags").unwind('tags'); +aggregate.unwind("a", "b", "c").unwind('tag1', 'tag2'); +aggregate.unwind( + { + path: "tags", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }) + .unwind({ + path: "tags", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }); +aggregate.unwind( + { + path: "a", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "b", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "c", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }) + .unwind({ + path: "tag1", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "tag2", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }); + +/* + * section schematype.js + * http://mongoosejs.com/docs/api.html#schematype-js + */ +new mongoose.SchemaType('hello', 9, 'hello' ); +var STSchema = new mongoose.Schema({ + mixed: mongoose.Schema.Types.Mixed +}); +var schematype = schema.path('mixed'); +schematype.default('default'); +STSchema.path('born').get(cb).get(cb); +STSchema.path('name').index(true).index({ unique: true, sparse: true }); +schematype.required(true, 'mess').required(true); +schematype.select(true).select(false); +STSchema.path('name').set(cb).set(cb); +schematype.sparse(true).sparse(true); +schematype.text(true).text(true); +schematype.unique(true).unique(true); +schematype.validate(/re/) + .validate({}, 'error') + .validate(cb, 'try', 'tri'); + +/* + * section promise.js + * http://mongoosejs.com/docs/api.html#promise-js + */ +var mongopromise = new mongoose.Promise(); +mongopromise = new mongoose.Promise(function (err: any, arg: any) { + arg.sparse(true); + err.stack; +}); +mongopromise = new mongoose.Promise(function (err: any, arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); + err.stack; +}); +mongopromise.addBack(function (err: any, arg: any) { + err.stack; + arg.sparse(true); +}).addBack(function (err: any, arg1: any, arg2: any) { + err.stack; + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.addCallback(function (arg: any) { + arg.sparse(true); +}).addCallback(function (arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.addErrback(function (err: any) { + err.stack; +}).addErrback(function () {}); +mongopromise.catch(function (err: any) { + err.stack; +}).catch(function () {}); +mongopromise.end(); +mongopromise.error(999).error([]); +mongopromise.on('init', function () {}).on('init', function () {}); +mongopromise.reject({}).reject('').reject(new Error('hi')); +mongopromise.resolve(new Error('hi'), {}).resolve(); +mongopromise.then(function (arg: any) { + arg.sparse(true); +}, function (err: any) { + err.stack; +}).then(function (arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.complete(new mongoose.SchemaType('')).complete( + new mongoose.SchemaType(''), + new mongoose.SchemaType('') +); +/* static properties */ +mongoose.Promise.ES6(function (complete: Function, error: Function) { + complete.apply(this); + error.apply(this); +}); + +/* inherited properties */ +mongopromise.chain(mongopromise); +mongoose.Promise.FAILURE; +/* practical example */ +mongoose.model('') + .findOne({}) + .exec() + .then(function (arg) { + if (arg) { + arg.save; + } + return 1; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('string'); + }); + }).then(function (str) { + str.toLowerCase + return (mongoose.model('')).findOne({}).exec(); + }).then(function (arg) { + if (arg) { + arg.save; + } + return 1; + }).catch(function (err) { + return 1; + }).then(function (arg) { + arg.toFixed; + return new Promise<{a: string, b: number}>((resolve, reject) => { + resolve({a: 'hi', b: 29}); + }); + }).then(function (arg) { + arg.a.toLowerCase; + arg.b.toFixed; + }); + +mongoose.model('').findOne({}) + .then(function (arg) { + if (arg) { + arg.save; + } + return 2; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('str'); + }); + }).then(function (str) { + str.toLowerCase; + }); + +mongoose.model('').aggregate() + .then(function (arg) { + return 2; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('str'); + }); + }).then(function (str) { + str.toLowerCase; + }); + +/* pluggable promise */ +(mongoose).Promise = Promise; +require('mongoose').Promise = Promise; +mongoose.Promise.race; +mongoose.Promise.all; + +mongoose.model('').findOne() + .exec().then(cb); + +/* + * section model.js + * http://mongoosejs.com/docs/api.html#model-js + */ +var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ + name: String, + type: { + type: mongoose.Schema.Types.Mixed, + required: true + } +}), 'myCollection', true); +MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { + docs[0].save(); + docs[0].__v; +}); +MongoModel.findById(999, function (err, doc) { + var handleSave = function(err: Error, product: mongoose.Document, numAffected: number) {}; + if (!doc) { + return; + } + doc.increment(); + doc.save(handleSave).then(cb).catch(cb); + doc.save({ validateBeforeSave: false }, handleSave).then(cb).catch(cb); + doc.save({ safe: true }, handleSave).then(cb).catch(cb); + doc.save({ safe: { w: 2, j: true } }, handleSave).then(cb).catch(cb); + doc.save({ safe: { w: 'majority', wtimeout: 10000 } }, handleSave).then(cb).catch(cb); + + // test if Typescript can infer the types of (err, product, numAffected) + doc.save(function(err, product, numAffected) { product.save(); }) + .then(function(p) { p.save() }).catch(cb); + doc.save({ validateBeforeSave: false }, function(err, product, numAffected) { + product.save(); + }).then(function(p) { p.save() }).catch(cb); +}); +MongoModel = (new MongoModel()).model('MongoModel'); +var mongoModel = new MongoModel(); +mongoModel.remove(function (err, product) { + if (err) throw(err); + MongoModel.findById(product._id, function (err, product) { + if (product) { + product.id.toLowerCase(); + product.remove(); + } + }); +}); +mongoModel.save().then(function (product) { + product.save().then(cb).catch(cb); +}); +MongoModel.aggregate( + { $group: { _id: null, maxBalance: { $max: '$balance' }}} + , { $project: { _id: 0, maxBalance: 1 }} + , cb); +MongoModel.aggregate() + .group({ _id: null, maxBalance: { $max: '$balance' } }) + .exec(cb); +MongoModel.count({ type: 'jungle' }, function (err, count) { + count.toFixed(); +}); +MongoModel.create({ + type: 'jelly bean' +}, { + type: 'snickers' +}, cb).then(function (a) { + a.save(); +}) +MongoModel.create([{ type: 'jelly bean' }, { + type: 'snickers' +}], function (err, candies) { + var jellybean = candies[0]; + var snickers = candies[1]; +}).then(function (arg) { + arg[0].save(); + arg[1].save(); +}); +MongoModel.distinct('url', { clicks: {$gt: 100}}, function (err, result) { +}); +MongoModel.distinct('url').exec(cb); +MongoModel.ensureIndexes({}, cb); +MongoModel.find({ name: 'john', age: { $gte: 18 }}); +MongoModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) { + docs[0].remove(); + docs[1].execPopulate(); +}); +MongoModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) +MongoModel.find({ name: /john/i }, null, { skip: 10 }) +MongoModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); +MongoModel.find({ name: /john/i }, null, { skip: 10 }).exec(function (err, docs) {}); +MongoModel.findById(999, function (err, adventure) {}); +MongoModel.findById(999).exec(cb); +MongoModel.findById(999, 'name length', function (err, adventure) { + if (adventure) { + adventure.save(); + } +}); +MongoModel.findById(999, 'name length').exec(cb); +MongoModel.findById(999, '-length').exec(function (err, adventure) { + if (adventure) { + adventure.addListener('click', cb); + } +}); +MongoModel.findById(999, 'name', { lean: true }, function (err, doc) {}); +MongoModel.findById(999, 'name').lean().exec(function (err, doc) {}); +MongoModel.findByIdAndRemove(999, {}, cb); +MongoModel.findByIdAndRemove(999, {}); +MongoModel.findByIdAndRemove(999, cb); +MongoModel.findByIdAndRemove(999); +MongoModel.findByIdAndRemove(); +MongoModel.findByIdAndUpdate(999, {}, {}, cb); +MongoModel.findByIdAndUpdate(999, {}, {}); +MongoModel.findByIdAndUpdate(999, {}, cb); +MongoModel.findByIdAndUpdate(999, {}); +MongoModel.findByIdAndUpdate(); +MongoModel.findOne({ type: 'iphone' }, function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }, cb); +MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(cb); +MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec(cb); +interface ModelUser { + _id: any; + name: string; + abctest: string; +} +MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec() +.then(function(doc: ModelUser) { + doc._id; + doc.name; + doc.abctest; +}); +MongoModel.findOneAndRemove({}, {}, cb); +MongoModel.findOneAndRemove({}, {}); +MongoModel.findOneAndRemove({}, cb); +MongoModel.findOneAndRemove({}); +MongoModel.findOneAndRemove(); +MongoModel.findOneAndUpdate({}, {}, {}, cb); +MongoModel.findOneAndUpdate({}, {}, {}); +MongoModel.findOneAndUpdate({}, {}, cb); +MongoModel.findOneAndUpdate({}, {}); +MongoModel.findOneAndUpdate(); +MongoModel.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { + results[0].on('data', cb); +}); +MongoModel.geoNear({ type : "Point", coordinates : [9,9] }, { + maxDistance : 5, spherical : true +}, function(err, results, stats) { + console.log(results); +}); +MongoModel.geoSearch({ type : "house" }, { + near: [10, 10], maxDistance: 5 +}, function(err, res) { + res[0].remove(); +}); +MongoModel.hydrate({ + _id: '54108337212ffb6d459f854c', + type: 'jelly bean' +}).execPopulate(); +MongoModel.insertMany([ + { name: 'Star Wars' }, + { name: 'The Empire Strikes Back' } +], function(error, docs) {}); +MongoModel.insertMany({name: 'Star Wars'}, function(error, doc) {}); +MongoModel.mapReduce({ + map: cb, + reduce: cb +}, function (err, results) { + console.log(results) +}).then(function (model) { + return model.find().where('value').gt(10).exec(); +}).then(function (docs) { + console.log(docs); +}).then(null, cb); +MongoModel.findById(999, function (err, user) { + if (!user) { + return; + } + var opts = [ + { path: 'company', match: { x: 1 }, select: 'name' } + , { path: 'notes', options: { limit: 10 }, model: 'override' } + ] + MongoModel.populate(user, opts, cb); + MongoModel.populate(user, opts, function (err, user) { + console.log(user); + }); +}); +MongoModel.find(999, function (err, users) { + var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] + var promise = MongoModel.populate(users, opts); + promise.then(console.log); +}); +MongoModel.populate({ + name: 'Indiana Jones', + weapon: 389 +}, { + path: 'weapon', + model: 'Weapon' +}, cb); +var users = [{ name: 'Indiana Jones', weapon: 389 }] +users.push({ name: 'Batman', weapon: 8921 }) +MongoModel.populate(users, { path: 'weapon' }, function (err, users) { + users.forEach(cb); +}); +MongoModel.remove({ title: 'baby born from alien father' }, cb); +MongoModel.remove({_id: '999'}).exec().then(cb).catch(cb); +MongoModel.update({ age: { $gt: 18 } }, { oldEnough: true }, cb); +MongoModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, cb); +MongoModel.where('age').gte(21).lte(65).exec(cb); +MongoModel.where('age').gte(21).lte(65).where('name', /^b/i); +new (mongoModel.base.model(''))(); +mongoModel.baseModelName.toLowerCase(); +mongoModel.collection.$format(99); +mongoModel.collection.initializeOrderedBulkOp; +mongoModel.collection.findOne; +mongoModel.db.openSet(''); +mongoModel.discriminators; +mongoModel.modelName.toLowerCase(); +MongoModel = mongoModel.base.model('new', mongoModel.schema); +/* inherited properties */ +MongoModel.modelName; +mongoModel.modelName; +MongoModel.collection; +mongoModel.collection; +mongoModel._id; +mongoModel.execPopulate(); +mongoModel.on('data', cb); +mongoModel.addListener('event', cb); +MongoModel.findOne({ title: /timex/i }) + .populate('_creator', 'name') + .exec(function (err, story) { + if (story) { + story.execPopulate(); + } + }); +MongoModel.find({ + id: 999 +}) +.populate({ + path: 'fans', + match: { age: { $gte: 21 }}, + select: 'name -_id', + options: { limit: 5 } +}) +.exec(); +/* practical example */ +interface Location extends mongoose.Document { + name: string; + address: string; + rating: number; + facilities: string[]; + coords: number[]; + openingTimes: any[]; + reviews: any[]; +}; +const locationSchema = new mongoose.Schema({ + name: { type: String, required: true }, + address: String, + rating: { type: Number, "default": 0, min: 0, max: 5 }, + facilities: [String], + coords: { type: [Number], index: "2dsphere" }, + openingTimes: [mongoose.Schema.Types.Mixed], + reviews: [mongoose.SchemaTypes.Mixed] +}); +var LocModel = mongoose.model("Location", locationSchema); +LocModel.findById(999) + .select("-reviews -rating") + .exec(function (err, location) { + if (!location) { + return; + } + location.name = 'blah'; + location.address = 'blah'; + location.reviews.forEach(review => {}); + location.facilities.forEach(facility => { + facility.toLowerCase(); + }); + }); +LocModel.find() + .select('-reviews -rating') + .exec(function (err, locations) { + locations.forEach(location => { + location.name = 'blah'; + location.address = 'blah'; + location.reviews.forEach(review => {}); + location.facilities.forEach(facility => { + facility.toLowerCase(); + }); + }); + }); +LocModel.find({}).$where('') + .exec(function (err, locations) { + locations[0].name; + locations[1].openingTimes; + }); +LocModel.count({}) + .exec(function (err, count) { + count.toFixed(); + }); +LocModel.distinct('') + .select('-review') + .exec(function (err, distinct) { + distinct.concat; + }) + .then(cb).catch(cb); +LocModel.findByIdAndRemove() + .exec(function (err, doc) { + if (!doc) { + return; + } + doc.addListener; + doc.openingTimes; + }); +LocModel.findByIdAndUpdate() + .select({}) + .exec(function (err, location) { + if (location) { + location.reviews; + } + }); +LocModel.findOne({}, function (err, doc) { + if (doc) { + doc.openingTimes; + } +}); +LocModel.findOneAndRemove() + .exec(function (err, location) { + if (location) { + location.name; + } + }); +LocModel.findOneAndUpdate().exec().then(function (arg) { + if (arg) { + arg.openingTimes; + } +}); +LocModel.geoSearch({}, { + near: [1, 2], + maxDistance: 22 +}, function (err, res) { res[0].openingTimes; }); +interface IStatics { + staticMethod2: (a: number) => string; +} +interface MyDocument extends mongoose.Document { + prop: string; + method: () => void; +} +interface MyModel extends mongoose.Model { + staticProp: string; + staticMethod: () => void; +} +interface ModelStruct { + doc: MyDocument; + model: MyModel; + method1: (callback: (model: MyModel, doc: MyDocument) => void) => MyModel; +} +var modelStruct1 = {}; +var myModel1: MyModel; +var myDocument1: MyDocument; +modelStruct1.method1(function (myModel1, myDocument1) { + myModel1.staticProp; + myModel1.staticMethod(); + myDocument1.prop; + myDocument1.method(); +}).staticProp.toLowerCase(); +var mySchema = new mongoose.Schema({}); +export var Final: MyModel = mongoose.connection.model('Final', mySchema); +Final.findOne(function (err: any, doc: MyDocument) { + doc.save(); + doc.remove(); + doc.model(''); +}); +export var Final2: MyModel = mongoose.model('Final2', mySchema); +Final2.staticMethod(); +Final2.staticProp; +var final2 = new Final2(); +final2.prop; +final2.method;interface ibase extends mongoose.Document { + username: string; +} +interface extended extends ibase { + email: string; +} +const base: mongoose.Model = mongoose.model('testfour') +const extended: mongoose.Model = base.discriminator('extendedS', schema); +const x = new extended({ + username: 'hi', // required in baseSchema + email: 'beddiw', // required in extededSchema +}); diff --git a/types/mongoose/v4/tsconfig.json b/types/mongoose/v4/tsconfig.json new file mode 100644 index 0000000000..ad36fd5ca3 --- /dev/null +++ b/types/mongoose/v4/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "mongoose": [ + "mongoose/v4" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mongoose-tests.ts" + ] +} \ No newline at end of file diff --git a/types/mongoose/v4/tslint.json b/types/mongoose/v4/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/mongoose/v4/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index a551d15ba8..272abb5e39 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -251,6 +251,7 @@ export declare class Request extends events.EventEmitter { public parameters: IRequestParameters; public verbose: boolean; public canceled: boolean; + public multiple: boolean; public stream: any; public constructor(connection?: ConnectionPool); public constructor(transaction: Transaction); diff --git a/types/new-relic-browser/index.d.ts b/types/new-relic-browser/index.d.ts new file mode 100644 index 0000000000..59b2f9a8e6 --- /dev/null +++ b/types/new-relic-browser/index.d.ts @@ -0,0 +1,209 @@ +// Type definitions for NewRelicBrowser 0.1072 +// Project: https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api +// Definitions by: Rene Hamburger , Piotr Kubisa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const newrelic: NewRelic.Browser; + +declare namespace NewRelic { + interface Browser { + /** + * Adds a unique name and ID to identify releases with multiple JavaScript bundles on the same page. + * + * @param releaseName A short description of the component; for example, the name of a project, + * application, file, or library. + * @param releaseId The ID or version of this release; for example, a version number, build number + * from your CI environment, GitHub SHA, GUID, or a hash of the contents. Since New Relic converts this + * value into a string, you can also use null or undefined if necessary + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/addRelease + */ + addRelease(releaseName: string, releaseId: string): void; + + /** + * Reports a Browser PageAction event to Insights along with a name and attributes. + * + * @param name Name or category of the action. Reports to Insights as the actionName attribute. + * @param attributes JSON object with one or more key/value pairs. + * The key will report to Insights as its own PageAction attribute with the specified values. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/addPageAction + */ + addPageAction(name: string, attributes: { [key: string]: string }): void; + + /** + * Adds a JavaScript object with a custom name, start time, etc. to an in-progress session trace. + * + * @param eventObject If you are sending the same event object to New Relic Insights as a + * PageAction, omit the TYPE attribute. If included, it will override the event type and cause the + * PageAction event to be sent incorrectly. Instead, use the NAME attribute for event information. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/add-to-trace + */ + addToTrace(eventObject: EventObject): void; + + /** + * Records an additional time point as "finished" in a session trace, and sends the event to Insights. + * + * @param timestamp Defaults to the current time of the call. If used, this marks the time that + * the page is "finished" according to your own criteria. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/finished + */ + finished(timestamp?: number): void; + + /** + * Identifies a browser error without disrupting your app's operations. + * + * @param Provide a meaningful error message that you can use when analyzing data on + * New Relic Browser's JavaScript errors page. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/noticeError + */ + noticeError(error: any): void; + + /** + * Adds a user-defined attribute name and value to subsequent events on the page. + * + * @param name Name of the attribute. Appears as column in the PageView event. + * It will also appear as a column in the PageAction event if you are using it. + * @param value Value of the attribute. Appears as the value in the named attribute column in the + * PageView event. It will appear as a column in the PageAction event if you are using it. Custom attribute + * values cannot be complex objects, only simple types such as strings and numbers. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setCustomAttribute + */ + setCustomAttribute(name: string, value: string): void; + + /** + * Allows selective ignoring of known errors that the Browser agent captures. + * + * @param filterCallback The callback will be called with each error, so it is not + * specific to one error. `err` will usually be an error object, but it can be other data types. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setErrorHandler + */ + setErrorHandler(filterCallback: (err: any) => boolean): void; + + /** + * Groups page views to help URL structure or to capture the URL's routing information. + * + * @param name Name of the page you want to use when viewing it in New Relic Browser or Insights. + * @param host Default is http://custom.transaction. Typically set host to your site's domain URI. + * To further group these custom transactions, provide a custom host. Otherwise, the page views will be + * assigned the default domain custom.transaction. Segments within the name must be explicitly added to + * the Whitelist segments in your URL whitelist settings if they do not already appear. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setPageViewName + */ + setPageViewName(name: string, host?: string): void; + + /** + * Returns a new API object that is bound to the current SPA interaction. + * + * @returns This method returns an API object that is bound to a specific BrowserInteraction + * event. Each time this method is called for the same BrowserInteraction, a new object is created, but it still + * references the same interaction. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/interaction-browser-spa-api + */ + interaction(): BrowserInteraction; + + /** + * Gives SPA routes more accurate names than default names. Monitors specific routes rather than by default + * grouping. + * + * @param name Current route name for the page. Route names passed to setCurrentRouteName() can + * be any string, but they should represent a routing pattern rather than a specific resource. For example, + * use /users/:id rather than /users/123. If null, exits out of the route change requirement and returns to + * the default naming strategy. + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-set-current-route-name + */ + setCurrentRouteName(name: string): void; + } + + interface EventObject { + /** Event name */ + name: string; + /** Start time in ms since epoch */ + start: number; + /** End time in ms since epoch. Defaults to same as start resulting in trace object with a duration of zero. */ + end?: number; + /** Origin of event */ + origin?: string; + /** Event type */ + type?: string; + } + + interface BrowserInteraction { + /** + * Times sub-components of a SPA interaction separately, including wait time and JS execution time. + * + * @param name This will be used as the name of the tracer. If you do not include a name, + * New Relic Browser does not add a node to the interaction tree. The callback time will be + * attributed to the parent node. + * @param syncCallback + * @returns This method ends the async time. It calls (and times) the callback that was passed into createTracer(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-create-tracer + */ + createTracer(name: string, syncCallback?: () => void): () => void; + + /** + * Ends the New Relic SPA interaction at the current time. + * + * @returns This method returns the same API object created by interaction(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-end + */ + end(): BrowserInteraction; + + /** + * Stores values across the current SPA interaction asynchronously in New Relic Browser. + * + * @param callback A function that accepts the interaction context object + * as its only argument. + * @returns This method returns the same API object created by interaction(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-get-context + */ + getContext(callback: (contextObject: any) => void): BrowserInteraction; + + /** + * Overrides other SPA save() calls; ignores an interaction so it is not saved or sent to New Relic. + * + * @returns This method returns the same API object created by interaction(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-ignore-browser + */ + ignore(): BrowserInteraction; + + /** + * Adds custom attributes for SPA interactions to the end of an event. It is called when the interaction + * has finished. You can invoke methods to modify the interaction, but methods that have asynchronous + * side effects will not have an effect. + * + * @param callback + * @returns This method returns the same API object created by interaction(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-on-end + */ + onEnd(callback: (contextObject: any) => void): BrowserInteraction; + + /** + * Ensures a SPA browser interaction will be saved when it ends. + * + * @returns This method returns the same API object created by interaction(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-save + */ + save(): BrowserInteraction; + + /** + * Adds a custom SPA attribute only to the current interaction in New Relic Browser. + * + * @param key Used as the attribute name on the BrowserInteraction event. + * @param Used as the attribute value on the BrowserInteraction event. This can be a + * string, number, boolean, or object. If it is an object, New Relic serializes it to a JSON string. + * @returns This method returns the same API object created by interaction(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-set-attribute + */ + setAttribute(key: string, value: any): BrowserInteraction; + + /** + * Sets the name and trigger of a SPA's browser interaction that is not a route change or URL change. + * + * @param name If null, the name will be set using the targetGroupedUrl attribute. + * If not null, this will set the browserInteractionName attribute in the BrowserInteraction event. + * @param trigger If not null, this will set the TRIGGER attribute on the BrowserInteraction event. + * @returns This method returns the same API object created by interaction(). + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/spa-set-name + */ + setName(name: string, trigger?: string): BrowserInteraction; + } +} diff --git a/types/new-relic-browser/new-relic-browser-tests.ts b/types/new-relic-browser/new-relic-browser-tests.ts new file mode 100644 index 0000000000..b9f75b142d --- /dev/null +++ b/types/new-relic-browser/new-relic-browser-tests.ts @@ -0,0 +1,87 @@ +// The following tests are largely taken straight from the examples at https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api + +// --- NewRelic.Browser methods ---------------------------------------------- + +// addRelease() +newrelic.addRelease('checkout page', 'a818994'); + +// addPageAction() +newrelic.addPageAction('copy-text-button', { result: 'success' }); + +// addToTrace() +newrelic.addToTrace({ + name: 'Event Name', + start: 1417044274239, + end: 1417044274252, + origin: 'Origin of event', + type: 'What type of event was this' +}); +newrelic.addToTrace({ + name: 'Event Name', + start: 1417044274239 +}); + +// finished() +newrelic.finished(); + +// noticeError() +try { + JSON.parse('{ "bar"'); +} catch (err) { + newrelic.noticeError(err); +} +newrelic.noticeError(new Error('bar')); + +// setCustomAttribute() +newrelic.setCustomAttribute('nodeId', '123'); + +// setErrorHandler() +newrelic.setErrorHandler((err) => { + if (err.message !== 'foo') { + return true; + } else { + return false; + } +}); + +// setPageViewName() +newrelic.setPageViewName('/login', 'https://www.myapp.com'); + +// setCurrentRouteName() +newrelic.setCurrentRouteName('/users/:id'); + +// --- NewRelic.BrowserInteraction methods ----------------------------------- + +// createTracer() +newrelic + .interaction() + .createTracer('customSegment', () => { })(); + +// end() +newrelic.interaction().end(); + +// getContext(), setAttribute() +const interaction = newrelic.interaction(); +interaction.getContext(ctx => { + if (ctx.productId) { + interaction.setAttribute('productId', ctx.productId); + } +}); + +// ignore() +newrelic.interaction().ignore(); + +// onEnd(), setAttribute() +newrelic.interaction().onEnd(ctx => { + interaction.setAttribute( + 'averageChartLoadTime', + ctx.totalChartLoadTime / ctx.chartLoadCount + ); +}); + +// setName(), setAttribute(), save() +newrelic.interaction() + .setName('loadNextPage') + .setAttribute('username', 'userName') + .setAttribute('userId', 123) + .save(); diff --git a/types/new-relic-browser/tsconfig.json b/types/new-relic-browser/tsconfig.json new file mode 100644 index 0000000000..61ee6742c7 --- /dev/null +++ b/types/new-relic-browser/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "new-relic-browser-tests.ts" + ] +} diff --git a/types/new-relic-browser/tslint.json b/types/new-relic-browser/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/new-relic-browser/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 8f4e6cf636..38f043554b 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 9.3.x +// Type definitions for Node.js 9.4.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -410,6 +410,7 @@ declare namespace NodeJS { setMaxListeners(n: number): this; getMaxListeners(): number; listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; emit(event: string | symbol, ...args: any[]): boolean; listenerCount(type: string | symbol): number; // Added in Node 6... @@ -520,6 +521,7 @@ declare namespace NodeJS { export interface WriteStream extends Socket { readonly writableHighWaterMark: number; + readonly writableLength: number; columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; @@ -532,6 +534,7 @@ declare namespace NodeJS { } export interface ReadStream extends Socket { readonly readableHighWaterMark: number; + readonly readableLength: number; isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; @@ -916,6 +919,7 @@ declare module "events" { setMaxListeners(n: number): this; getMaxListeners(): number; listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; emit(event: string | symbol, ...args: any[]): boolean; eventNames(): Array; listenerCount(type: string | symbol): number; @@ -1466,27 +1470,28 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function deflate(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function deflateRaw(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function gzip(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function gzip(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function gzipSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function gunzip(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function gunzip(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function gunzipSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function inflate(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function inflate(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function inflateRaw(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateRaw(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function unzip(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function unzip(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function unzipSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + type InputType = string | Buffer | DataView | ArrayBuffer /* | TypedArray */; + export function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + export function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + export function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + export function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + export function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + export function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + export function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; export namespace constants { // Allowed flush values. @@ -5304,7 +5309,8 @@ declare module "stream" { export class Readable extends Stream implements NodeJS.ReadableStream { readable: boolean; - readableHighWaterMark: number; + readonly readableHighWaterMark: number; + readonly readableLength: number; constructor(opts?: ReadableOptions); _read(size: number): void; read(size?: number): any; @@ -5392,6 +5398,7 @@ declare module "stream" { export class Writable extends Stream implements NodeJS.WritableStream { writable: boolean; readonly writableHighWaterMark: number; + readonly writableLength: number; constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void; @@ -5484,6 +5491,7 @@ declare module "stream" { export class Duplex extends Readable implements Writable { writable: boolean; readonly writableHighWaterMark: number; + readonly writableLength: number; constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void; diff --git a/types/nodemailer/lib/mailer/index.d.ts b/types/nodemailer/lib/mailer/index.d.ts index f08c2d085d..bd9dd7ba8d 100644 --- a/types/nodemailer/lib/mailer/index.d.ts +++ b/types/nodemailer/lib/mailer/index.d.ts @@ -3,7 +3,7 @@ import { EventEmitter } from 'events'; import { Socket } from 'net'; import { Readable } from 'stream'; -import { URL } from 'url'; +import { Url } from 'url'; import { SentMessageInfo, Transport, TransportOptions } from '../..'; import * as shared from '../shared'; @@ -34,7 +34,7 @@ declare namespace Mail { /** String, Buffer or a Stream contents for the attachmentent */ content?: string | Buffer | Readable; /** path to a file or an URL (data uris are allowed as well) if you want to stream the file instead of including it (better for larger attachments) */ - path?: string | URL; + path?: string | Url; } interface Attachment extends AttachmentLike { @@ -175,11 +175,11 @@ declare class Mail extends EventEmitter { setupProxy(proxyUrl: string): void; set(key: 'oauth2_provision_cb', value: (user: string, renew: boolean, callback: (err: Error | null, accessToken?: string, expires?: number) => void) => void): Map; - set(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a', value: (proxy: URL, options: TransportOptions, callback: (err: Error | null, socketOptions?: { connection: Socket }) => void) => void): Map; + set(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a', value: (proxy: Url, options: TransportOptions, callback: (err: Error | null, socketOptions?: { connection: Socket }) => void) => void): Map; set(key: string, value: any): Map; get(key: 'oauth2_provision_cb'): (user: string, renew: boolean, callback: (err: Error | null, accessToken: string, expires: number) => void) => void; - get(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a'): (proxy: URL, options: TransportOptions, callback: (err: Error | null, socketOptions: { connection: Socket }) => void) => void; + get(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a'): (proxy: Url, options: TransportOptions, callback: (err: Error | null, socketOptions: { connection: Socket }) => void) => void; get(key: string): any; addListener(event: 'error', listener: (err: Error) => void): this; diff --git a/types/oauth2-server/index.d.ts b/types/oauth2-server/index.d.ts index a423f48a58..06b6fbadb0 100644 --- a/types/oauth2-server/index.d.ts +++ b/types/oauth2-server/index.d.ts @@ -5,7 +5,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -import { Request, RequestHandler } from "express"; +import Express = require("express"); /** * Represents an OAuth2 server instance. diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 924b66f514..c217a6d873 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -14618,6 +14618,7 @@ declare module olx { maxZoom?: number; duration?: number; easing?: ((t: number) => number); + callback?: olx.animation.AnimateCallback; } } diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index 666b7b746f..4353f48960 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -399,6 +399,10 @@ let view: ol.View = new ol.View({ voidValue = view.setMaxZoom(numberValue); voidValue = view.setMinZoom(numberValue); +voidValue = view.fit(simpleGeometry); +voidValue = view.fit(extent); +voidValue = view.fit(extent, {callback: () => {}}); +voidValue = view.fit(extent, {callback: (animationCompleted: boolean) => {}}); // // ol.layer.Base diff --git a/types/p-limit/index.d.ts b/types/p-limit/index.d.ts index a10fd05e1e..416622298b 100644 --- a/types/p-limit/index.d.ts +++ b/types/p-limit/index.d.ts @@ -7,4 +7,4 @@ declare namespace pLimit {} export = pLimit; -declare function pLimit(concurrency: number): (fn: () => PromiseLike) => Promise; +declare function pLimit(concurrency: number): (fn: () => PromiseLike) => Promise; diff --git a/types/p-limit/p-limit-tests.ts b/types/p-limit/p-limit-tests.ts index 6e50894802..e04b895e87 100644 --- a/types/p-limit/p-limit-tests.ts +++ b/types/p-limit/p-limit-tests.ts @@ -1,6 +1,6 @@ import pLimit = require('p-limit'); -const limit = pLimit(1); +const limit = pLimit(1); const input = [ limit(() => Promise.resolve('foo')), diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 64d961ed10..5bd4315bfd 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -290,7 +290,7 @@ declare module paper { * Transforms a point and returns the result. * @param point - the point to be transformed */ - transform(point: Point): Matrix; + transform(point: Point): Point; /** * Transforms an array of coordinates by this matrix and stores the results into the destination array, which is also returned. @@ -304,7 +304,7 @@ declare module paper { * Inverse transforms a point and returns the result. * @param point - the point to be transformed */ - inverseTransform(point: Point): Matrix; + inverseTransform(point: Point): Point; /** * Attempts to decompose the affine transformation described by this matrix into scaling, rotation and shearing, and returns an object with these properties if it succeeded, null otherwise. @@ -1308,12 +1308,12 @@ declare module paper { * The function to be called when the mouse button is pushed down on the item. The function receives a MouseEvent object which contains information about the mouse event. */ onMouseDown: (event: MouseEvent) => void; - + /** * The function to be called when the mouse position changes while the mouse is being dragged. The function receives a MouseEvent object which contains information about the mouse event. */ onMouseDrag: (event: MouseEvent) => void; - + /** * The function to be called when the mouse button is released over the item. * The function receives a MouseEvent object which contains information about the mouse event. @@ -1353,9 +1353,11 @@ declare module paper { /** * Clones the item within the same project and places the copy above the item. - * @param insert [optional] - specifies whether the copy should be inserted into the DOM. When set to true, it is inserted above the original. default: true + * @param options [optional] - object with 2 parameters + * insert: specifies whether the copy should be inserted into the DOM. When set to true, it is inserted above the original. default: true + * deep: specifies whether the item’s children should also be cloned — default: true */ - clone(insert?: boolean): Item; + clone(options?: { insert?: boolean, deep?: boolean }): Item; /** * When passed a project, copies the item to the project, or duplicates it within the same project. When passed an item, copies the item into the specified item. @@ -3535,7 +3537,7 @@ declare module paper { * @param highlight [optional] - */ constructor(color: Gradient, origin: Point, destination: Point, highlight?: Point); - + /** * Creates a RGB Color object. * @param hex - the RGB color in hex, i.e. #000000 @@ -3769,6 +3771,48 @@ declare module paper { */ onResize: (event: Event) => void; + /** + * The function to be called when the mouse button is pushed down on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseDown: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse position changes while the mouse is being dragged. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseDrag: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse button is released over the item. + * The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseUp: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse clicks on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onClick: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse double clicks on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onDoubleClick: (event: MouseEvent) => void; + + /** + * The function to be called repeatedly when the mouse moves on top of the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseMove: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse moves over the item. This function will only be called again, once the mouse moved outside of the item first. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseEnter: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse moves out of the item. + * The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseLeave: (event: MouseEvent) => void; + /** * Removes this view from the project and frees the associated element. */ diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index b053b46790..6d7dfaf351 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Pixi.js 4.6 +// Type definitions for Pixi.js 4.7 // Project: https://github.com/pixijs/pixi.js/tree/dev // Definitions by: clark-stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -63,6 +63,7 @@ declare namespace PIXI { let PRECISION: string; let UPLOADS_PER_FRAME: number; let CAN_UPLOAD_SAME_BUFFER: boolean; + let MESH_CANVAS_PADDING: number; } ////////////////////////////////////////////////////////////////////////////// @@ -208,6 +209,7 @@ declare namespace PIXI { renderer: PIXI.WebGLRenderer | PIXI.CanvasRenderer; stage: Container; ticker: ticker.Ticker; + loader: loaders.Loader; readonly screen: Rectangle; stop(): void; @@ -497,6 +499,7 @@ declare namespace PIXI { drawCircle(x: number, y: number, radius: number): Graphics; drawEllipse(x: number, y: number, width: number, height: number): Graphics; drawPolygon(path: number[] | Point[] | Polygon): Graphics; + drawStar(x: number, y: number, points: number, radius: number, innerRadius: number, rotation?: number): Graphics; clear(): Graphics; isFastRect(): boolean; protected _renderCanvas(renderer: CanvasRenderer): void; @@ -1737,7 +1740,9 @@ declare namespace PIXI { // shader - class Shader extends glCore.GLShader { } + class Shader extends glCore.GLShader { + constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[], attributeLocations?: { [key: string]: number }, precision?: string); + } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////EXTRACT/////////////////////////////////////////// @@ -2163,7 +2168,7 @@ declare namespace PIXI { // pixi loader extends // https://github.com/englercj/resource-loader/ - // 2.0.9 + // 2.1.1 class MiniSignalBinding { //tslint:disable-next-line:ban-types forbidden-types @@ -2251,6 +2256,8 @@ declare namespace PIXI { onStart: MiniSignal; onComplete: MiniSignal; + concurrency: number; + add(...params: any[]): this; //tslint:disable-next-line:ban-types forbidden-types add(name: string, url: string, options?: LoaderOptions, cb?: Function): this; @@ -2268,6 +2275,7 @@ declare namespace PIXI { protected _prepareUrl(url: string): string; //tslint:disable-next-line:ban-types forbidden-types protected _loadResource(resource: Resource, dequeue: Function): void; + protected _onStart(): void; protected _onComplete(): void; protected _onLoad(resource: Resource): void; @@ -2523,7 +2531,11 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// namespace particles { interface ParticleContainerProperties { + /** + * DEPRECIATED - Use `vertices` + */ scale?: boolean; + vertices?: boolean; position?: boolean; rotation?: boolean; uvs?: boolean; @@ -2531,7 +2543,7 @@ declare namespace PIXI { alpha?: boolean; } class ParticleContainer extends Container { - constructor(maxSize?: number, properties?: ParticleContainerProperties, batchSize?: number, autoSize?: boolean); + constructor(maxSize?: number, properties?: ParticleContainerProperties, batchSize?: number, autoResize?: boolean); protected _tint: number; protected tintRgb: number | any[]; tint: number; diff --git a/types/promise-queue/index.d.ts b/types/promise-queue/index.d.ts new file mode 100644 index 0000000000..efeaf04909 --- /dev/null +++ b/types/promise-queue/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for promise-queue 2.2 +// Project: https://github.com/azproduction/promise-queue +// Definitions by: Lachlan Stuart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = PromiseQueue; + +declare class PromiseQueue { + /** + * + * @param maxPendingPromises [Infinity] Number of promises that can run at once. + * @param maxQueuedPromises [Infinity] Number of promises generators that can be in the queue at once. + * `add()` will return a rejected promise if this limit would be exceeded. + * @param options [{}] See QueueOptions + */ + constructor(maxPendingPromises?: number, maxQueuedPromises?: number, options?: PromiseQueue.QueueOptions); + + /** + * Enqueue a promise generator. When the number of running promises is less than `maxPendingPromises`, + * this function will be called and the returned promise will be held as a running promise until it + * rejects or resolves. + * + * @throws If the global `Promise` is undefined and `Queue.configure` hasn't been called. + * @param promiseGenerator A function that returns a promise when called. + * @returns A promise that forwards the resolution/rejection of the promise returned by `promiseGenerator`, + * or immediately rejects if `maxQueuedPromise` is exceeded. + */ + add(promiseGenerator: () => Promise): Promise; + + /** + * Returns the number of promiseGenerators waiting in queue. + */ + getPendingLength(): number; + + /** + * Returns the number of in-flight promises + */ + getQueueLength(): number; + + /** + * Set which promise constructor to use for the value returned by PromiseQueue#add. + * If this isn't called, the global `Promise` constructor is used. + * @param GlobalPromise A constructor for Promises + */ + static configure(GlobalPromise: PromiseConstructor): void; +} + +declare namespace PromiseQueue { + interface QueueOptions { + /** + * Callback that is called when the queue is empty and all pending promises have resolved + */ + onEmpty(): void; + } +} diff --git a/types/promise-queue/promise-queue-tests.ts b/types/promise-queue/promise-queue-tests.ts new file mode 100644 index 0000000000..fb3764c98f --- /dev/null +++ b/types/promise-queue/promise-queue-tests.ts @@ -0,0 +1,11 @@ +import * as PromiseQueue from 'promise-queue'; + +PromiseQueue.configure(Promise); + +const queue1 = new PromiseQueue(); +const queue2 = new PromiseQueue(1, 1, {onEmpty: () => null}); + +const queuedPromise: Promise = queue1.add(() => Promise.resolve(123)); + +const running: number = queue1.getPendingLength(); +const inQueue: number = queue1.getQueueLength(); diff --git a/types/promise-queue/tsconfig.json b/types/promise-queue/tsconfig.json new file mode 100644 index 0000000000..3487f5aa3e --- /dev/null +++ b/types/promise-queue/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "promise-queue-tests.ts" + ] +} diff --git a/types/promise-queue/tslint.json b/types/promise-queue/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promise-queue/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/prosemirror-model/index.d.ts b/types/prosemirror-model/index.d.ts index 47741b200e..153358e3c6 100644 --- a/types/prosemirror-model/index.d.ts +++ b/types/prosemirror-model/index.d.ts @@ -832,7 +832,7 @@ export class ResolvedPos { * its parent node or its parent node isn't a textblock (in which * case no marks should be preserved). */ - marksAcross(): Mark[] | null | void; + marksAcross($end: ResolvedPos): Mark[] | null | void; /** * The depth up to which this position and the given (non-resolved) * position share the same parent nodes. diff --git a/types/pty.js/index.d.ts b/types/pty.js/index.d.ts index 5a58f4b9fb..88c2615a82 100644 --- a/types/pty.js/index.d.ts +++ b/types/pty.js/index.d.ts @@ -18,10 +18,9 @@ interface TerminalOptions { gid?: number; } -import stream = require('stream'); import net = require('net'); -export declare class Terminal implements stream.Stream { +export declare class Terminal { /** Read-only name of the terminal. */ name: string; /** Read-only number of columns in the terminal. */ @@ -69,9 +68,9 @@ export declare class Terminal implements stream.Stream { resume(): void; setEncoding(encoding: string): void; /** - * Closes the master end of the pseudo-terminal, and attempts to kill the spawned process - * associated with the slave end of the pseudo-terminal (but only if [[pid]] is not null). - */ + * Closes the master end of the pseudo-terminal, and attempts to kill the spawned process + * associated with the slave end of the pseudo-terminal (but only if [[pid]] is not null). + */ destroy(): void; // NodeJS Stream interface @@ -85,21 +84,15 @@ export declare class Terminal implements stream.Stream { once(event: string, listener: Function): this; removeListener(event: string, listener: Function): this; removeAllListeners(event?: string): this; - // NOTE: this method is not actually defined in pty.js - setMaxListeners(n: number): this; - getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; eventNames(): string[]; } /** * Creates a new pseudo-terminal, spawns a child process, and associates it with the slave -* end of the pseudo-terminal. -*/ + * end of the pseudo-terminal. + */ export declare function createTerminal(file?: string, args?: string[], opt?: TerminalOptions): Terminal; /** Alias for [[createTerminal]]. */ export declare function fork(file?: string, args?: string[], opt?: TerminalOptions): Terminal; diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 3ad70755a0..8337acfbe4 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -1,12 +1,22 @@ // Type definitions for pubnub 4.0 // Project: https://github.com/pubnub/javascript -// Definitions by: bitbankinc , rollymaduk +// Definitions by: bitbankinc , rollymaduk , vitosamson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration declare class Pubnub { constructor(config: Pubnub.PubnubConfig); + static CATEGORIES: Pubnub.Categories; + + static OPERATIONS: Pubnub.Operations; + + static generateUUID(): string; + + setUUID(uuid: string): void; + + getUUID(): string; + setAuthKey(authKey: string): void; setFilterExpression(filterExpression: string): void; @@ -15,7 +25,7 @@ declare class Pubnub { publish( params: Pubnub.PublishParameters, - callback: (status: any, response: Pubnub.PublishResponse) => void + callback: (status: Pubnub.PublishStatus, response: Pubnub.PublishResponse) => void ): void; publish( @@ -24,7 +34,7 @@ declare class Pubnub { fire( params: Pubnub.FireParameters, - callback: (status: any, response: Pubnub.PublishResponse) => void + callback: (status: Pubnub.PublishStatus, response: Pubnub.PublishResponse) => void ): void; fire( @@ -45,7 +55,7 @@ declare class Pubnub { hereNow( params: Pubnub.HereNowParameters, - callback: (status: any, response: Pubnub.HereNowResponse) => void + callback: (status: Pubnub.HereNowStatus, response: Pubnub.HereNowResponse) => void ): void; hereNow( @@ -53,9 +63,31 @@ declare class Pubnub { ): Promise; whereNow( - params: {uuid: string}, + params: Pubnub.WhereNowParameters, callback: (status: Pubnub.WhereNowStatus, response: Pubnub.WhereNowResponse) => void ): void; + + whereNow( + params: Pubnub.WhereNowParameters + ): Promise; + + getState( + params: Pubnub.GetStateParameters, + callback: (status: Pubnub.GetStateStatus, state: Pubnub.GetStateResponse) => void + ): void; + + getState( + params: Pubnub.GetStateParameters + ): Promise; + + setState( + params: Pubnub.SetStateParameters, + callback: (status: Pubnub.SetStateStatus, state: Pubnub.SetStateResponse) => void + ): void; + + setState( + params: Pubnub.SetStateParameters + ): Promise; } declare namespace Pubnub { @@ -83,15 +115,30 @@ declare namespace Pubnub { secretKey?: string; } - interface PubnubData { - actualChannel: string; + interface MessageEvent { channel: string; + subscription: string; + timetoken: string; message: any; + publisher: string; + + /** + * @deprecated + */ + actualChannel: string; + + /** + * @deprecated + */ + subscribedChannel: string; } + // PubnubData was renamed to MessageEvent, keep old name for backwards compatibility + type PubnubData = MessageEvent; + interface StatusEvent { - category: string; - operation: string; + category: string; // see Pubnub.Categories + operation: string; // see Pubnub.Operations affectedChannels: string[]; subscribedChannels: string[]; affectedChannelGroups: string[]; @@ -99,6 +146,26 @@ declare namespace Pubnub { currentTimetoken: number | string; } + interface PresenceEvent { + action: 'join' | 'leave' | 'state-change' | 'timeout'; + channel: string; + occupancy: number; + state?: any; + subscription: string; + timestamp: number; + timetoken: string; + uuid: string; + + /** + * @deprecated + */ + actualChannel: string; + /** + * @deprecated + */ + subscribedChannel: string; + } + // publish interface PublishParameters { message: any; @@ -113,6 +180,13 @@ declare namespace Pubnub { timetoken: number; } + interface PublishStatus { + operation: string; // see Pubnub.Operations + category: string; // see Pubnub.Categories; + error: boolean; + errorData: Error; + } + // fire interface FireParameters { message: any; @@ -137,9 +211,9 @@ declare namespace Pubnub { // addListener interface ListenerParameters { - status?: (statusEvent: StatusEvent) => void; - message?: (data: PubnubData) => void; - presence?: (presenceEvent: any) => void; + status?(statusEvent: StatusEvent): void; + message?(messageEvent: MessageEvent): void; + presence?(presenceEvent: PresenceEvent): void; } // hereNow @@ -153,10 +227,29 @@ declare namespace Pubnub { interface HereNowResponse { totalChannels: number; totalOccupancy: number; - channels: {[channel: string]: any}; + channels: { + [channel: string]: { + name: string; + occupancy: number; + occupants: Array<{ + uuid: string; + state?: any; + }>; + }; + }; + } + + interface HereNowStatus { + error: boolean; + operation: string; // see Pubnub.Operations; + statusCode: number; } // whereNow + interface WhereNowParameters { + uuid?: string; + } + interface WhereNowStatus { error: boolean; operation: string; @@ -174,12 +267,71 @@ declare namespace Pubnub { state?: any; } + interface SetStateStatus { + error: boolean; + operation: string; + statusCode: number; + } + + interface SetStateResponse { + state: any; + } + // getState interface GetStateParameters { uuid?: string; channels?: string[]; channelGroups?: string[]; } + + interface GetStateStatus { + error: boolean; + operation: string; + statusCode: number; + } + + interface GetStateResponse { + channels: { + [channel: string]: any; + }; + } + + interface Categories { + PNNetworkUpCategory: string; + PNNetworkDownCategory: string; + PNNetworkIssuesCategory: string; + PNTimeoutCategory: string; + PNBadRequestCategory: string; + PNAccessDeniedCategory: string; + PNUnknownCategory: string; + PNReconnectedCategory: string; + PNConnectedCategory: string; + PNRequestMessageCountExceededCategory: string; + } + + interface Operations { + PNTimeOperation: string; + PNHistoryOperation: string; + PNDeleteMessagesOperation: string; + PNFetchMessagesOperation: string; + PNSubscribeOperation: string; + PNUnsubscribeOperation: string; + PNPublishOperation: string; + PNPushNotificationEnabledChannelsOperation: string; + PNRemoveAllPushNotificationsOperation: string; + PNWhereNowOperation: string; + PNSetStateOperation: string; + PNHereNowOperation: string; + PNGetStateOperation: string; + PNHeartbeatOperation: string; + PNChannelGroupsOperation: string; + PNRemoveGroupOperation: string; + PNChannelsForGroupOperation: string; + PNAddChannelsToGroupOperation: string; + PNRemoveChannelsFromGroupOperation: string; + PNAccessManagerGrant: string; + PNAccessManagerAudit: string; + } } -export default Pubnub; +export = Pubnub; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 291fc035fe..63bd206cde 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -1,4 +1,4 @@ -import Pubnub from 'pubnub'; +import * as Pubnub from 'pubnub'; const console = { log: (params: any) => {} @@ -36,8 +36,10 @@ pubnub.subscribe({channels: ['channel-1']}); pubnub.addListener({ status: statusEvent => { - if (statusEvent.category === "PNConnectedCategory") { + if (statusEvent.category === Pubnub.CATEGORIES.PNConnectedCategory) { console.log(statusEvent.category); + } else if (statusEvent.operation === Pubnub.OPERATIONS.PNAccessManagerAudit) { + console.log(statusEvent.operation); } }, message: message => { @@ -49,3 +51,38 @@ pubnub.addListener({ }); pubnub.unsubscribe({channels: ['channel-1']}); + +pubnub.unsubscribeAll(); + +pubnub.setUUID(Pubnub.generateUUID()); +const uuid = pubnub.getUUID(); + +pubnub.whereNow({ uuid: '' }, (status, res) => { + if (!status.error) { + console.log(res.channels[0]); + } +}); + +pubnub.whereNow({ uuid: '' }).then(res => { + console.log(res.channels[1]); +}); + +pubnub.getState({ uuid: '' }, (status, res) => { + if (!status.error) { + console.log(res.channels[0]); + } +}); + +pubnub.getState({ uuid: '' }).then(res => { + console.log(res.channels[1]); +}); + +pubnub.setState({ channels: [] }, (status, res) => { + if (!status.error) { + console.log(res.state); + } +}); + +pubnub.setState({ channels: [] }).then(res => { + console.log(res.state); +}); diff --git a/types/quixote/index.d.ts b/types/quixote/index.d.ts index 7bf7ffbc65..2f420b5bec 100644 --- a/types/quixote/index.d.ts +++ b/types/quixote/index.d.ts @@ -74,28 +74,28 @@ interface QElementList { // Element positions and sizes are available on all QElement instances. interface ElementDescriptor { // The top edge of the element - top: PositionDescriptor; + top?: PositionDescriptor; // The right edge of the element - right: PositionDescriptor; + right?: PositionDescriptor; // The bottom edge of the element - bottom: PositionDescriptor; + bottom?: PositionDescriptor; // The left edge of the element - left: PositionDescriptor; + left?: PositionDescriptor; // Horizontal center: midway between the right and left edges. - center: PositionDescriptor; + center?: PositionDescriptor; // Vertical middle: midway between the top and bottom edges. - middle: PositionDescriptor; + middle?: PositionDescriptor; // Width of the element. - width: SizeDescriptor; + width?: SizeDescriptor; // Height of the element. - height: SizeDescriptor; + height?: SizeDescriptor; } // Viewport positions and sizes are available on QFrame.viewport() @@ -230,4 +230,4 @@ declare module "quixote" { } export = Quixote; -} \ No newline at end of file +} diff --git a/types/rc-tree/index.d.ts b/types/rc-tree/index.d.ts index 8091b2edd5..4dc789824d 100644 --- a/types/rc-tree/index.d.ts +++ b/types/rc-tree/index.d.ts @@ -58,6 +58,24 @@ export interface SelectData { event: "select"; } +export interface OnDragStartData { + event: Event; + node: TreeNode; +} + +export interface OnDragEnterData { + event: Event; + node: TreeNode; + expandedKeys: string[]; +} + +export interface OnDropData { + event: Event; + node: TreeNode; + dragNode: TreeNode; + dragNodesKeys: string[]; +} + export interface TreeProps extends Props { /** * additional css class of root dom node @@ -149,6 +167,18 @@ export interface TreeProps extends Props { * whether can drag treeNode. */ draggable?: boolean; + /** + * event on drag start + */ + onDragStart?: (props: OnDragStartData) => void; + /** + * event on drag enter + */ + onDragEnter?: (props: OnDragEnterData) => void; + /** + * event on drag drop + */ + onDrop?: (props: OnDropData) => void; } export default class Tree extends Component { } diff --git a/types/rc-tree/rc-tree-tests.tsx b/types/rc-tree/rc-tree-tests.tsx index c57866284f..571465978d 100644 --- a/types/rc-tree/rc-tree-tests.tsx +++ b/types/rc-tree/rc-tree-tests.tsx @@ -44,6 +44,18 @@ export class Demo extends React.Component { console.log('onCheck', checkedKeys, info); } + onDragStart(params: {event: Event, node: TreeNode}) { + console.log('onDragStart', params.event, params.node); + } + + OnDragEnterData(params: {event: Event, node: TreeNode, expandedKeys: string[]}) { + console.log('OnDragEnterData', params.event, params.node, params.expandedKeys); + } + + OnDropData(params: {event: Event, node: TreeNode, dragNode: TreeNode, dragNodesKeys: string[]}) { + console.log('OnDropData', params.event, params.node, params.dragNode, params.dragNodesKeys); + } + onEdit() { setTimeout(() => { console.log('current key: '); @@ -73,6 +85,8 @@ export class Demo extends React.Component { defaultSelectedKeys={this.state.defaultSelectedKeys} defaultCheckedKeys={this.state.defaultCheckedKeys} onSelect={this.onSelect} onCheck={this.onCheck} + onDragStart={this.onDragStart} onDragEnter={this.OnDragEnterData} + onDrop={this.OnDropData} > diff --git a/types/react-bootstrap/lib/DropdownButton.d.ts b/types/react-bootstrap/lib/DropdownButton.d.ts index e2626e2bb7..b1addd7ace 100644 --- a/types/react-bootstrap/lib/DropdownButton.d.ts +++ b/types/react-bootstrap/lib/DropdownButton.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Sizes } from 'react-bootstrap'; +import { Sizes, Omit } from 'react-bootstrap'; import { DropdownBaseProps } from './Dropdown'; declare namespace DropdownButton { @@ -13,7 +13,7 @@ declare namespace DropdownButton { title: React.ReactNode; } - export type DropdownButtonProps = DropdownButtonBaseProps & React.HTMLProps; + export type DropdownButtonProps = DropdownButtonBaseProps & Omit, 'title'>; } declare class DropdownButton extends React.Component { } diff --git a/types/react-data-grid/index.d.ts b/types/react-data-grid/index.d.ts index 3e79703242..f712b43e1b 100644 --- a/types/react-data-grid/index.d.ts +++ b/types/react-data-grid/index.d.ts @@ -219,6 +219,22 @@ declare namespace AdazzleReactDataGrid { * @param columnKey the column key that we are looking to pull values from */ getValidFilterValues?: (columnKey: string) => Array + + getCellActions?: (column: Column, row: object) => (ActionButton | ActionMenu)[] + } + + type ActionButton = { + icon: string; + callback: () => void; + } + + type ActionMenu = { + icon: string; + actions: { + icon: string; + text: string; + callback: () => void; + }[]; } /** diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index cb68e8f0b2..60309b7f20 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker 1.0 +// Type definitions for react-datepicker 1.1 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -37,6 +37,7 @@ export interface ReactDatePickerProps { highlightDates?: any[]; id?: string; includeDates?: any[]; + includeTimes?: any[]; inline?: boolean; isClearable?: boolean; locale?: string; @@ -64,10 +65,13 @@ export interface ReactDatePickerProps { readOnly?: boolean; required?: boolean; scrollableYearDropdown?: boolean; + scrollableMonthYearDropdown?: boolean; selected?: moment.Moment | null; selectsEnd?: boolean; selectsStart?: boolean; + showDisabledMonthNavigation?: boolean; showMonthDropdown?: boolean; + showMonthYearDropdown?: boolean; showWeekNumbers?: boolean; showYearDropdown?: boolean; startDate?: moment.Moment; diff --git a/types/react-dynamic-number/index.d.ts b/types/react-dynamic-number/index.d.ts new file mode 100644 index 0000000000..c1ffdc229d --- /dev/null +++ b/types/react-dynamic-number/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for react-dynamic-number 1.7 +// Project: https://github.com/uhlryk/react-dynamic-number +// Definitions by: Eugene Rodin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +/** + * remove Diff & Omit when in will be placed in TS from scratch + */ +export type Diff = ({[P in T]: P} & {[P in U]: never} & {[x: string]: never})[T]; +export type Omit = {[P in Diff]: T[P]}; + +export type BaseInputProps = Partial< + Omit< + React.DetailedHTMLProps, HTMLInputElement>, + 'ref' | 'value' | 'onChange' | 'placeholder' + > +>; + +export interface DynamicNumberProps extends BaseInputProps { + value?: number | ''; + separator?: '.' | ','; + thousand?: boolean | ' '; + integer?: number; + fraction?: number; + positive?: boolean; + negative?: boolean; + placeholder?: string; + onChange?: (event: React.ChangeEvent, modelValue: number, viewValue: string) => void; +} + +export default class DynamicNumber extends React.Component {} diff --git a/types/react-dynamic-number/react-dynamic-number-tests.tsx b/types/react-dynamic-number/react-dynamic-number-tests.tsx new file mode 100644 index 0000000000..0dd947b6c7 --- /dev/null +++ b/types/react-dynamic-number/react-dynamic-number-tests.tsx @@ -0,0 +1,16 @@ +import * as React from 'react'; +import DynamicNumber from 'react-dynamic-number'; + +export class Test extends React.Component { + render() { + return ( + + ); + } +} diff --git a/types/react-dynamic-number/tsconfig.json b/types/react-dynamic-number/tsconfig.json new file mode 100644 index 0000000000..ad1a3aee65 --- /dev/null +++ b/types/react-dynamic-number/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "react-dynamic-number-tests.tsx"] +} diff --git a/types/react-dynamic-number/tslint.json b/types/react-dynamic-number/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-dynamic-number/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 7fc19e41ab..383fdef681 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -7,6 +7,7 @@ // Karol Janyst , // Brian Houser , // Krister Kari +// Martin Raedlinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -189,6 +190,7 @@ declare namespace ReactIntl { defaultLocale?: string; defaultFormats?: any; textComponent?: any; + initialNow?: any; } } diff --git a/types/react-native-material-ui/index.d.ts b/types/react-native-material-ui/index.d.ts index 0168f557bc..f3147eecf7 100644 --- a/types/react-native-material-ui/index.d.ts +++ b/types/react-native-material-ui/index.d.ts @@ -432,6 +432,12 @@ export interface ToolBarRightElement { menu?: {icon: string, labels: string[]}; } +export interface RightElementPressEvent { + action: string; + index: number; + result?: any; +} + export interface ToolbarProps { isSearchActive?: boolean; size?: number; @@ -443,7 +449,7 @@ export interface ToolbarProps { searchable?: Searchable; onPress?(): void; onLeftElementPress?(): void; - onRightElementPress?(): void; + onRightElementPress?(e: RightElementPressEvent): void; } /** diff --git a/types/react-native-navigation/index.d.ts b/types/react-native-navigation/index.d.ts new file mode 100644 index 0000000000..893a904f73 --- /dev/null +++ b/types/react-native-navigation/index.d.ts @@ -0,0 +1,270 @@ +// Type definitions for react-native-navigation 1.1 +// Project: https://github.com/wix/react-native-navigation +// Definitions by: Egor Shulga +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from 'react'; + +export namespace Navigation { + function registerComponent(screenID: string, generator: () => React.ComponentType, store?: any, provider?: any): void; + function startTabBasedApp(params: TabBasedApp): void; + function startSingleScreenApp(params: SingleScreenApp): void; + function showModal(params: ModalScreen): void; + function dismissModal(params?: { animationType?: 'none' | 'slide-down' }): void; + function dismissAllModals(params?: { animationType?: 'none' | 'slide-down' }): void; + function showLightBox(params?: LightBox): void; + function dismissLightBox(): void; + function handleDeepLink(params?: { link: string; payload?: string; }): void; + function registerScreen(screenId: string, generator: () => React.ComponentType): void; + function getCurrentlyVisibleScreenId(): Promise; +} + +export interface TabBasedApp { + tabs: TabScreen[]; + tabsStyle?: { + tabBarButtonColor?: string; + tabBarSelectedButtonColor?: string; + tabBarBackgroundColor?: string; + initialTabIndex?: number; + }; + appStyle?: { + orientation?: 'auto' | 'landscape' | 'portrait'; + bottomTabBadgeTextColor?: string; + bottomTabBadgeBackgroundColor?: string; + backButtonImage?: any; + hideBackButtonTitle?: boolean; + }; + drawer?: Drawer; + passProps?: object; + animationType?: 'none' | 'slide-down' | 'fade'; +} + +export interface TabScreen { + label?: string; + screen: string; + icon?: any; + selectedIcon?: any; + title?: string; + navigatorStyle?: NavigatorStyle; + navigatorButtons?: NavigatorButtons; +} + +export interface SingleScreenApp { + screen: Screen; + drawer?: Drawer; + passProps?: object; + animationType?: 'none' | 'slide-down' | 'fade'; +} + +export interface Screen { + screen: string; + title?: string; + navigatorStyle?: NavigatorStyle; + navigatorButtons?: NavigatorButtons; +} + +export interface ModalScreen extends Screen { + passProps?: object; + animationType?: 'slide-up' | 'none'; +} + +export interface ResetScreen extends Screen { + passProps?: object; + animated?: boolean; + animationType?: 'fade' | 'slide-horizontal'; +} + +export interface PushedScreen extends ResetScreen { + titleImage?: any; + backButtonTitle?: string; + backButtonHidden?: boolean; + previewView?: React.Component | number; + previewHeight?: number; + previewCommit?: boolean; + previewActions?: Action[]; +} + +export interface Action { + id: string; + title: string; + style?: 'selected' | 'destructive'; + actions: Action[]; +} + +export interface LightBox { + screen: string; + passProps?: object; + style?: { + backgroundBlur?: 'dark' | 'light' | 'xlight' | 'none'; + backgroundColor?: string; + }; + adjustSoftInput?: 'nothing' | 'pan' | 'resize' | 'unspecified'; +} + +export interface Navigator { + push(params: PushedScreen): void; + pop(params?: { animated?: boolean; animationType?: 'fade' | 'slide-horizontal'; }): void; + popToRoot(params?: { animated?: boolean; animationType?: 'fade' | 'slide-horizontal'; }): void; + resetTo(params: PushedScreen): void; + showModal(params: ModalScreen): void; + dismissModal(params?: { animationType?: 'none' | 'slide-down' }): void; + dismissAllModals(params?: { animationType?: 'none' | 'slide-down' }): void; + showLightBox(params: LightBox): void; + dismissLightBox(): void; + showInAppNotification(params?: { screen: string; passProps?: object; autoDismissTimerSec?: number }): void; + handleDeepLink(params: { link: string }): void; + setButtons(params: NavigatorButtons & { animated?: boolean }): void; + setTitle(params: { title: string }): void; + setSubTitle(params: { subtitle: string }): void; + toggleDrawer(params: { side: 'left' | 'right'; animated?: boolean; to?: 'open' | 'closed' }): void; + setDrawerEnabled(params: { side: 'left' | 'right'; enabled: boolean }): void; + toggleTabs(params: { to: 'hidden' | 'shown'; animated?: boolean }): void; + setTabBadge(params?: { tabIndex?: number; badge?: number; badgeColor?: string; }): void; + setTabButton(params?: { tabIndex?: number; icon?: any; selectedIcon?: any; label?: string; }): void; + switchToTab(params?: { tabIndex?: number }): void; + toggleNavBar(params: { to: 'hidden' | 'shown'; animated?: boolean }): void; + setOnNavigatorEvent(callback: (event: { id: string }) => void): void; + addOnNavigatorEvent(callback: (event: { id: string }) => void): () => void; + screenIsCurrentlyVisible(): Promise; + setStyle(params: NavigatorStyle): void; +} + +export class ScreenVisibilityListener { + constructor(params: ScreenVisibilityListenerParams); + register(): void; + unregister(): void; +} + +export interface ScreenVisibilityListenerParams { + willAppear?: (params: ListenerParams) => void; + didAppear?: (params: ListenerParams) => void; + willDisappear?: (params: ListenerParams) => void; + didDisappear?: (params: ListenerParams) => void; +} + +export interface ListenerParams { + screen: string; + startTime: number; + endTime: number; + commandType: string; +} + +export type NavigationComponentProps

= + P & { + navigator: Navigator; + }; + +export interface NavigatorStyle { + navBarTextColor?: string; + navBarTextFontSize?: number; + navBarTextFontFamily?: string; + navBarBackgroundColor?: string; + navBarCustomView?: string; + navBarComponentAlignment?: 'center' | 'fill'; + navBarCustomViewInitialProps?: object; + navBarButtonColor?: string; + topBarElevationShadowEnabled?: boolean; + navBarHidden?: boolean; + navBarHideOnScroll?: boolean; + navBarTranslucent?: boolean; + navBarTransparent?: boolean; + navBarNoBorder?: boolean; + drawUnderNavBar?: boolean; + drawUnderTabBar?: boolean; + navBarBlur?: boolean; + tabBarHidden?: boolean; + statusBarHidden?: boolean; + statusBarTextColorScheme?: string; + navBarSubtitleColor?: string; + navBarSubtitleFontFamily?: string; + navBarSubtitleFontSize?: number; + screenBackgroundColor?: string; + orientation?: 'auto ' | 'landscape' | 'portrait'; + disabledButtonColor?: string; + // iOS only + statusBarTextColorSchemeSingleScreen?: string; + statusBarHideWithNavBar?: boolean; + statusBarBlur?: boolean; + disabledBackGesture?: boolean; + disabledSimultaneousGesture?: boolean; + screenBackgroundImageName?: string; + rootBackgroundImageName?: string; + navBarButtonFontSize?: number; + navBarButtonFontWeight?: string | number; + navBarLeftButtonFontSize?: number; + navBarLeftButtonColor?: string; + navBarLeftButtonFontWeight?: string | number; + navBarRightButtonFontSize?: number; + navBarRightButtonColor?: string; + navBarRightButtonFontWeight?: string | number; + topBarShadowColor?: string; + topBarShadowOpacity?: number; + topBarShadowOffset?: number; + topBarShadowRadius?: number; + preferredContentSize?: { width: number, height: number }; + modalPresentationStyle?: 'formSheet' | 'pageSheet' | 'overFullScreen' | 'overCurrentContext' | 'fullScreen'; + largeTitle?: boolean; + // Android only + navigationBarColor?: string; + navBarTitleTextCentered?: boolean; + navBarButtonFontFamily?: string; + statusBarColor?: string; + drawUnderStatusBar?: boolean; + collapsingToolBarImage?: object; + collapsingToolBarCollapsedColor?: string; + navBarTextFontBold?: boolean; + navBarHeight?: number; + navBarTopPadding?: number; + topTabsHeight?: number; + topBarBorderColor?: string; + topBarBorderWidth?: number; +} + +export interface NavigatorButtons { + leftButtons?: NavigatorButton[]; + rightButtons?: NavigatorButton[]; +} + +export type IdAndroid = 'back' | 'cancel' | 'accept' | 'sideMenu'; + +export type SystemItemIOS = 'done' | 'cancel' | 'edit' | 'save' | 'add' | + 'flexibleSpace' | 'fixedSpace' | 'compose' | 'reply' | 'action' | 'organize' | + 'bookmarks' | 'search' | 'refresh' | 'stop' | 'camera' | 'trash' | 'play' | + 'pause' | 'rewind' | 'fastForward' | 'undo' | 'redo'; + +export interface NavigatorButton { + id: string | IdAndroid; + title?: string; + icon?: any; + component?: string; + passProps?: object; + testID?: string; + disabled?: boolean; + disableIconTint?: boolean; + buttonColor?: string; + buttonFontSize?: number; + buttonFontWeight?: string | number; + systemItem?: SystemItemIOS; +} + +export interface FABAndroid { + collapsedId?: string; + collapsedIcon?: any; + collapsedIconColor?: string; + expendedId?: string; + expendedIcon?: any; + expendedIconColor?: string; + backgroundColor?: string; + actions?: NavigatorButton[]; +} + +export interface Drawer { + left?: { + screen: string; + }; + right?: { + screen: string; + }; + disableOpenGesture?: boolean; +} diff --git a/types/react-native-navigation/react-native-navigation-tests.tsx b/types/react-native-navigation/react-native-navigation-tests.tsx new file mode 100644 index 0000000000..292b0fb375 --- /dev/null +++ b/types/react-native-navigation/react-native-navigation-tests.tsx @@ -0,0 +1,66 @@ +import * as React from 'react'; +import { Text, View } from 'react-native'; +import { Navigation, NavigationComponentProps, NavigatorStyle, NavigatorButtons } from 'react-native-navigation'; + +class Screen1 extends React.Component> { + static navigatorButtons: NavigatorButtons = { + leftButtons: [{ + id: 'sideMenu' + }] + }; + + componentDidMount() { + this.props.navigator.push({ screen: 'example.Screen2' }); + } + + render() { + return ( + + Screen 1 + + ); + } +} + +class Screen2 extends React.Component { + static navigatorStyle: NavigatorStyle = { + drawUnderNavBar: true, + navBarTranslucent: true + }; + + componentDidMount() { + this.props.navigator.resetTo({ screen: 'example.Screen1' }); + } + + render() { + return ( + + Screen 2 + + ); + } +} + +const Drawer = (props: NavigationComponentProps) => { + return ( + + Drawer + + ); +}; + +Navigation.registerComponent('example.Screen1', () => Screen1); +Navigation.registerComponent('example.Screen2', () => Screen2); +Navigation.registerComponent('example.Drawer', () => Drawer); + +Navigation.startSingleScreenApp({ + screen: { + screen: 'example.Screen1', + title: 'Screen 1', + }, + drawer: { + left: { + screen: 'example.Drawer', + } + } +}); diff --git a/types/react-native-navigation/tsconfig.json b/types/react-native-navigation/tsconfig.json new file mode 100644 index 0000000000..715f1f9e62 --- /dev/null +++ b/types/react-native-navigation/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-navigation-tests.tsx" + ] +} diff --git a/types/react-native-navigation/tslint.json b/types/react-native-navigation/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-navigation/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 492287a754..ca5a375e74 100644 --- a/types/react-native-tab-view/index.d.ts +++ b/types/react-native-tab-view/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -import { PureComponent, ReactNode } from 'react' +import { PureComponent, ReactNode, ComponentType } from 'react' import { Animated, StyleProp, @@ -233,5 +233,5 @@ export class TabBar extends PureComponent< > {} export function SceneMap(scenes: { - [key: string]: (props: any) => ReactNode + [key: string]: ComponentType }): (props: { route: Route }) => ReactNode diff --git a/types/react-native-tab-view/react-native-tab-view-tests.tsx b/types/react-native-tab-view/react-native-tab-view-tests.tsx index f57952cbc4..97d8c09257 100644 --- a/types/react-native-tab-view/react-native-tab-view-tests.tsx +++ b/types/react-native-tab-view/react-native-tab-view-tests.tsx @@ -1,4 +1,4 @@ -import { PureComponent } from 'react' +import { PureComponent, Component } from 'react' import { View, StyleSheet } from 'react-native' import { TabViewAnimated, @@ -11,9 +11,14 @@ import { const FirstRoute = () => ( ) -const SecondRoute = () => ( - -) + +class SecondRoute extends Component { + render() { + return ( + + ); + } +} class TabViewExample extends PureComponent { state: { index: number; routes: Array } = { diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index b264df6d64..4d9edaa364 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -3,13 +3,36 @@ // Definitions by: HuHuanming // abrahambotros // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import * as React from 'react'; import { ViewProperties } from 'react-native'; +export interface OnLoadData { + canPlayFastForward: boolean; + canPlayReverse: boolean; + canPlaySlowForward: boolean; + canPlaySlowReverse: boolean; + canStepBackward: boolean; + canStepForward: boolean; + currentTime: number; + duration: number; + naturalSize: { + height: number; + width: number; + orientation: 'horizontal' | 'landscape'; + }; +} + +export interface LoadError { + error: { + '': string; + errorString: string; + }; +} + export interface VideoProperties extends ViewProperties { /* Native only */ src?: any; @@ -46,12 +69,12 @@ export interface VideoProperties extends ViewProperties { currentTime?: number; progressUpdateInterval?: number; onLoadStart?(): void; - onLoad?(): void; + onLoad?(data: OnLoadData): void; onBuffer?(): void; - onError?(): void; + onError?(error: LoadError): void; onProgress?(data: { - currentTime: number, - playableDuration: number, + currentTime: number; + playableDuration: number; }): void; onSeek?(): void; onEnd?(): void; diff --git a/types/react-native-video/react-native-video-tests.tsx b/types/react-native-video/react-native-video-tests.tsx index 5b61336e80..0e7990a04e 100644 --- a/types/react-native-video/react-native-video-tests.tsx +++ b/types/react-native-video/react-native-video-tests.tsx @@ -17,10 +17,40 @@ class VideoTest extends React.Component {

Test
- - ); -} +import { OverlayFade } from './react-overlays-tests-transition'; class TestAffix extends React.Component { render(): JSX.Element { @@ -35,6 +22,32 @@ class TestAffix extends React.Component { } } +class TestOverlay extends React.Component<{}, {open: boolean}> { + target: HTMLElement | null = null; + state = {open: false}; + + render(): JSX.Element { + const { open } = this.state; + + return ( +
+ + + this.target} + transition={OverlayFade} + onHide={() => this.setState({open: false})} + placement="bottom"> +
Popover content
+
+
+ ); + } +} + class TestRootCloseWrapper extends React.Component { handleRootClose = () => { }; render() { diff --git a/types/react-overlays/test/react-overlays-tests-transition.tsx b/types/react-overlays/test/react-overlays-tests-transition.tsx new file mode 100644 index 0000000000..e1e04d7dda --- /dev/null +++ b/types/react-overlays/test/react-overlays-tests-transition.tsx @@ -0,0 +1,12 @@ +import * as React from 'react'; +import { CSSTransition } from 'react-transition-group'; +import { TransitionProps } from 'react-transition-group/Transition'; + +export function OverlayFade(props: TransitionProps): JSX.Element { + return ( + + ); +} diff --git a/types/react-overlays/test/react-overlays-tests.tsx b/types/react-overlays/test/react-overlays-tests.tsx index dde53d76bc..cbb2046fbc 100644 --- a/types/react-overlays/test/react-overlays-tests.tsx +++ b/types/react-overlays/test/react-overlays-tests.tsx @@ -1,7 +1,6 @@ import * as React from "react"; import { - Transition, Portal, Modal, Position, @@ -11,19 +10,7 @@ import { RootCloseWrapper, } from "react-overlays"; -function testTransition() { - return ( - -
Test
-
- ); -} +import { OverlayFade } from './react-overlays-tests-transition'; class TestAffix extends React.Component { render(): JSX.Element { @@ -37,6 +24,32 @@ class TestAffix extends React.Component { } } +class TestOverlay extends React.Component<{}, {open: boolean}> { + target: HTMLElement | null = null; + state = {open: false}; + + render(): JSX.Element { + const { open } = this.state; + + return ( +
+ + + this.target} + transition={OverlayFade} + onHide={() => this.setState({open: false})} + placement="bottom"> +
Popover content
+
+
+ ); + } +} + class TestRootCloseWrapper extends React.Component { handleRootClose = () => { }; render() { diff --git a/types/react-overlays/tsconfig.json b/types/react-overlays/tsconfig.json index 78f037e583..33066cce2e 100644 --- a/types/react-overlays/tsconfig.json +++ b/types/react-overlays/tsconfig.json @@ -21,6 +21,7 @@ "files": [ "index.d.ts", "test/react-overlays-tests.tsx", - "test/react-overlays-tests-individual.tsx" + "test/react-overlays-tests-individual.tsx", + "test/react-overlays-tests-transition.tsx" ] } \ No newline at end of file diff --git a/types/react-router-navigation-core/index.d.ts b/types/react-router-navigation-core/index.d.ts new file mode 100644 index 0000000000..a7ad09748c --- /dev/null +++ b/types/react-router-navigation-core/index.d.ts @@ -0,0 +1,156 @@ +// Type definitions for react-router-navigation-core 1.0 +// Project: https://github.com/LeoLeBras/react-router-navigation#readme +// Definitions by: Kalle Ott +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +// High-level wrappers +import { PureComponent, ReactNode, ComponentClass, ReactElement } from "react"; +import { BackHandler, StyleProp, ViewStyle } from "react-native"; +import { History, Location } from "history"; +import { RouterProps, RouteProps, match } from "react-router"; + +export type Route = { + key: string; + routeName: string; + match?: match; +}; + +export type NavigationState = { + index: number; + routes: Array; +}; + +export type RouteProps = { + component?: ComponentClass; + render?: (props: RouterProps) => ReactNode; + children?: ((props: RouterProps) => ReactNode) | ReactNode; + path?: string; + exact?: boolean; + strict?: boolean; +}; + +export type Card = RouteProps & { + key: string; +}; + +export type CardsRendererProps = { + onNavigateBack: (routeKey?: string) => boolean; + navigationState: NavigationState<{ + path?: string; + params?: object; + }>; + cards: Card[]; +}; + +export type Tab = RouteProps & { + key: string; + onIndexChange?: (index: number) => void; +}; + +export type TabsRendererProps = { + onIndexChange: (index: number) => void; + navigationState: NavigationState<{ + title?: string; + testID?: string; + }>; + loadedTabs: string[]; + tabs: Tab[]; +}; + +export type CardStackProps = { + children?: ReactNode[]; + render: (props: CardsRendererProps) => ReactNode; +}; + +export class CardStack extends PureComponent< + CardStackProps, + { + key: number; + navigationState: NavigationState<{ + path?: string; + params?: object; + }>; + cards: Card[]; + } +> { + unlistenHistory: () => void; + + constructor(props: CardStackProps, context?: any); + + onListenHistory: (history: History, nextHistory: History) => void; + + // Pop to previous scene (n-1) + onNavigateBack: () => boolean; +} + +export type TabStackProps = { + children?: ReactNode[]; + render: (props: TabsRendererProps) => ReactNode; + lazy?: boolean; + forceSync?: boolean; + style?: StyleProp; +}; + +export class TabStack extends PureComponent< + TabStackProps, + { + navigationState: NavigationState<{ + title?: string; + testID?: string; + }>; + tabs: Tab[]; + loadedTabs: string[]; + rootIndex: number; + tabsHistory: { [key: number]: Location[] }; + } +> { + static defaultProps: { + forceSync: false; + }; + + unlistenHistory?: () => void; + + constructor(props: TabStackProps); + + onListenHistory: (history: History, nextHistory: History) => void; + + onIndexChange: (index: number) => void; +} + +// Test if current stack item should be updated +export const shouldUpdate: ( + currentItem: RouteProps, + nextItem: RouteProps, + currentLocation: Location, + nextLocation: Location +) => boolean; + +// Get stack item from a specific route +export const get: (items: Item[], route: Route) => Item; + +// Generate unique key +export const createKey: (route: Route) => string; + +// Get current route from a specific history location +export const getRoute: ( + stack: RouteProps[], + location: Location +) => Route | undefined; + +// Render a subview with props +export const renderSubView: ( + render: (propsA: any, propsB: any) => ReactNode, + additionalProps?: any +) => (ownProps: any) => ReactNode; + +// Build stack with React elements +export const build: ( + children: Array>, + oldBuild?: Item[] +) => Item[]; + +export const runHistoryListenner: ( + history: History, + onListenHistory: () => void +) => () => void; diff --git a/types/react-router-navigation-core/react-router-navigation-core-tests.tsx b/types/react-router-navigation-core/react-router-navigation-core-tests.tsx new file mode 100644 index 0000000000..6d6d048886 --- /dev/null +++ b/types/react-router-navigation-core/react-router-navigation-core-tests.tsx @@ -0,0 +1,49 @@ +import * as React from "react"; +import { View } from "react-native"; +import { TabStack, renderSubView } from "react-router-navigation-core"; +import { TabBarProps, TabProps } from "react-router-navigation"; +import { TabViewAnimated } from "react-native-tab-view"; + +type Props = TabBarProps & { + children?: Array>; + lazy?: boolean; +}; + +type State = { + key: string; +}; + +class BottomNavigation extends React.Component { + state = { key: Math.random().toString(10) }; + + render() { + return ( + { + const ownProps = { ...this.props, ...props }; + return ( + , + ownProps + )} + renderFooter={renderSubView( + sceneProps => , + ownProps + )} + renderScene={renderSubView( + sceneProps => , + ownProps + )} + /> + ); + }} + /> + ); + } +} diff --git a/types/react-router-navigation-core/tsconfig.json b/types/react-router-navigation-core/tsconfig.json new file mode 100644 index 0000000000..b4572aa56c --- /dev/null +++ b/types/react-router-navigation-core/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "module": "commonjs", + "lib": ["es6", "dom"], + "jsx": "react", + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": ["index.d.ts", "react-router-navigation-core-tests.tsx"] +} diff --git a/types/react-router-navigation-core/tslint.json b/types/react-router-navigation-core/tslint.json new file mode 100644 index 0000000000..9771c6e171 --- /dev/null +++ b/types/react-router-navigation-core/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "interface-over-type-literal": false, + "prefer-method-signature": false, + "prefer-declare-function": false, + "semicolon": false + } +} diff --git a/types/react-router-navigation/index.d.ts b/types/react-router-navigation/index.d.ts new file mode 100644 index 0000000000..863158cd3f --- /dev/null +++ b/types/react-router-navigation/index.d.ts @@ -0,0 +1,187 @@ +// Type definitions for react-router-navigation 1.0 +// Project: https://github.com/LeoLeBras/react-router-navigation#readme +// Definitions by: Kalle Ott +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Component, ReactNode, ReactElement, ComponentClass } from "react"; +import { StyleProp, ViewProperties, ViewStyle, TextStyle } from "react-native"; +import { TabViewAnimated, TabViewPagerPan } from "react-native-tab-view"; +import { RouteProps } from "react-router-navigation-core"; +import { + NavigationTransitionProps, + NavigationTransitionSpec +} from "react-navigation"; + +/** + * Navigation + */ + +export type CardProps = RouteProps & NavBarProps; + +// TODO specify exact type when lib changes +export type CardSubViewProps = any; +// NavigationSceneRendererProps & +// CardsRendererProps & +// CardProps + +export interface NavBarProps { + // General + hideNavBar?: boolean; + renderNavBar?: (props: CardSubViewProps) => ReactNode; + navBarStyle?: StyleProp; + // Left button + hideBackButton?: boolean; + backButtonTintColor?: string; + backButtonTitle?: string; + renderLeftButton?: (props: CardSubViewProps) => ReactNode; + // Title + title?: string; + titleStyle?: StyleProp; + renderTitle?: (props: CardSubViewProps) => ReactNode; + // Right button + renderRightButton?: (props: CardSubViewProps) => ReactNode; +} + +export interface NavigationProps extends NavBarProps { + cardStyle?: StyleProp; + configureTransition?: ( + transitionProps: NavigationTransitionProps, + prevTransitionProps?: NavigationTransitionProps + ) => NavigationTransitionSpec; + onTransitionStart?: (...args: any[]) => void; + onTransitionEnd?: (...args: any[]) => void; +} + +export interface Card extends CardProps { + key: string; +} + +/** + * Tabs + */ + +// TODO specify exact type when lib changes +export type TabSubViewProps = any; +// SceneRendererProps & +// TabsRendererProps & +// TabBarProps + +export interface TabBarProps { + hideTabBar?: boolean; + renderTabBar?: (props: TabSubViewProps) => ReactNode; + tabBarStyle?: StyleProp; + tabStyle?: StyleProp; + label?: string; + labelStyle?: StyleProp; + renderLabel?: (props: TabSubViewProps) => ReactNode; + tabTintColor?: string; + tabActiveTintColor?: string; + // only: + renderTabIcon?: (props: TabSubViewProps) => ReactNode; + // only: + tabBarPosition?: "top" | "bottom"; + tabBarIndicatorStyle?: StyleProp; +} + +export interface TabsProps extends TabBarProps { + // only: + initialLayout?: { width?: number; height?: number }; + configureTransition?: ( + transitionProps: NavigationTransitionProps, + prevTransitionProps?: NavigationTransitionProps + ) => NavigationTransitionSpec; +} + +export interface TabProps extends RouteProps, TabBarProps { + onReset?: (props: TabBarProps & RouteProps) => void; + onIndexChange?: (index: number) => void; +} + +export interface Tab extends TabProps { + key: string; +} + +// High-level wrappers +export interface BottomNavigationProps extends TabBarProps { + children?: ReactNode[]; + lazy?: boolean; + style?: StyleProp; +} + +export class BottomNavigation extends Component< + BottomNavigationProps, + { + key: string; + } +> { + static defaultProps: { + lazy: true; + }; + + renderPager: (sceneProps: TabSubViewProps) => ReactNode; + + renderNavigationBar: ( + sceneProps: TabSubViewProps, + props: TabSubViewProps + ) => ReactNode; + + renderSceneView: (sceneProps: TabSubViewProps) => ReactNode; + + renderScene: (sceneProps: TabSubViewProps) => ReactElement; +} + +export function Card(props: CardProps): ReactElement; + +export class NavBar extends Component { + props: CardSubViewProps; + + renderLeftComponent: (sceneProps: CardSubViewProps) => ReactNode; + + renderTitleComponent: (sceneProps: CardSubViewProps) => ReactNode; + + renderRightComponent: (sceneProps: CardSubViewProps) => ReactNode; +} + +export interface NavigationComponentProps extends NavigationProps { + children?: Array>; +} + +export class Navigation extends Component { + props: NavigationComponentProps; + + renderHeader: ( + sceneProps: CardSubViewProps, + props: CardSubViewProps + ) => ReactNode; + + renderSceneComponent: ( + sceneProps: CardSubViewProps + ) => ComponentClass | undefined; +} + +export function Tab(props: TabProps): ReactElement<{}>; + +export interface TabBarComponentProps extends TabBarProps { + children?: Array>; +} + +export class Tabs extends Component< + TabBarComponentProps, + { + key: string; + } +> { + props: TabBarComponentProps; + + renderHeader: (sceneProps: TabSubViewProps) => ReactElement | null; + + renderFooter: (sceneProps: TabSubViewProps) => ReactElement | null; + + renderTabBar: ( + sceneProps: TabSubViewProps, + props: TabSubViewProps + ) => ReactElement | null; + + renderScene: (sceneProps: TabSubViewProps) => ReactElement | null; +} diff --git a/types/react-router-navigation/react-router-navigation-tests.tsx b/types/react-router-navigation/react-router-navigation-tests.tsx new file mode 100644 index 0000000000..a70ad1ef60 --- /dev/null +++ b/types/react-router-navigation/react-router-navigation-tests.tsx @@ -0,0 +1,21 @@ +import * as React from "react"; +import { Text } from "react-native"; +import { NativeRouter, Link } from "react-router-native"; +import { Navigation, Card } from "react-router-navigation"; + +const App = () => ( + + + ( + + Press it + + )} + /> + Hello} /> + + +); diff --git a/types/react-router-navigation/tsconfig.json b/types/react-router-navigation/tsconfig.json new file mode 100644 index 0000000000..d9909d32a6 --- /dev/null +++ b/types/react-router-navigation/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "module": "commonjs", + "lib": ["es6", "dom"], + "jsx": "react", + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": ["index.d.ts", "react-router-navigation-tests.tsx"] +} diff --git a/types/react-router-navigation/tslint.json b/types/react-router-navigation/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-router-navigation/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index cf5efbbb36..1bebd855f1 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -14,6 +14,7 @@ // Jérémy Fauvel // Daniel Roth // Egor Shulga +// Youen Toupin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 diff --git a/types/react-router/test/examples-from-react-router-website/CustomLink.tsx b/types/react-router/test/examples-from-react-router-website/CustomLink.tsx index f3b1fb180e..ef5173e97e 100644 --- a/types/react-router/test/examples-from-react-router-website/CustomLink.tsx +++ b/types/react-router/test/examples-from-react-router-website/CustomLink.tsx @@ -24,9 +24,9 @@ interface OldSchoolMenuLinkProps extends LinkProps { } const OldSchoolMenuLink: React.SFC = ({ label, to, activeOnlyWhenExact }) => ( - ( -
- {match ? '> ' : ''}{label} + ( +
+ {params.match ? '> ' : ''}{label}
)}/> ); diff --git a/types/react-router/v3/lib/IndexRoute.d.ts b/types/react-router/v3/lib/IndexRoute.d.ts index 9c82775c12..1132713b1a 100644 --- a/types/react-router/v3/lib/IndexRoute.d.ts +++ b/types/react-router/v3/lib/IndexRoute.d.ts @@ -12,9 +12,10 @@ import { type ComponentCallback = (err: any, component: RouteComponent) => any; type ComponentsCallback = (err: any, components: RouteComponents) => any; -export interface IndexRouteProps { +export interface IndexRouteProps { component?: RouteComponent; components?: RouteComponents; + props?: Props; getComponent?(nextState: RouterState, callback: ComponentCallback): void; getComponents?(nextState: RouterState, callback: ComponentsCallback): void; onEnter?: EnterHook; diff --git a/types/react-router/v3/lib/Route.d.ts b/types/react-router/v3/lib/Route.d.ts index 15aafebc75..a9ca90b42a 100644 --- a/types/react-router/v3/lib/Route.d.ts +++ b/types/react-router/v3/lib/Route.d.ts @@ -11,7 +11,7 @@ import { } from "react-router"; import { IndexRouteProps } from "react-router/lib/IndexRoute"; -export interface RouteProps extends IndexRouteProps { +export interface RouteProps extends IndexRouteProps { path?: RoutePattern; } @@ -23,7 +23,7 @@ export default Route; type RouteCallback = (err: any, route: PlainRoute) => void; type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; -export interface PlainRoute extends RouteProps { +export interface PlainRoute extends RouteProps { childRoutes?: PlainRoute[]; getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; indexRoute?: PlainRoute; diff --git a/types/react-router/v3/lib/Router.d.ts b/types/react-router/v3/lib/Router.d.ts index 02550026b9..55072a140e 100644 --- a/types/react-router/v3/lib/Router.d.ts +++ b/types/react-router/v3/lib/Router.d.ts @@ -66,10 +66,10 @@ export interface InjectedRouter { isActive: ActiveFunction; } -export interface RouteComponentProps { +export interface RouteComponentProps { location: Location; params: P & R; - route: PlainRoute; + route: PlainRoute; router: InjectedRouter; routes: PlainRoute[]; routeParams: R; diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index 8eade27abc..4487ea4093 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-select 1.1 +// Type definitions for react-select 1.2 // Project: https://github.com/JedWatson/react-select // Definitions by: ESQUIBET Hugo // Gilad Gray @@ -10,6 +10,7 @@ // Onat Yigit Mercan // Ian Johnson // Anton Novik +// David Schkalee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -324,6 +325,18 @@ export interface ReactSelectProps extends React.Props extends React.Props; + /** + * number of options to jump when using page up/down keys + * @default 5 + */ + pageSize?: number; /** * field placeholder, displayed when there's no value * @default "Select..." */ placeholder?: string | JSX.Element; + /** + * whether the selected option is removed from the dropdown on multi selects + * @default true + */ + removeSelected?: boolean; /** * applies HTML5 required attribute when needed * @default false @@ -393,6 +416,11 @@ export interface ReactSelectProps extends React.Props { it("No Results renderer with element", () => { no results} />; }); + + it("onSelectResetsInput", () => { + ; + }); + + it("onCloseResetsInput", () => { + ; + }); + + it("pageSize", () => { + ; + }); + + it("removeSelected", () => { + ; + }); + + it("rtl", () => { + ; + }); }); diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index fed845fd49..1800a9d745 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -167,7 +167,7 @@ export interface TableProps extends PadRowComponent: () => React.ReactNode; /** Server-side callbacks */ - onFetchData: () => void; + onFetchData: (state: any, instance: any) => void; } export interface ControlledStateOverrideProps { @@ -177,6 +177,9 @@ export interface ControlledStateOverrideProps { /** Default: undefined */ pageSize: number | undefined; + /** Default: undefined */ + pages: number | undefined; + /** Default: undefined */ sorting: number; diff --git a/types/react-table/react-table-tests.tsx b/types/react-table/react-table-tests.tsx index a5609394ce..3230e4c5da 100644 --- a/types/react-table/react-table-tests.tsx +++ b/types/react-table/react-table-tests.tsx @@ -93,6 +93,7 @@ const Component = (props: {}) => { PadRowComponent={() =>  } page={undefined} pageSize={undefined} + pages={undefined} sorted={[]} filtered={[]} resized={[]} @@ -106,7 +107,7 @@ const Component = (props: {}) => { indexKey='_index' groupedByPivotKey='_groupedByPivot' className='' - onFetchData={() => null} + onFetchData={(state, instance) => null} style={{}} column={{ Cell: undefined, diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 42abd8d45c..83ab445356 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -193,37 +193,37 @@ declare namespace React { // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" function createElement( type: "input", - props?: InputHTMLAttributes & ClassAttributes, + props?: InputHTMLAttributes & ClassAttributes | null, ...children: ReactNode[]): DetailedReactHTMLElement, HTMLInputElement>; function createElement

, T extends HTMLElement>( type: keyof ReactHTML, - props?: ClassAttributes & P, + props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; function createElement

, T extends SVGElement>( type: keyof ReactSVG, - props?: ClassAttributes & P, + props?: ClassAttributes & P | null, ...children: ReactNode[]): ReactSVGElement; function createElement

, T extends Element>( type: string, - props?: ClassAttributes & P, + props?: ClassAttributes & P | null, ...children: ReactNode[]): DOMElement; // Custom components function createElement

( type: SFC

, - props?: Attributes & P, + props?: Attributes & P | null, ...children: ReactNode[]): SFCElement

; function createElement

( type: ClassType, ClassicComponentClass

>, - props?: ClassAttributes> & P, + props?: ClassAttributes> & P | null, ...children: ReactNode[]): CElement>; function createElement, C extends ComponentClass

>( type: ClassType, - props?: ClassAttributes & P, + props?: ClassAttributes & P | null, ...children: ReactNode[]): CElement; function createElement

( type: SFC

| ComponentClass

| string, - props?: Attributes & P, + props?: Attributes & P | null, ...children: ReactNode[]): ReactElement

; // DOM Elements @@ -2498,6 +2498,189 @@ declare namespace React { unselectable?: boolean; } + // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/ + interface HTMLAttributes extends DOMAttributes { + /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ + 'aria-activedescendant'?: string; + /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ + 'aria-atomic'?: boolean | 'false' | 'true'; + /** + * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be + * presented if they are made. + */ + 'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both'; + /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ + 'aria-busy'?: boolean | 'false' | 'true'; + /** + * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. + * @see aria-pressed @see aria-selected. + */ + 'aria-checked'?: boolean | 'false' | 'mixed' | 'true'; + /** + * Defines the total number of columns in a table, grid, or treegrid. + * @see aria-colindex. + */ + 'aria-colcount'?: number; + /** + * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. + * @see aria-colcount @see aria-colspan. + */ + 'aria-colindex'?: number; + /** + * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-colindex @see aria-rowspan. + */ + 'aria-colspan'?: number; + /** Indicates the element that represents the current item within a container or set of related elements. */ + 'aria-current'?: boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time'; + /** + * Identifies the element (or elements) that describes the object. + * @see aria-labelledby + */ + 'aria-describedby'?: string; + /** + * Identifies the element that provides a detailed, extended description for the object. + * @see aria-describedby. + */ + 'aria-details'?: string; + /** + * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. + * @see aria-hidden @see aria-readonly. + */ + 'aria-disabled'?: boolean | 'false' | 'true'; + /** + * Indicates what functions can be performed when a dragged object is released on the drop target. + * @deprecated in ARIA 1.1 + */ + 'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup'; + /** + * Identifies the element that provides an error message for the object. + * @see aria-invalid @see aria-describedby. + */ + 'aria-errormessage'?: string; + /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ + 'aria-expanded'?: boolean | 'false' | 'true'; + /** + * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, + * allows assistive technology to override the general default of reading in document source order. + */ + 'aria-flowto'?: string; + /** + * Indicates an element's "grabbed" state in a drag-and-drop operation. + * @deprecated in ARIA 1.1 + */ + 'aria-grabbed'?: boolean | 'false' | 'true'; + /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ + 'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog'; + /** + * Indicates whether the element is exposed to an accessibility API. + * @see aria-disabled. + */ + 'aria-hidden'?: boolean | 'false' | 'true'; + /** + * Indicates the entered value does not conform to the format expected by the application. + * @see aria-errormessage. + */ + 'aria-invalid'?: boolean | 'false' | 'true' | 'grammar' | 'spelling'; + /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ + 'aria-keyshortcuts'?: string; + /** + * Defines a string value that labels the current element. + * @see aria-labelledby. + */ + 'aria-label'?: string; + /** + * Identifies the element (or elements) that labels the current element. + * @see aria-describedby. + */ + 'aria-labelledby'?: string; + /** Defines the hierarchical level of an element within a structure. */ + 'aria-level'?: number; + /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ + 'aria-live'?: 'off' | 'assertive' | 'polite'; + /** Indicates whether an element is modal when displayed. */ + 'aria-modal'?: boolean | 'false' | 'true'; + /** Indicates whether a text box accepts multiple lines of input or only a single line. */ + 'aria-multiline'?: boolean | 'false' | 'true'; + /** Indicates that the user may select more than one item from the current selectable descendants. */ + 'aria-multiselectable'?: boolean | 'false' | 'true'; + /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ + 'aria-orientation'?: 'horizontal' | 'vertical'; + /** + * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship + * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. + * @see aria-controls. + */ + 'aria-owns'?: string; + /** + * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. + * A hint could be a sample value or a brief description of the expected format. + */ + 'aria-placeholder'?: string; + /** + * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-setsize. + */ + 'aria-posinset'?: number; + /** + * Indicates the current "pressed" state of toggle buttons. + * @see aria-checked @see aria-selected. + */ + 'aria-pressed'?: boolean | 'false' | 'mixed' | 'true'; + /** + * Indicates that the element is not editable, but is otherwise operable. + * @see aria-disabled. + */ + 'aria-readonly'?: boolean | 'false' | 'true'; + /** + * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. + * @see aria-atomic. + */ + 'aria-relevant'?: 'additions' | 'additions text' | 'all' | 'removals' | 'text'; + /** Indicates that user input is required on the element before a form may be submitted. */ + 'aria-required'?: boolean | 'false' | 'true'; + /** Defines a human-readable, author-localized description for the role of an element. */ + 'aria-roledescription'?: string; + /** + * Defines the total number of rows in a table, grid, or treegrid. + * @see aria-rowindex. + */ + 'aria-rowcount'?: number; + /** + * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. + * @see aria-rowcount @see aria-rowspan. + */ + 'aria-rowindex'?: number; + /** + * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-rowindex @see aria-colspan. + */ + 'aria-rowspan'?: number; + /** + * Indicates the current "selected" state of various widgets. + * @see aria-checked @see aria-pressed. + */ + 'aria-selected'?: boolean | 'false' | 'true'; + /** + * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-posinset. + */ + 'aria-setsize'?: number; + /** Indicates if items in a table or grid are sorted in ascending or descending order. */ + 'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other'; + /** Defines the maximum allowed value for a range widget. */ + 'aria-valuemax'?: number; + /** Defines the minimum allowed value for a range widget. */ + 'aria-valuemin'?: number; + /** + * Defines the current value for a range widget. + * @see aria-valuetext. + */ + 'aria-valuenow'?: number; + /** Defines the human readable text alternative of aria-valuenow for a range widget. */ + 'aria-valuetext'?: string; + } + interface AllHTMLAttributes extends HTMLAttributes { // Standard HTML Attributes accept?: string; diff --git a/types/react/test/index.ts b/types/react/test/index.ts index 16141fabb4..3e2be1605f 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -141,6 +141,9 @@ const StatelessComponent3: React.SFC = // allows null return props => props.foo ? DOM.div(null, props.foo, props.children) : null; +// allows null as props +const StatelessComponent4: React.SFC = props => null; + // React.createFactory const factory: React.CFactory = React.createFactory(ModernComponent); @@ -160,15 +163,22 @@ const domFactoryElement: React.DOMElement, Element> = // React.createElement const element: React.CElement = React.createElement(ModernComponent, props); const elementNoState: React.CElement = React.createElement(ModernComponentNoState, props); +const elementNullProps: React.CElement<{}, ModernComponentNoPropsAndState> = React.createElement(ModernComponentNoPropsAndState, null); const statelessElement: React.SFCElement = React.createElement(StatelessComponent, props); +const statelessElementNullProps: React.SFCElement = React.createElement(StatelessComponent4, null); const domElement: React.DOMElement, HTMLDivElement> = React.createElement("div"); +const domElementNullProps = React.createElement("div", null); const htmlElement = React.createElement("input", { type: "text" }); +const inputElementNullProps: React.DOMElement, HTMLInputElement> = React.createElement("input", null); const svgElement = React.createElement("svg", { accentHeight: 12 }); +const svgElementNullProps = React.createElement("svg", null); const fragmentElement: React.ReactElement<{}> = React.createElement(React.Fragment, {}, [React.createElement("div"), React.createElement("div")]); +const fragmentElementNullProps: React.ReactElement<{}> = React.createElement(React.Fragment, null, [React.createElement("div"), React.createElement("div")]); const customProps: React.HTMLProps = props; const customDomElement = "my-element"; const nonLiteralElement = React.createElement(customDomElement, customProps); +const customDomElementNullProps = React.createElement(customDomElement, null); // https://github.com/Microsoft/TypeScript/issues/15019 @@ -307,7 +317,11 @@ const htmlAttr: React.HTMLProps = { }, dangerouslySetInnerHTML: { __html: "STRONG" - } + }, + 'aria-atomic': false, + 'aria-checked': 'true', + 'aria-colcount': 7, + 'aria-label': 'test' }; DOM.div(htmlAttr); DOM.span(htmlAttr); diff --git a/types/react/test/tsx.tsx b/types/react/test/tsx.tsx index 38d902c387..bc48add9a4 100644 --- a/types/react/test/tsx.tsx +++ b/types/react/test/tsx.tsx @@ -41,6 +41,16 @@ StatelessComponent2.defaultProps = { foo

; +// WAI-ARIA 1.1 Attributes +
+ bar +
; + interface Props { hello: string; } diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts index 753ae4550e..96c0b3af7e 100644 --- a/types/react/v15/index.d.ts +++ b/types/react/v15/index.d.ts @@ -2448,6 +2448,189 @@ declare namespace React { unselectable?: boolean; } + // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/ + interface HTMLAttributes extends DOMAttributes { + /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ + 'aria-activedescendant'?: string; + /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ + 'aria-atomic'?: boolean | 'false' | 'true'; + /** + * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be + * presented if they are made. + */ + 'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both'; + /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ + 'aria-busy'?: boolean | 'false' | 'true'; + /** + * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. + * @see aria-pressed @see aria-selected. + */ + 'aria-checked'?: boolean | 'false' | 'mixed' | 'true'; + /** + * Defines the total number of columns in a table, grid, or treegrid. + * @see aria-colindex. + */ + 'aria-colcount'?: number; + /** + * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. + * @see aria-colcount @see aria-colspan. + */ + 'aria-colindex'?: number; + /** + * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-colindex @see aria-rowspan. + */ + 'aria-colspan'?: number; + /** Indicates the element that represents the current item within a container or set of related elements. */ + 'aria-current'?: boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time'; + /** + * Identifies the element (or elements) that describes the object. + * @see aria-labelledby + */ + 'aria-describedby'?: string; + /** + * Identifies the element that provides a detailed, extended description for the object. + * @see aria-describedby. + */ + 'aria-details'?: string; + /** + * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. + * @see aria-hidden @see aria-readonly. + */ + 'aria-disabled'?: boolean | 'false' | 'true'; + /** + * Indicates what functions can be performed when a dragged object is released on the drop target. + * @deprecated in ARIA 1.1 + */ + 'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup'; + /** + * Identifies the element that provides an error message for the object. + * @see aria-invalid @see aria-describedby. + */ + 'aria-errormessage'?: string; + /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ + 'aria-expanded'?: boolean | 'false' | 'true'; + /** + * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, + * allows assistive technology to override the general default of reading in document source order. + */ + 'aria-flowto'?: string; + /** + * Indicates an element's "grabbed" state in a drag-and-drop operation. + * @deprecated in ARIA 1.1 + */ + 'aria-grabbed'?: boolean | 'false' | 'true'; + /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ + 'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog'; + /** + * Indicates whether the element is exposed to an accessibility API. + * @see aria-disabled. + */ + 'aria-hidden'?: boolean | 'false' | 'true'; + /** + * Indicates the entered value does not conform to the format expected by the application. + * @see aria-errormessage. + */ + 'aria-invalid'?: boolean | 'false' | 'true' | 'grammar' | 'spelling'; + /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ + 'aria-keyshortcuts'?: string; + /** + * Defines a string value that labels the current element. + * @see aria-labelledby. + */ + 'aria-label'?: string; + /** + * Identifies the element (or elements) that labels the current element. + * @see aria-describedby. + */ + 'aria-labelledby'?: string; + /** Defines the hierarchical level of an element within a structure. */ + 'aria-level'?: number; + /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ + 'aria-live'?: 'off' | 'assertive' | 'polite'; + /** Indicates whether an element is modal when displayed. */ + 'aria-modal'?: boolean | 'false' | 'true'; + /** Indicates whether a text box accepts multiple lines of input or only a single line. */ + 'aria-multiline'?: boolean | 'false' | 'true'; + /** Indicates that the user may select more than one item from the current selectable descendants. */ + 'aria-multiselectable'?: boolean | 'false' | 'true'; + /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ + 'aria-orientation'?: 'horizontal' | 'vertical'; + /** + * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship + * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. + * @see aria-controls. + */ + 'aria-owns'?: string; + /** + * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. + * A hint could be a sample value or a brief description of the expected format. + */ + 'aria-placeholder'?: string; + /** + * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-setsize. + */ + 'aria-posinset'?: number; + /** + * Indicates the current "pressed" state of toggle buttons. + * @see aria-checked @see aria-selected. + */ + 'aria-pressed'?: boolean | 'false' | 'mixed' | 'true'; + /** + * Indicates that the element is not editable, but is otherwise operable. + * @see aria-disabled. + */ + 'aria-readonly'?: boolean | 'false' | 'true'; + /** + * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. + * @see aria-atomic. + */ + 'aria-relevant'?: 'additions' | 'additions text' | 'all' | 'removals' | 'text'; + /** Indicates that user input is required on the element before a form may be submitted. */ + 'aria-required'?: boolean | 'false' | 'true'; + /** Defines a human-readable, author-localized description for the role of an element. */ + 'aria-roledescription'?: string; + /** + * Defines the total number of rows in a table, grid, or treegrid. + * @see aria-rowindex. + */ + 'aria-rowcount'?: number; + /** + * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. + * @see aria-rowcount @see aria-rowspan. + */ + 'aria-rowindex'?: number; + /** + * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-rowindex @see aria-colspan. + */ + 'aria-rowspan'?: number; + /** + * Indicates the current "selected" state of various widgets. + * @see aria-checked @see aria-pressed. + */ + 'aria-selected'?: boolean | 'false' | 'true'; + /** + * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-posinset. + */ + 'aria-setsize'?: number; + /** Indicates if items in a table or grid are sorted in ascending or descending order. */ + 'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other'; + /** Defines the maximum allowed value for a range widget. */ + 'aria-valuemax'?: number; + /** Defines the minimum allowed value for a range widget. */ + 'aria-valuemin'?: number; + /** + * Defines the current value for a range widget. + * @see aria-valuetext. + */ + 'aria-valuenow'?: number; + /** Defines the human readable text alternative of aria-valuenow for a range widget. */ + 'aria-valuetext'?: string; + } + interface AllHTMLAttributes extends HTMLAttributes { // Standard HTML Attributes accept?: string; diff --git a/types/react/v15/test/index.ts b/types/react/v15/test/index.ts index be6d27b659..b0c358b011 100644 --- a/types/react/v15/test/index.ts +++ b/types/react/v15/test/index.ts @@ -346,7 +346,11 @@ const htmlAttr: React.HTMLProps = { }, dangerouslySetInnerHTML: { __html: "STRONG" - } + }, + 'aria-atomic': false, + 'aria-checked': 'true', + 'aria-colcount': 7, + 'aria-label': 'test' }; React.DOM.div(htmlAttr); React.DOM.span(htmlAttr); diff --git a/types/react/v15/test/tsx.tsx b/types/react/v15/test/tsx.tsx index 8afb75d9a8..289a912a3f 100644 --- a/types/react/v15/test/tsx.tsx +++ b/types/react/v15/test/tsx.tsx @@ -41,6 +41,16 @@ StatelessComponent2.defaultProps = { foo ; +// WAI-ARIA 1.1 Attributes +
+ bar +
; + interface Props { hello: string; } diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index 59bca2df3d..38c55bc08a 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -6,6 +6,7 @@ // Fábio Paiva // FaithForHumans // Kurt Preston +// Kræn Hansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/reactstrap/lib/Input.d.ts b/types/reactstrap/lib/Input.d.ts index f5c5ac1d02..c5827f9a75 100644 --- a/types/reactstrap/lib/Input.d.ts +++ b/types/reactstrap/lib/Input.d.ts @@ -27,15 +27,9 @@ type InputType = | 'time' | 'color'; -// Intermediate interface to "redefine" the type of size to string -// size:number => size:any => size:string -interface Intermediate extends React.InputHTMLAttributes { - size?: any; -} - -export interface InputProps extends Intermediate { +export interface InputProps extends React.InputHTMLAttributes { type?: InputType; - size?: string; + bsSize?: 'lg' | 'sm'; state?: string; valid?: boolean; tag?: React.ReactType; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 2a67844f9f..0f0bf7b81d 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -1381,16 +1381,16 @@ class Example50 extends React.Component { render() { return (
- + - - + + - +
@@ -3247,7 +3247,7 @@ function Example104() { - + ); diff --git a/types/readline-sync/index.d.ts b/types/readline-sync/index.d.ts index 2931f22d90..e3c08c3b52 100644 --- a/types/readline-sync/index.d.ts +++ b/types/readline-sync/index.d.ts @@ -32,6 +32,7 @@ export interface BasicOptions { validate?(path: string): boolean | string; create?: boolean; guide?: boolean; + cancel?: any; } // Basic Functions diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 2b7364c38b..3b9afac937 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -4,6 +4,7 @@ // Raphael Mueller // Roy Xue // Zheyang Song +// Rich Baird // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -773,7 +774,11 @@ export interface Coordinate { export interface TooltipPayload { name: string; value: string | number | Array; - unit: string; + unit?: string; + color?: string; + fill?: string; + dataKey?: string; + formatter?: TooltipFormatter; } export interface TooltipProps extends Animatable { @@ -794,6 +799,7 @@ export interface TooltipProps extends Animatable { payload?: TooltipPayload[]; itemSorter?: ItemSorter; filterNull?: boolean; + useTranslate3d?: boolean; } export class Tooltip extends React.Component { } diff --git a/types/redis/index.d.ts b/types/redis/index.d.ts index db0dd122ba..85dfc05596 100644 --- a/types/redis/index.d.ts +++ b/types/redis/index.d.ts @@ -128,11 +128,14 @@ export interface Commands { */ ping(callback?: Callback): R; ping(message: string, callback?: Callback): R; + PING(callback?: Callback): R; + PING(message: string, callback?: Callback): R; /** * Post a message to a channel. */ publish(channel: string, value: string, cb?: Callback): R; + PUBLISH(channel: string, value: string, cb?: Callback): R; /** * Authenticate to the server. diff --git a/types/request-promise-native/index.d.ts b/types/request-promise-native/index.d.ts index e4fc27a8c2..d13e4c8fd5 100644 --- a/types/request-promise-native/index.d.ts +++ b/types/request-promise-native/index.d.ts @@ -17,11 +17,11 @@ declare namespace requestPromise { interface RequestPromiseOptions extends request.CoreOptions { simple?: boolean; - transform?(body: any, response: http.IncomingMessage, resolveWithFullResponse?: boolean): any; + transform?(body: any, response: request.Response, resolveWithFullResponse?: boolean): any; resolveWithFullResponse?: boolean; } - type FullResponse = request.RequestResponse; + type FullResponse = request.Response; type OptionsWithUri = request.UriOptions & RequestPromiseOptions; type OptionsWithUrl = request.UrlOptions & RequestPromiseOptions; type Options = OptionsWithUri | OptionsWithUrl; diff --git a/types/request-promise/index.d.ts b/types/request-promise/index.d.ts index 8e811a415e..8b2382d049 100644 --- a/types/request-promise/index.d.ts +++ b/types/request-promise/index.d.ts @@ -23,7 +23,7 @@ declare namespace requestPromise { interface RequestPromiseOptions extends request.CoreOptions { simple?: boolean; - transform?(body: any, response: http.IncomingMessage, resolveWithFullResponse?: boolean): any; + transform?(body: any, response: request.Response, resolveWithFullResponse?: boolean): any; transform2xxOnly?: boolean; resolveWithFullResponse?: boolean; } diff --git a/types/request/index.d.ts b/types/request/index.d.ts index c35adefa86..71f41ff794 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for request 2.0 +// Type definitions for request 2.47 // Project: https://github.com/request/request // Definitions by: Carlos Ballesteros Velasco , // bonnici , @@ -14,11 +14,13 @@ /// +import caseless = require('caseless'); import stream = require('stream'); import http = require('http'); import https = require('https'); import fs = require('fs'); import FormData = require('form-data'); +import net = require('net'); import tough = require('tough-cookie'); import { Url } from 'url'; @@ -113,7 +115,7 @@ declare namespace request { interface CoreOptions { baseUrl?: string; - callback?: (error: any, response: RequestResponse, body: any) => void; + callback?: RequestCallback; jar?: CookieJar | boolean; formData?: { [key: string]: any }; form?: { [key: string]: any } | string; @@ -177,32 +179,7 @@ declare namespace request { type OptionsWithUrl = UrlOptions & CoreOptions; type Options = OptionsWithUri | OptionsWithUrl; - type RequestCallback = (error: any, response: RequestResponse, body: any) => void; - - type ResponseRequest = CoreOptions & { - uri: Url; - }; - - interface RequestResponse extends http.IncomingMessage { - request: ResponseRequest; - body: any; - timingStart?: number; - timings?: { - socket: number; - lookup: number; - connect: number; - response: number; - end: number; - }; - timingPhases?: { - wait: number; - dns: number; - tcp: number; - firstByte: number; - download: number; - total: number; - }; - } + type RequestCallback = (error: any, response: Response, body: any) => void; interface HttpArchiveRequest { url?: string; @@ -232,32 +209,32 @@ declare namespace request { body: any; } - interface Request extends stream.Stream { + interface Request extends caseless.Httpified, stream.Stream { readable: boolean; writable: boolean; + explicitMethod?: true; - getAgent(): http.Agent; - // start(): void; - // abort(): void; + debug(...args: any[]): void; pipeDest(dest: any): void; - setHeader(name: string, value: string, clobber?: boolean): Request; - setHeaders(headers: Headers): Request; qs(q: object, clobber?: boolean): Request; form(): FormData; form(form: any): Request; multipart(multipart: RequestPart[]): Request; json(val: any): Request; aws(opts: AWSOptions, now?: boolean): Request; + hawk(opts: HawkOptions): void; auth(username: string, password: string, sendImmediately?: boolean, bearer?: string): Request; oauth(oauth: OAuthOptions): Request; jar(jar: CookieJar): Request; on(event: string, listener: (...args: any[]) => void): this; on(event: 'request', listener: (req: http.ClientRequest) => void): this; - on(event: 'response', listener: (resp: http.IncomingMessage) => void): this; + on(event: 'response', listener: (resp: Response) => void): this; on(event: 'data', listener: (data: Buffer | string) => void): this; on(event: 'error', listener: (e: Error) => void): this; - on(event: 'complete', listener: (resp: http.IncomingMessage, body?: string | Buffer) => void): this; + on(event: 'complete', listener: (resp: Response, body?: string | Buffer) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'socket', listener: (src: net.Socket) => void): this; write(buffer: Buffer | string, cb?: (err?: Error) => void): boolean; write(str: string, encoding?: string, cb?: (err?: Error) => void): boolean; @@ -269,9 +246,95 @@ declare namespace request { resume(): void; abort(): void; destroy(): void; - toJSON(): object; + toJSON(): RequestAsJSON; + + // several of the CoreOptions are copied onto the request instance + host?: string; + port?: number; + followAllRedirects?: boolean; + followOriginalHttpMethod?: boolean; + maxRedirects?: number; + removeRefererHeader?: boolean; + encoding?: string | null; + timeout?: number; + localAddress?: string; + strictSSL?: boolean; + rejectUnauthorized?: boolean; + time?: boolean; + gzip?: boolean; + preambleCRLF?: boolean; + postambleCRLF?: boolean; + withCredentials?: boolean; + key?: Buffer; + cert?: Buffer; + passphrase?: string; + ca?: string | Buffer | string[] | Buffer[]; + har?: HttpArchiveRequest; + + // set in `Request.prototype.init` + headers: Headers; + method: string; + pool: false | { [key: string]: http.Agent | https.Agent }; + dests: stream.Readable[]; + callback?: RequestCallback; + uri: Url & { href: string, pathname: string }; + proxy: null | string | Url; + tunnel: boolean; + setHost: boolean; + path: string; + agent: false | http.Agent | https.Agent; + body: Buffer | Buffer[] | string | string[] | stream.Readable; + timing?: boolean; + src?: stream.Readable; + + // set in `Request.prototype.start` + href: string; + startTime?: number; + startTimeNow?: number; + timings?: { + socket: number; + lookup: number; + connect: number; + response: number; + end: number; + }; + + // set in `Request.prototype.onRequestResponse` + elapsedTime?: number; + response?: Response; } + interface Response extends http.IncomingMessage { + statusCode: number; + statusMessage: string; + request: Request; + body: any; // Buffer, string, stream.Readable, or a plain object if `json` was truthy + caseless: caseless.Caseless; // case-insensitive access to headers + toJSON(): ResponseAsJSON; + + timingStart?: number; + elapsedTime?: number; + timings?: { + socket: number; + lookup: number; + connect: number; + response: number; + end: number; + }; + timingPhases?: { + wait: number; + dns: number; + tcp: number; + firstByte: number; + download: number; + total: number; + }; + } + + // aliases for backwards compatibility + type ResponseRequest = Request; + type RequestResponse = Response; + interface Headers { [key: string]: any; } @@ -305,6 +368,19 @@ declare namespace request { bucket?: string; } + interface RequestAsJSON { + uri: Url; + method: string; + headers: Headers; + } + + interface ResponseAsJSON { + statusCode: number; + body: any; + headers: Headers; + request: RequestAsJSON; + } + type Cookie = tough.Cookie; interface CookieJar { diff --git a/types/request/request-tests.ts b/types/request/request-tests.ts index bffb522876..5f56f3bc9d 100644 --- a/types/request/request-tests.ts +++ b/types/request/request-tests.ts @@ -7,23 +7,23 @@ import request = require('request'); import stream = require('stream'); import urlModule = require('url'); -const value: any = 'value'; +let value: any; let str: string; let strOrUndef: string | undefined; let strOrTrueOrUndef: string | true | undefined; const buffer: NodeBuffer = new Buffer('foo'); -const num = 0; +let num = 0; let bool: boolean; let date: Date; let obj: object; const dest = 'foo'; const uri = 'foo-bar'; -const headers: request.Headers = {}; +let headers: request.Headers = {}; -let agent: http.Agent; let write: stream.Writable = new stream.Writable(); let req: request.Request = request(uri, function callback() {}); +let res: request.Response; let form: FormData; const bodyArr: request.RequestPart[] = [{ @@ -126,14 +126,14 @@ const opt: request.OptionsWithUri = { opt.uri = str; // --- --- --- --- --- --- --- --- --- --- --- --- +let strOrFalse: string | false; +strOrFalse = req.setHeader(str, str); +strOrFalse = req.setHeader(str, str, bool); +req.setHeader({str}); +strOrFalse = req.hasHeader(str); +strOrUndef = req.getHeader(str); +bool = req.removeHeader(str); -agent = req.getAgent(); -// req.start(); -// req.abort(); -req.pipeDest(dest); -req = req.setHeader(str, str); -req = req.setHeader(str, str, bool); -req = req.setHeaders(headers); req = req.qs(obj); req = req.qs(obj, bool); req = req.form(obj); @@ -147,6 +147,7 @@ req = req.jar(jar); write = req.pipe(write); write = req.pipe(write, value); req.pipe(req); +req.pipeDest(dest); req.write(value); req.end(str); req.end(buffer); @@ -155,6 +156,19 @@ req.resume(); req.abort(); req.destroy(); +strOrUndef = req.host; +str = req.method; +str = req.path; +str = req.href; +str = req.uri.href; +str = req.uri.pathname; +value = req.body; +headers = req.headers; +value = req.headers['foo']; + +if (req.response) { + res = req.response; +} // --- --- --- --- --- --- --- --- --- --- --- --- req = request(uri); @@ -227,8 +241,30 @@ r.post(options); request .get('http://example.com/example.png') -.on('response', (response: any) => { - // check response +.on('response', (response) => { + res = response; + num = response.statusCode; + str = response.statusMessage; + req = response.request; + value = response.body; + strOrUndef = response.caseless.get('foo'); + strOrFalse = response.caseless.has('content-type'); + + if (response.timings) { + num = response.timings.socket; + num = response.timings.lookup; + num = response.timings.connect; + num = response.timings.response; + num = response.timings.end; + } + if (response.timingPhases) { + num = response.timingPhases.wait; + num = response.timingPhases.dns; + num = response.timingPhases.tcp; + num = response.timingPhases.firstByte; + num = response.timingPhases.download; + num = response.timingPhases.total; + } }) .pipe(request.put('http://another.com/another.png')); @@ -247,7 +283,7 @@ request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img request .get('http://google.com/img.png') - .on('response', (response: any) => { + .on('response', (response) => { console.log(response.statusCode); // 200 console.log(response.headers['content-type']); // 'image/png' }) diff --git a/types/screeps/index.d.ts b/types/screeps/index.d.ts index 145c240b39..17155770d5 100644 --- a/types/screeps/index.d.ts +++ b/types/screeps/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Screeps 2.1 +// Type definitions for Screeps 2.2 // Project: https://github.com/screeps/screeps // Definitions by: Marko Sulamägi // Nhan Ho @@ -39,6 +39,7 @@ declare const FIND_MY_CREEPS: 102; declare const FIND_HOSTILE_CREEPS: 103; declare const FIND_SOURCES_ACTIVE: 104; declare const FIND_SOURCES: 105; +/** `FIND_DROPPED_ENERGY` is deprecated the return value is the same as `FIND_DROPPED_RESOURCES` */ declare const FIND_DROPPED_ENERGY: -106; declare const FIND_DROPPED_RESOURCES: 106; declare const FIND_STRUCTURES: 107; @@ -106,6 +107,7 @@ declare const RAMPART_DECAY_AMOUNT: 300; declare const RAMPART_DECAY_TIME: 100; declare const RAMPART_HITS: 1; declare const RAMPART_HITS_MAX: { + [rcl: number]: number 2: 300000, 3: 1000000, 4: 3000000, @@ -128,6 +130,7 @@ declare const WALL_HITS_MAX: 300000000; declare const EXTENSION_HITS: 1000; declare const EXTENSION_ENERGY_CAPACITY: { + [rcl: number]: number 0: 50, 1: 50, 2: 50, @@ -286,6 +289,7 @@ declare const POWER_SPAWN_POWER_CAPACITY: number; declare const POWER_SPAWN_ENERGY_RATIO: number; declare const EXTRACTOR_HITS: number; +declare const EXTRACTOR_COOLDOWN: number; declare const LAB_HITS: number; declare const LAB_MINERAL_CAPACITY: number; @@ -316,17 +320,19 @@ declare const MINERAL_MIN_AMOUNT: Record; declare const MINERAL_RANDOM_FACTOR: number; declare const MINERAL_DENSITY: { - 1: number, - 2: number, - 3: number, - 4: number + [level: number]: number + 1: number, + 2: number, + 3: number, + 4: number }; declare const MINERAL_DENSITY_PROBABILITY: { - 1: number, - 2: number, - 3: number, - 4: number + [level: number]: number + 1: number, + 2: number, + 3: number, + 4: number }; declare const MINERAL_DENSITY_CHANGE: number; @@ -354,12 +360,14 @@ declare const NUKER_GHODIUM_CAPACITY: number; declare const NUKE_LAND_TIME: number; declare const NUKE_RANGE: number; declare const NUKE_DAMAGE: { + [range: number]: number 0: number, 1: number, 4: number }; declare const REACTIONS: { + [resource: string]: {[resource: string]: string} H: { O: "OH", L: "LH", @@ -493,6 +501,7 @@ declare const REACTIONS: { }; declare const BOOSTS: { + [part: string]: {[boost: string]: {[action: string]: number}} work: { UO: { harvest: 3 @@ -621,6 +630,8 @@ declare const LOOK_TERRAIN: "terrain"; declare const ORDER_SELL: "sell"; declare const ORDER_BUY: "buy"; + +declare const SYSTEM_USERNAME: string; /** * A site of a structure which is currently under construction. */ @@ -727,8 +738,10 @@ interface Creep extends RoomObject { saying: string; /** * The remaining amount of game ticks after which the creep will die. + * + * Will be `undefined` if the creep is still spawning. */ - ticksToLive: number; + ticksToLive: number | undefined; /** * Attack another creep or structure in a short-ranged attack. Needs the * ATTACK body part. If the target is inside a rampart, then the rampart is @@ -748,7 +761,7 @@ interface Creep extends RoomObject { * The controller under attack cannot be upgraded for the next 1,000 ticks. * The target has to be at adjacent square to the creep. * - * @returns Result Code: OK, ERR_NOT_OWNER, ERR_BUSY, ERR_INVALID_TARGET, ERR_NOT_IN_RANGE, ERR_NO_BODYPART + * @returns Result Code: OK, ERR_NOT_OWNER, ERR_BUSY, ERR_INVALID_TARGET, ERR_NOT_IN_RANGE, ERR_NO_BODYPART, ERR_TIRED */ attackController(target: StructureController): CreepActionReturnCode; /** @@ -1225,20 +1238,22 @@ type StoreDefinition = Partial> & { // energy: number; // } -interface LookAtTypes { - constructionSite?: ConstructionSite; - creep?: Creep; - energy?: Resource; - exit?: any; // TODO what type is this? - flag?: Flag; - mineral?: Mineral; - nuke?: Nuke; - resource?: Resource; - source?: Source; - structure?: Structure; - terrain?: Terrain; +interface AllLookAtTypes { + constructionSite: ConstructionSite; + creep: Creep; + energy: Resource; + exit: any; // TODO what type is this? + flag: Flag; + mineral: Mineral; + nuke: Nuke; + resource: Resource; + source: Source; + structure: Structure; + terrain: Terrain; } +type LookAtTypes = Partial; + type LookAtResult = Pick & { type: K }; type LookAtResultWithPos = LookAtResult & { @@ -1276,7 +1291,6 @@ interface FindTypes { 103: Creep; // FIND_HOSTILE_CREEPS 104: Source; // FIND_SOURCES_ACTIVE 105: Source; // FIND_SOURCES - "-106": Resource; // FIND_DROPPED_ENERGY 106: Resource; // FIND_DROPPED_RESOURCES 107: AnyStructure; // FIND_STRUCTURES 108: AnyOwnedStructure; // FIND_MY_STRUCTURES @@ -1439,6 +1453,7 @@ type ScreepsReturnCode = ERR_NOT_OWNER | ERR_NO_PATH | ERR_BUSY | + ERR_NAME_EXISTS | ERR_NOT_FOUND | ERR_NOT_ENOUGH_RESOURCES | ERR_NOT_ENOUGH_ENERGY | @@ -1476,7 +1491,8 @@ type CreepActionReturnCode = ERR_BUSY | ERR_INVALID_TARGET | ERR_NOT_IN_RANGE | - ERR_NO_BODYPART; + ERR_NO_BODYPART | + ERR_TIRED; type CreepMoveReturnCode = OK | @@ -1504,7 +1520,6 @@ type FindConstant = FIND_HOSTILE_CREEPS | FIND_SOURCES_ACTIVE | FIND_SOURCES | - FIND_DROPPED_ENERGY | FIND_DROPPED_RESOURCES | FIND_STRUCTURES | FIND_MY_STRUCTURES | @@ -2126,7 +2141,7 @@ interface PathFinder { * @param goal goal A RoomPosition, an object containing a RoomPosition and range or an array of either. * @param opts An object containing additional pathfinding flags. */ - search(origin: RoomPosition, goal: RoomPosition | { pos: RoomPosition, range: number } | RoomPosition[] | Array<{ pos: RoomPosition, range: number }>, opts?: PathFinderOpts): PathFinderPath; + search(origin: RoomPosition, goal: RoomPosition | { pos: RoomPosition, range: number } | Array, opts?: PathFinderOpts): PathFinderPath; /** * Specify whether to use this new experimental pathfinder in game objects methods. * This method should be invoked every tick. It affects the following methods behavior: @@ -2504,6 +2519,13 @@ interface RoomPosition { * @param target Can be a RoomPosition object or any object containing RoomPosition. */ getRangeTo(target: RoomPosition | { pos: RoomPosition }): number; + /** + * Check whether this position is in the given range of another position. + * @param x X position in the room. + * @param y Y position in the room. + * @param range The range distance. + */ + inRangeTo(x: number, y: number, range: number): boolean; /** * Check whether this position is in the given range of another position. * @param toPos The target position. @@ -2540,7 +2562,7 @@ interface RoomPosition { * Get an object with the given type at the specified room position. * @param type One of the following string constants: constructionSite, creep, exit, flag, resource, source, structure, terrain */ - lookFor(type: T): Array; + lookFor(type: T): Array; } interface RoomPositionConstructor extends _Constructor { @@ -2915,14 +2937,14 @@ interface Room { * @param y The Y position. * @returns An array of Creep at the given position. */ - lookForAt(type: T, x: number, y: number): Array; + lookForAt(type: T, x: number, y: number): Array; /** * Get the objects at the given RoomPosition. * @param type One of the LOOK_* constants. * @param target Can be a RoomPosition object or any object containing RoomPosition. * @returns An array of Creeps at the specified position if found. */ - lookForAt(type: T, target: RoomPosition | _HasRoomPosition): Array; + lookForAt(type: T, target: RoomPosition | _HasRoomPosition): Array; /** * Get the given objets in the supplied area. * @param type One of the LOOK_* constants @@ -2933,14 +2955,14 @@ interface Room { * @param asArray Flatten the results into an array? * @returns An object with the sstructure object[X coord][y coord] as an array of found objects. */ - lookForAtArea( + lookForAtArea( type: T, top: number, left: number, bottom: number, right: number, asArray?: false - ): LookForAtAreaResultMatrix; + ): LookForAtAreaResultMatrix; /** * Get the given objets in the supplied area. * @param type One of the LOOK_* constants @@ -2951,14 +2973,14 @@ interface Room { * @param asArray Flatten the results into an array? * @returns An array of found objects with an x & y property for their position */ - lookForAtArea( + lookForAtArea( type: T, top: number, left: number, bottom: number, right: number, asArray: true - ): LookForAtAreaResultArray; + ): LookForAtAreaResultArray; /** * Serialize a path array into a short string representation, which is suitable to store in memory. @@ -3780,6 +3802,7 @@ type AnyOwnedStructure = StructureLink | StructureNuker | StructureObserver | + StructurePowerBank | StructurePowerSpawn | StructureRampart | StructureSpawn | @@ -3794,6 +3817,5 @@ type AnyStructure = AnyOwnedStructure | StructureContainer | StructurePortal | - StructurePowerBank | StructureRoad | StructureWall; diff --git a/types/screeps/screeps-tests.ts b/types/screeps/screeps-tests.ts index 5b518c8336..bbe542b568 100644 --- a/types/screeps/screeps-tests.ts +++ b/types/screeps/screeps-tests.ts @@ -400,9 +400,6 @@ interface CreepMemory { const resources = room.find(FIND_DROPPED_RESOURCES); resources[0].resourceType; - const energy = room.find(FIND_DROPPED_ENERGY); - energy[0].resourceType; - const sites = room.find(FIND_CONSTRUCTION_SITES); sites[0].remove(); @@ -410,7 +407,7 @@ interface CreepMemory { const exits = room.find(FIND_EXIT); const creepsHere = room.lookForAt(LOOK_CREEPS, 10, 10); - creepsHere[0]!.getActiveBodyparts(ATTACK); + creepsHere[0].getActiveBodyparts(ATTACK); const towers = room.find(FIND_MY_STRUCTURES, { filter: (structure) => { @@ -462,20 +459,20 @@ interface CreepMemory { { const nukes = room.lookForAt(LOOK_NUKES, creep.pos); - nukes[0]!.launchRoomName; + nukes[0].launchRoomName; const flags = room.lookForAtArea(LOOK_FLAGS, 10, 10, 20, 20); const x = flags[10]; const y = x[11]; const entry = y[0]; - entry.flag!.remove(); + entry.flag.remove(); const creeps = room.lookForAtArea(LOOK_CREEPS, 10, 10, 20, 20, true); creeps[0].x; creeps[0].y; - creeps[0].creep!.move(TOP); + creeps[0].creep.move(TOP); } // Advanced Structure types @@ -509,3 +506,12 @@ interface CreepMemory { Game.rooms.myRoom.find(FIND_MY_STRUCTURES, (s) => s.structureType === STRUCTURE_RAMPART).forEach((r) => r.notifyWhenAttacked(false)); } + +{ + // Test that you can use signatures + EXTENSION_ENERGY_CAPACITY[Game.rooms.myRoom.controller!.level]; + + REACTIONS[Object.keys(creep.carry)[0]]; + + BOOSTS[creep.body[0].type]; +} diff --git a/types/screeps/tsconfig.json b/types/screeps/tsconfig.json index 0e153958c2..8dcc302c5c 100644 --- a/types/screeps/tsconfig.json +++ b/types/screeps/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "screeps-tests.ts" ] - } +} diff --git a/types/scrypt-async/index.d.ts b/types/scrypt-async/index.d.ts index e4a1867a1f..f3176c9e13 100644 --- a/types/scrypt-async/index.d.ts +++ b/types/scrypt-async/index.d.ts @@ -1,15 +1,31 @@ -// Type definitions for scrypt-async v1.2.0 +// Type definitions for scrypt-async v1.3.1 // Project: https://github.com/dchest/scrypt-async-js // Definitions by: Kaur Kuut +// Stefano Sicco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace ScryptAsync { +declare namespace scrypt { interface CallbackFunc { (key: string): any; (key: number[]): any; } + interface Options { + N?: number; + logN?: number; + r: number; + p: number; + dkLen: number; + encoding?: string; + interruptStep?: number; + } + interface ScryptStatic { + (password: string, salt: string, options: Options, callback: CallbackFunc): void; + (password: number[], salt: string, options: Options, callback: CallbackFunc): void; + (password: string, salt: number[], options: Options, callback: CallbackFunc): void; + (password: number[], salt: number[], options: Options, callback: CallbackFunc): void; + (password: string, salt: string, logN: number, r: number, dkLen: number, interruptStep: number, callback: CallbackFunc, encoding: string): void; (password: string, salt: number[], logN: number, r: number, dkLen: number, interruptStep: number, callback: CallbackFunc, encoding: string): void; (password: number[], salt: string, logN: number, r: number, dkLen: number, interruptStep: number, callback: CallbackFunc, encoding: string): void; @@ -32,6 +48,6 @@ declare namespace ScryptAsync { } } -declare var scrypt: ScryptAsync.ScryptStatic; +declare var scrypt: scrypt.ScryptStatic; -export = scrypt; \ No newline at end of file +export = scrypt; diff --git a/types/scrypt-async/scrypt-async-tests.ts b/types/scrypt-async/scrypt-async-tests.ts index ed12c9a5e5..e2a43fefee 100644 --- a/types/scrypt-async/scrypt-async-tests.ts +++ b/types/scrypt-async/scrypt-async-tests.ts @@ -1,23 +1,49 @@ // Tests by: Kaur Kuut import scrypt = require("scrypt-async"); -var callback = function(key: string | number[]) { }; +var callback: scrypt.CallbackFunc = function(key: string | number[]) { }; scrypt("abc", "def", 10, 8, 32, 1000, callback, "base64"); -scrypt("abc", [4,5,6], 10, 8, 32, 1000, callback, "base64"); -scrypt([1,2,3], "def", 10, 8, 32, 1000, callback, "base64"); -scrypt([1,2,3], [4,5,6], 10, 8, 32, 1000, callback, "base64"); +scrypt("abc", [100, 101, 102], 10, 8, 32, 1000, callback, "base64"); +scrypt([97, 98, 99], "def", 10, 8, 32, 1000, callback, "base64"); +scrypt([97, 98, 99], [100, 101, 102], 10, 8, 32, 1000, callback, "base64"); scrypt("abc", "def", 10, 8, 32, 1000, callback); -scrypt("abc", [4,5,6], 10, 8, 32, 1000, callback); -scrypt([1,2,3], "def", 10, 8, 32, 1000, callback); -scrypt([1,2,3], [4,5,6], 10, 8, 32, 1000, callback); +scrypt("abc", [100, 101, 102], 10, 8, 32, 1000, callback); +scrypt([97, 98, 99], "def", 10, 8, 32, 1000, callback); +scrypt([97, 98, 99], [100, 101, 102], 10, 8, 32, 1000, callback); scrypt("abc", "def", 10, 8, 32, callback, "base64"); -scrypt("abc", [4,5,6], 10, 8, 32, callback, "base64"); -scrypt([1,2,3], "def", 10, 8, 32, callback, "base64"); -scrypt([1,2,3], [4,5,6], 10, 8, 32, callback, "base64"); +scrypt("abc", [100, 101, 102], 10, 8, 32, callback, "base64"); +scrypt([97, 98, 99], "def", 10, 8, 32, callback, "base64"); +scrypt([97, 98, 99], [100, 101, 102], 10, 8, 32, callback, "base64"); scrypt("abc", "def", 10, 8, 32, callback); -scrypt("abc", [4,5,6], 10, 8, 32, callback); -scrypt([1,2,3], "def", 10, 8, 32, callback); -scrypt([1,2,3], [4,5,6], 10, 8, 32, callback); \ No newline at end of file +scrypt("abc", [100, 101, 102], 10, 8, 32, callback); +scrypt([97, 98, 99], "def", 10, 8, 32, callback); +scrypt([97, 98, 99], [100, 101, 102], 10, 8, 32, callback); + +// Tests by: Stefano Sicco +// "abc" === [97, 98, 99] +// "def" === [100, 101, 102] + + + +var opts: scrypt.Options = { + r: 8, + p: 1, + dkLen: 32, + encoding: 'base64', + interruptStep: 1000 +}; +opts.N = 1024; + +scrypt("abc", "def", opts, callback); +scrypt("abc", [100, 101, 102], opts, callback); +scrypt([97, 98, 99], "def", opts, callback); +scrypt([97, 98, 99], [100, 101, 102], opts, callback); + +opts.logN = 10; +scrypt("abc", "def", opts, callback); +scrypt("abc", [100, 101, 102], opts, callback); +scrypt([97, 98, 99], "def", opts, callback); +scrypt([97, 98, 99], [100, 101, 102], opts, callback); diff --git a/types/semver/index.d.ts b/types/semver/index.d.ts index 8b1bedbb58..06221be8af 100644 --- a/types/semver/index.d.ts +++ b/types/semver/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for semver 5.4 +// Type definitions for semver 5.5 // Project: https://github.com/npm/node-semver // Definitions by: Bart van der Schoor // BendingBender @@ -143,6 +143,12 @@ export function outside(version: string | SemVer, range: string | Range, hilo: ' */ export function intersects(range1: string | Range, range2: string | Range, loose?: boolean): boolean; +// Coercion +/** + * Coerces a string to semver if possible + */ +export function coerce(version: string | SemVer): SemVer | null; + export class SemVer { constructor(version: string | SemVer, loose?: boolean); diff --git a/types/semver/semver-tests.ts b/types/semver/semver-tests.ts index 753ddeb638..5935f1fe5f 100644 --- a/types/semver/semver-tests.ts +++ b/types/semver/semver-tests.ts @@ -65,6 +65,9 @@ bool = semver.ltr(version, str, loose); bool = semver.outside(version, str, '<', loose); bool = semver.intersects(str, str, loose); +// Coercion +sem = semver.coerce(str); + let ver = new semver.SemVer(str, bool); str = ver.raw; bool = ver.loose; diff --git a/types/serialport/index.d.ts b/types/serialport/index.d.ts index 74a4f90e42..84b5790fd4 100644 --- a/types/serialport/index.d.ts +++ b/types/serialport/index.d.ts @@ -34,6 +34,8 @@ declare class SerialPort extends Stream.Duplex { on(event: string, callback?: (data?: any) => void): this; static Binding: SerialPort.BaseBinding; + + static list(): Promise; } declare namespace SerialPort { diff --git a/types/sinon-stub-promise/index.d.ts b/types/sinon-stub-promise/index.d.ts index 2df6502e11..6de3b17b2a 100644 --- a/types/sinon-stub-promise/index.d.ts +++ b/types/sinon-stub-promise/index.d.ts @@ -1,21 +1,30 @@ -// Type definitions for sinon-stub-promise v1.1.0 +// Type definitions for sinon-stub-promise v2.1.0 // Project: https://github.com/substantial/sinon-stub-promise // Definitions by: Thiago Temple +// Tim Stackhouse // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// declare module 'sinon' { - interface SinonPromise extends Function { - resolves(value?: any): void; - rejects(value?: any): void; + interface SinonThenable { + resolved: boolean; + rejected: boolean; + resolveValue: any; + rejectValue: any; + then(onFulfill: (resolveValue?: any) => void, onReject?: (rejectValue?: any) => void): SinonThenable; + catch(onReject: (rejectValue?: any) => void): SinonThenable; + finally(callback: () => void): SinonThenable; } interface SinonStub { - returnsPromise(): SinonPromise; + thenable: SinonThenable; + returnsPromise(): SinonStub; + resolves(value?: any): SinonStub; + rejects(value?: any): SinonStub; } } declare function sinonStubPromise(sinon: sinon.SinonStatic): void; -export = sinonStubPromise; \ No newline at end of file +export = sinonStubPromise; diff --git a/types/sinon-stub-promise/sinon-stub-promise-tests.ts b/types/sinon-stub-promise/sinon-stub-promise-tests.ts index 7840272bd6..f9b1c59d4d 100644 --- a/types/sinon-stub-promise/sinon-stub-promise-tests.ts +++ b/types/sinon-stub-promise/sinon-stub-promise-tests.ts @@ -1,13 +1,49 @@ import * as sinon from 'sinon'; + +function testReturnsPromise() { + const stub = sinon.stub().returnsPromise(); +} + function testResolve() { - var promise = sinon.stub().returnsPromise(); - promise.resolves('test val'); + const stub = sinon + .stub() + .returnsPromise() + .resolves("test val"); } function testReject() { - var promise = sinon.stub().returnsPromise(); - promise.rejects('test val'); + const stub = sinon + .stub() + .returnsPromise() + .rejects("test val"); } +function testThenableThen() { + const stub = sinon.stub().returnsPromise(); + const thenable = stub.thenable; + thenable.then(() => {}); + thenable.then(resolveValue => {}); + thenable.then(() => {}, () => {}); + thenable.then(() => {}, rejectValue => {}); + thenable.then(resolveValue => {}, rejectValue => {}); +} + +function testThenableCatch() { + const stub = sinon.stub().returnsPromise(); + const thenable = stub.thenable; + thenable.catch(() => {}); + thenable.catch(rejectValue => {}); +} + +function testThenableFinally() { + const stub = sinon.stub().returnsPromise(); + const thenable = stub.thenable; + thenable.finally(() => {}); +} + +testReturnsPromise(); testResolve(); testReject(); +testThenableThen(); +testThenableCatch(); +testThenableFinally(); diff --git a/types/snapsvg/index.d.ts b/types/snapsvg/index.d.ts index ff0e9d09a9..a3397cedaa 100644 --- a/types/snapsvg/index.d.ts +++ b/types/snapsvg/index.d.ts @@ -278,7 +278,7 @@ declare namespace Snap { ellipse(x:number,y:number,rx:number,ry:number):Snap.Element; image(src:string,x:number,y:number,width:number,height:number):Snap.Element; line(x1:number,y1:number,x2:number,y2:number):Snap.Element; - path(pathString?:string):Snap.Element; + path(pathSpec: string | (string | number)[][]): Snap.Element; polygon(varargs:any[]):Snap.Element; polyline(varargs:any[]):Snap.Element; rect(x:number,y:number,width:number,height:number,rx?:number,ry?:number):Snap.Element; diff --git a/types/snapsvg/test/3.ts b/types/snapsvg/test/3.ts index 70381001ca..a97caefa45 100644 --- a/types/snapsvg/test/3.ts +++ b/types/snapsvg/test/3.ts @@ -193,9 +193,9 @@ window.onload=()=>{ var myPathString = "M 60 0 L 120 0 L 180 60 L 180 120 L 120 180 L 60 180 L 0 120 L 0 60 Z"; var p = s.path( myPathString ); + s.path([["M", 5, 10], ["l", 15, 2], ["Z"]]); var p2 = s.path( myPathString ).transform("t" + myTranslateX + "," + myTranslateY); - for( var count = 0; count < 500; count++ ) { x = Math.random() * 800; y = Math.random() * 400; diff --git a/types/storejs/index.d.ts b/types/storejs/index.d.ts index bc41120c60..0a677c0ecf 100644 --- a/types/storejs/index.d.ts +++ b/types/storejs/index.d.ts @@ -8,7 +8,7 @@ interface StoreJsAPI { readonly version: string; - readonly enabled: string; + readonly enabled: boolean; get(key: string, optionalDefaultValue?: any): any; set(key: string, value: any): any; remove(key: string): void; diff --git a/types/storejs/storejs-tests.ts b/types/storejs/storejs-tests.ts index 03c3769f9b..802f3dd40e 100644 --- a/types/storejs/storejs-tests.ts +++ b/types/storejs/storejs-tests.ts @@ -2,6 +2,9 @@ import * as store from 'store'; import * as engine from 'store/src/store-engine'; +// https://github.com/marcuswestin/store.js/blob/master/README-More.md#storeenabled-flag +console.log('storage is supported: ', store.enabled === true); + // https://github.com/marcuswestin/store.js/#api // Store current user diff --git a/types/storybook__addon-a11y/index.d.ts b/types/storybook__addon-a11y/index.d.ts new file mode 100644 index 0000000000..c29f546b6f --- /dev/null +++ b/types/storybook__addon-a11y/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for @storybook/addon-a11y 3.3 +// Project: https://github.com/storybooks/storybook +// Definitions by: HyunSeob +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { StoryDecorator } from '@storybook/react'; + +export const checkA11y: StoryDecorator; diff --git a/types/storybook__addon-a11y/storybook__addon-a11y-tests.tsx b/types/storybook__addon-a11y/storybook__addon-a11y-tests.tsx new file mode 100644 index 0000000000..4e60455618 --- /dev/null +++ b/types/storybook__addon-a11y/storybook__addon-a11y-tests.tsx @@ -0,0 +1,11 @@ +import * as React from 'react'; +import { storiesOf } from '@storybook/react'; +import { checkA11y } from '@storybook/addon-a11y'; + +storiesOf('button', module) + .addDecorator(checkA11y) + .add('Accessible', () => ( + + )); diff --git a/types/storybook__addon-a11y/tsconfig.json b/types/storybook__addon-a11y/tsconfig.json new file mode 100644 index 0000000000..4f04f36d5a --- /dev/null +++ b/types/storybook__addon-a11y/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "paths": { + "@storybook/addon-a11y": [ + "storybook__addon-a11y" + ], + "@storybook/react": [ + "storybook__react" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "storybook__addon-a11y-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/storybook__addon-a11y/tslint.json b/types/storybook__addon-a11y/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/storybook__addon-a11y/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/storybook__vue/index.d.ts b/types/storybook__vue/index.d.ts new file mode 100644 index 0000000000..13e6099724 --- /dev/null +++ b/types/storybook__vue/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for @storybook/vue 3.3 +// Project: https://github.com/storybooks/storybook +// Definitions by: Punit Gupta +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +// Created with the help of storybook__react types + +/// + +import Vue, { ComponentOptions } from 'vue'; + +// Story can be used as template or component +export type StoryFunction = () => ComponentOptions | string; +export type StoryDecorator = (story: () => ComponentOptions, context: { kind: string, story: string }) => ComponentOptions | null; + +export interface Story { + readonly kind: string; + add(storyName: string, getStory: StoryFunction): this; + addDecorator(decorator: StoryDecorator): this; +} + +export interface Addon { + [addonName: string]: (storyName: string, storyFn: StoryFunction) => void; +} +export interface StoryStore { + fileName: string | undefined; + kind: string; + stories: StoryObject[]; +} +export interface StoryObject { + name: string; + render: StoryFunction; +} + +export function addDecorator(decorator: StoryDecorator): void; +export function configure(loaders: () => void, module: NodeModule): void; +export function getStorybook(): StoryStore[]; +export function setAddon(addon: Addon): void; +export function storiesOf(kind: string, module: NodeModule): Story; diff --git a/types/storybook__vue/package.json b/types/storybook__vue/package.json new file mode 100644 index 0000000000..667aabc813 --- /dev/null +++ b/types/storybook__vue/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "vue": "^2.0.0" + } +} \ No newline at end of file diff --git a/types/storybook__vue/storybook__vue-tests.ts b/types/storybook__vue/storybook__vue-tests.ts new file mode 100644 index 0000000000..7c5c786ab7 --- /dev/null +++ b/types/storybook__vue/storybook__vue-tests.ts @@ -0,0 +1,50 @@ +import Vue, { ComponentOptions } from 'vue'; +import { addDecorator, configure, getStorybook, setAddon, storiesOf, StoryFunction, Story } from '@storybook/vue'; + +interface CustomStory extends Story { + addCentered(storyName: string, storyFn: StoryFunction): this; +} + +const addCenteredAddon = { + addCentered(this: Story, storyName: string, storyFn: StoryFunction): void { + console.log(this.kind); + this.add(storyName, storyFn); + } +}; + +const Decorator = (story: () => ComponentOptions) => { + const wrapper = story(); + return { + components: { wrapper }, + template: '
', + data() { + return { borderStyle: 'medium solid red' }; + } + }; +}; + +addDecorator(Decorator); +configure(() => undefined, module); +getStorybook().forEach(({ fileName, kind, stories }) => stories.forEach(({ name, render }) => render())); +setAddon(addCenteredAddon); + +storiesOf('Storybook__vue', module) + .addDecorator(Decorator) + .add('story as a template', () => '
') + .add('story as a component', () => ({ + components: {}, + template: '
' + })); + +(storiesOf('Custom_Story', module) as CustomStory) + .addCentered('custom story', () => ({ + template: '
' + })) + .add('story as a template', () => '
') + .add('story as a component', () => ({ + components: {}, + template: '
' + })) + .addCentered('custom story', () => ({ + template: '
' + })); diff --git a/types/storybook__vue/tsconfig.json b/types/storybook__vue/tsconfig.json new file mode 100644 index 0000000000..a472ebed8a --- /dev/null +++ b/types/storybook__vue/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@storybook/vue": [ + "storybook__vue" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "storybook__vue-tests.ts" + ] +} \ No newline at end of file diff --git a/types/storybook__vue/tslint.json b/types/storybook__vue/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/storybook__vue/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index c2d60ea644..c3fd4853b7 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -1330,7 +1330,7 @@ declare namespace Stripe { * override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to * end the customer's trial immediately. Only applies when the plan parameter is also provided. */ - trial_end?: number; + trial_end?: number | "now"; } interface ICustomerUpdateOptions extends IDataOptionsWithMetadata { @@ -4216,6 +4216,7 @@ declare namespace Stripe { namespace subscriptions { type SubscriptionStatus = "trialing" | "active" | "past_due" | "canceled" | "unpaid"; + type SubscriptionBilling = "charge_automatically" | "send_invoice"; /** * Subscriptions allow you to charge a customer's card on a recurring basis. A subscription ties a customer to * a particular plan you've created: https://stripe.com/docs/api#create_plan @@ -4325,14 +4326,14 @@ declare namespace Stripe { * end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an * invoice with payment instructions. */ - billing: "charge_automatically" | "send_invoice"; + billing: SubscriptionBilling; } interface ISubscriptionCustCreationOptions extends IDataOptionsWithMetadata { /** - * The identifier of the plan to subscribe the customer to. + * @deprecated Use items property instead. */ - plan: string; + plan?: string; /** * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice @@ -4370,19 +4371,19 @@ declare namespace Stripe { * will override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to end the * customer's trial immediately. */ - trial_end?: number; + trial_end?: number | "now"; /** * List of subscription items, each with an attached plan. */ - items?: ISubscriptionCreationItem; + items?: ISubscriptionCreationItem[]; /** * Either "charge_automatically", or "send_invoice". When charging automatically, Stripe will attempt to pay this subscription at the end of the * cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment * instructions. Defaults to "charge_automatically". */ - billing?: "charge_automatically" | "send_invoice"; + billing?: SubscriptionBilling; } interface ISubscriptionCreationOptions extends ISubscriptionCustCreationOptions { @@ -4407,7 +4408,7 @@ declare namespace Stripe { coupon?: string; /** - * The identifier of the plan to update the subscription to. If omitted, the subscription will not change plans. + * @deprecated Use items property instead. */ plan?: string; @@ -4446,14 +4447,19 @@ declare namespace Stripe { * will override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to end the * customer's trial immediately. */ - trial_end?: number; + trial_end?: number | "now"; /** * Either "charge_automatically", or "send_invoice". When charging automatically, Stripe will attempt to pay this subscription at the end of the * cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment * instructions. */ - billing?: "charge_automatically" | "send_invoice"; + billing?: SubscriptionBilling; + + /** + * List of subscription items, each with an attached plan. + */ + items?: ISubscriptionUpdateItem[]; } interface ISubscriptionCancellationOptions extends IDataOptions { @@ -4467,7 +4473,7 @@ declare namespace Stripe { /** * The billing mode of the subscriptions to retrieve. Either "charge_automatically" or "send_invoice". */ - billing?: "charge_automatically" | "send_invoice"; + billing?: SubscriptionBilling; /** * The ID of the customer whose subscriptions will be retrieved @@ -4496,6 +4502,40 @@ declare namespace Stripe { */ quantity?: number } + + interface ISubscriptionUpdateItem { + /** + * SubscriptionItem to update. + */ + id?: string; + + /** + * Delete all usage for a given subscription item. Only allowed when deleted is set to true and the current plan’s + * usage_type is metered. + */ + clear_usage?: boolean; + + /** + * Delete the specified item if set to true. + */ + deleted?: boolean; + + /** + * Set of key/value pairs that you can attach to an object. It can be useful for storing additional information about + * the object in a structured format. + */ + metadata?: IOptionsMetadata; + + /** + * Plan ID for this item. + */ + plan?: string; + + /** + * Quantity for this item. + */ + quantity?: number + } } namespace subscriptionItems { diff --git a/types/stripe/stripe-tests.ts b/types/stripe/stripe-tests.ts index 60374b697d..99cf3795db 100644 --- a/types/stripe/stripe-tests.ts +++ b/types/stripe/stripe-tests.ts @@ -251,9 +251,14 @@ stripe.customers.create({ customer.cards.list().then(function (cards) {}); customer.cards.del("card_17xMvXBoqMA9o2xkq6W5gamx").then(function (confirmation) {}); - customer.subscriptions.create({ plan: "gold" }).then(function (subscription) { }); - customer.subscriptions.retrieve("sub_8Eluur5KoIKxuy").then(function (subscription) { }); - customer.subscriptions.update("sub_8Eluur5KoIKxuy", { plan: "silver" }).then(function (subscription) { }); + customer.subscriptions.create({ items: [{ plan: "gold" }] }).then(function (subscription) { }); + customer.subscriptions.create({ items: [{ plan: "gold" }], trial_end: "now" }).then(function (subscription) { }); + customer.subscriptions.create({ items: [{ plan: "gold" }], trial_end: 1516881177 }).then(function (subscription) { }); + customer.subscriptions.retrieve("sub_8Eluur5KoIKxuy").then(function (subscription) { + customer.subscriptions.update("sub_8Eluur5KoIKxuy", { items: [{ id: subscription.items.data[0].id, plan: "silver" }] }).then(function (subscription) { }); + }); + customer.subscriptions.update("sub_8Eluur5KoIKxuy", { trial_end: "now" }); + customer.subscriptions.update("sub_8Eluur5KoIKxuy", { trial_end: 1516881177 }); customer.subscriptions.list().then(function (subscriptions) { }); customer.subscriptions.del("sub_8Eluur5KoIKxuy").then(function (subscription) { }); customer.subscriptions.deleteDiscount("sub_8Eluur5KoIKxuy").then(function (confirmation) { }); @@ -296,6 +301,22 @@ stripe.customers.create({ }); +// {"now"} for trial_end +stripe.customers.create({ + description: "Customer for test@example.com", + source: "tok_15V2YhEe31JkLCeQy9iUgsJX", // obtained with Stripe.js + plan: "platypi-dev", + trial_end: "now" +}); + +// {number} for trial_end +stripe.customers.create({ + description: "Customer for test@example.com", + source: "tok_15V2YhEe31JkLCeQy9iUgsJX", // obtained with Stripe.js + plan: "platypi-dev", + trial_end: 1516881177 +}); + stripe.customers.retrieve( "cus_5rfJKDJkuxzh5Q", function (err, customer) { @@ -484,12 +505,12 @@ stripe.customers.retrieveSubscription("cus_5rfJKDJkuxzh5Q", "sub_5rfJxnBLGSwsYp" // asynchronously called }); -stripe.customers.updateSubscription("cus_5rfJKDJkuxzh5Q", "sub_5rfJxnBLGSwsYp", { plan: "platypi-dev" }, +stripe.customers.updateSubscription("cus_5rfJKDJkuxzh5Q", "sub_5rfJxnBLGSwsYp", { items: [{ id: "si_62U5U5BoqBA2o2xp6Eqcl6J7", plan: "platypi-dev" }] }, function (err, subscription) { // asynchronously called } ); -stripe.customers.updateSubscription("cus_5rfJKDJkuxzh5Q", "sub_5rfJxnBLGSwsYp", { plan: "platypi-dev" }).then(function (subscription) { +stripe.customers.updateSubscription("cus_5rfJKDJkuxzh5Q", "sub_5rfJxnBLGSwsYp", { items: [{ id: "si_62U5U5BoqBA2o2xp6Eqcl6J7", plan: "platypi-dev" }] }).then(function (subscription) { // asynchronously called }); @@ -1114,11 +1135,18 @@ stripe.plans.list().then(function (plans) { //#region Subscriptions tests // ################################################################################## -stripe.subscriptions.create({ plan: "platypi-dev", customer: "cus_5rfJKDJkuxzh5Q" }, function(err, subscription) { +stripe.subscriptions.create({ items: [{ plan: "platypi-dev" }], customer: "cus_5rfJKDJkuxzh5Q" }, function(err, subscription) { // asynchronously called }); -stripe.subscriptions.create({ plan: "platypi-dev", customer: "cus_5rfJKDJkuxzh5Q" }).then(function(subscription) { +stripe.subscriptions.create({ items: [{ plan: "platypi-dev" }], customer: "cus_5rfJKDJkuxzh5Q" }).then(function(subscription) { // asynchronously called + + stripe.subscriptions.update("sub_8QwCiwZ9tmMSpt", { items: [{ id: subscription.items.data[0].id, plan: "platypi" }] }, function(err, subscription) { + // asynchronously called + }); + stripe.subscriptions.update("sub_8QwCiwZ9tmMSpt", { items: [{ id: subscription.items.data[0].id, plan: "platypi" }] }).then(function(subscription) { + // asynchronously called + }); }); stripe.subscriptions.retrieve("sub_8QwCiwZ9tmMSpt", function(err, subscription) { @@ -1134,13 +1162,6 @@ stripe.subscriptions.retrieve("sub_8QwCiwZ9tmMSpt").then(function(subscription) } }); -stripe.subscriptions.update("sub_8QwCiwZ9tmMSpt", { plan: "platypi" }, function(err, subscription) { - // asynchronously called -}); -stripe.subscriptions.update("sub_8QwCiwZ9tmMSpt", { plan: "platypi" }).then(function(subscription) { - // asynchronously called -}); - stripe.subscriptions.del("sub_8QwCiwZ9tmMSpt", function(err, subscription) { // asynchronously called }); diff --git a/types/swiper/index.d.ts b/types/swiper/index.d.ts index 5f4cf01298..65872facd2 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -320,8 +320,8 @@ declare class Swiper { enableMousewheelControl(): void; disableKeyboardControl(): void; enableKeyboardControl(): void; - disableTouchContro(): void; - enableTouchContro(): void; + disableTouchControl(): void; + enableTouchControl(): void; unsetGrabCursor(): void; setGrabCursor(): void; diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 2cea550034..e553853293 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for three.js 0.89 // Project: https://threejs.org -// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei , Ivo , David Asmuth , Brandon Roberge, Qinsi ZHU , Toshiya Nakakura , Poul Kjeldager Sørensen , Stefan Profanter , Edmund Fokschaner , Roelof Jooste , Daniel Hritzkiv +// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei , Ivo , David Asmuth , Brandon Roberge, Qinsi ZHU , Toshiya Nakakura , Poul Kjeldager Sørensen , Stefan Profanter , Edmund Fokschaner , Roelof Jooste , Daniel Hritzkiv , Apurva Ojas // Definitions: https://github.com//DefinitelyTyped export * from "./three-core"; @@ -27,6 +27,7 @@ export * from "./three-projector"; export * from "./three-renderpass"; export * from "./three-shaderpass"; export * from "./three-smaapass"; +export * from "./three-filmpass"; export * from "./three-trackballcontrols"; export * from "./three-transformcontrols"; export * from "./three-vrcontrols"; diff --git a/types/three/test/webgl/webgl_interactive_raycasting_points.ts b/types/three/test/webgl/webgl_interactive_raycasting_points.ts index ced8feb6c6..7f6f163a28 100644 --- a/types/three/test/webgl/webgl_interactive_raycasting_points.ts +++ b/types/three/test/webgl/webgl_interactive_raycasting_points.ts @@ -215,7 +215,7 @@ // var sphereGeometry = new THREE.SphereGeometry(0.1, 32, 32); - var sphereMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, shading: THREE.FlatShading}); + var sphereMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, flatShading: true}); for (var i = 0; i < 40; i++) { @@ -313,4 +313,4 @@ renderer.render(scene, camera); } -} \ No newline at end of file +} diff --git a/types/three/test/webgl/webgl_lights_hemisphere.ts b/types/three/test/webgl/webgl_lights_hemisphere.ts index 108419f4ad..c0daf3773f 100644 --- a/types/three/test/webgl/webgl_lights_hemisphere.ts +++ b/types/three/test/webgl/webgl_lights_hemisphere.ts @@ -113,7 +113,7 @@ loader.load( "models/animated/flamingo.js", function( geometry ) { - var material = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0xffffff, shininess: 20, morphTargets: true, vertexColors: THREE.FaceColors, shading: THREE.FlatShading } ); + var material = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0xffffff, shininess: 20, morphTargets: true, vertexColors: THREE.FaceColors, flatShading: true } ); var mesh = new THREE.Mesh( geometry, material ); var s = 0.35; diff --git a/types/three/test/webgl/webgl_materials.ts b/types/three/test/webgl/webgl_materials.ts index 23d2d98a23..68235c5e5c 100644 --- a/types/three/test/webgl/webgl_materials.ts +++ b/types/three/test/webgl/webgl_materials.ts @@ -56,20 +56,20 @@ materials.push(new THREE.MeshLambertMaterial({ map: texture, transparent: true })); materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd })); - materials.push(new THREE.MeshPhongMaterial({ color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.FlatShading })); + materials.push(new THREE.MeshPhongMaterial({ color: 0xdddddd, specular: 0x009900, shininess: 30, flatShading: true })); materials.push(new THREE.MeshNormalMaterial()); materials.push(new THREE.MeshBasicMaterial({ color: 0xffaa00, transparent: true, blending: THREE.AdditiveBlending })); //materials.push( new THREE.MeshBasicMaterial( { color: 0xff0000, blending: THREE.SubtractiveBlending } ) ); materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd })); - materials.push(new THREE.MeshPhongMaterial({ color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, map: texture, transparent: true })); + materials.push(new THREE.MeshPhongMaterial({ color: 0xdddddd, specular: 0x009900, shininess: 30, flatShading: false, map: texture, transparent: true })); materials.push(new THREE.MeshNormalMaterial({})); materials.push(new THREE.MeshBasicMaterial({ color: 0xffaa00, wireframe: true })); materials.push(new THREE.MeshDepthMaterial()); materials.push(new THREE.MeshLambertMaterial({ color: 0x666666, emissive: 0xff0000 })); - materials.push(new THREE.MeshPhongMaterial({ color: 0x000000, specular: 0x666666, emissive: 0xff0000, shininess: 10, shading: THREE.SmoothShading, opacity: 0.9, transparent: true })); + materials.push(new THREE.MeshPhongMaterial({ color: 0x000000, specular: 0x666666, emissive: 0xff0000, shininess: 10, flatShading: false, opacity: 0.9, transparent: true })); materials.push(new THREE.MeshBasicMaterial({ map: texture, transparent: true })); @@ -100,7 +100,7 @@ let material = materials[i]; geometry = material instanceof THREE.MeshFaceMaterial ? geometry_pieces : - (material.shading == THREE.FlatShading ? geometry_flat : geometry_smooth); + (material.flatShading ? geometry_flat : geometry_smooth); sphere = new THREE.Mesh(geometry, material); diff --git a/types/three/test/webgl/webgl_postprocessing.ts b/types/three/test/webgl/webgl_postprocessing.ts index 0c768eccea..dff5ec5592 100644 --- a/types/three/test/webgl/webgl_postprocessing.ts +++ b/types/three/test/webgl/webgl_postprocessing.ts @@ -26,7 +26,7 @@ scene.add(object); var geometry = new THREE.SphereGeometry(1, 4, 4); - var material = new THREE.MeshPhongMaterial({ color: 0xffffff, shading: THREE.FlatShading }); + var material = new THREE.MeshPhongMaterial({ color: 0xffffff, flatShading: true }); for (var i = 0; i < 100; i++) { @@ -84,4 +84,4 @@ composer.render(); } -} \ No newline at end of file +} diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index c3401a7737..8abbd380a7 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -450,11 +450,6 @@ export class Camera extends Object3D { getWorldDirection(optionalTarget?: Vector3): Vector3; - /** - * This make the camera look at the vector position in local space. - * @param vector point to look at - */ - lookAt(vector: Vector3): void; } export class CubeCamera extends Object3D { @@ -1620,6 +1615,12 @@ export class Object3D extends EventDispatcher { */ userData: any; + /** + * Used to check whether this or derived classes are Object3Ds. Default is true. + * You should not change this, as it is used internally for optimisation. + */ + isObject3D: boolean; + /** * Calls before rendering object */ @@ -1670,6 +1671,13 @@ export class Object3D extends EventDispatcher { */ rotateOnAxis(axis: Vector3, angle: number): Object3D; + /** + * Rotate an object along an axis in world space. The axis is assumed to be normalized. Method Assumes no rotated parent. + * @param axis A normalized vector in object space. + * @param angle The angle in radians. + */ + rotateOnWorldAxis(axis: Vector3, angle: number): Object3D; + /** * * @param angle @@ -1729,6 +1737,7 @@ export class Object3D extends EventDispatcher { * @param vector A world vector to look at. */ lookAt(vector: Vector3): void; + lookAt(x: number, y: number, z: number): void; /** * Adds object as child of this object. @@ -1738,7 +1747,7 @@ export class Object3D extends EventDispatcher { /** * Removes object as child of this object. */ - remove(object: Object3D): void; + remove(...object: Object3D[]): void; /** * Searches through the object's children and returns the first with a matching id, optionally recursive. @@ -1788,13 +1797,6 @@ export class Object3D extends EventDispatcher { * @param recursive */ copy(source: this, recursive?: boolean): this; - - /** - * @deprecated - */ - eulerOrder: string; - getChildByName(name: string): Object3D; - translate(distance: number, axis: Vector3): Object3D; } export interface Intersection { @@ -2364,8 +2366,6 @@ export interface MaterialParameters { transparent?: boolean; vertexColors?: Colors; visible?: boolean; - - shading?: Shading; } /** @@ -2598,15 +2598,6 @@ export class Material extends EventDispatcher { */ update(): void; - /** - * @deprecated - */ - warpRGB: Color; - - /** - * @deprecated Removed, use .flatShading instead. - */ - shading: Shading; } export interface LineBasicMaterialParameters extends MaterialParameters { @@ -2662,7 +2653,6 @@ export interface MeshBasicMaterialParameters extends MaterialParameters { combine?: Combine; reflectivity?: number; refractionRatio?: number; - shading?: Shading; wireframe?: boolean; wireframeLinewidth?: number; wireframeLinecap?: string; @@ -2684,7 +2674,6 @@ export class MeshBasicMaterial extends Material { combine: Combine; reflectivity: number; refractionRatio: number; - shading: Shading; wireframe: boolean; wireframeLinewidth: number; wireframeLinecap: string; @@ -6621,7 +6610,7 @@ export class ConeBufferGeometry extends BufferGeometry { export class ConeGeometry extends CylinderGeometry { constructor(radius?: number, height?: number, radialSegment?: number, heightSegment?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number); } - + export class DodecahedronBufferGeometry extends PolyhedronBufferGeometry { constructor(radius?: number, detail?: number); } @@ -6681,7 +6670,7 @@ export class LatheGeometry extends Geometry { phiLength: number; }; } - + export class OctahedronBufferGeometry extends PolyhedronBufferGeometry { constructor(radius?: number, detail?: number); } @@ -6721,10 +6710,10 @@ export class PlaneGeometry extends Geometry { heightSegments: number; }; } - + export class PolyhedronBufferGeometry extends BufferGeometry { constructor(vertices: number[], indices: number[], radius: number, detail: number); - + parameters: { vertices: number[]; indices: number[]; @@ -6820,7 +6809,7 @@ export class SphereGeometry extends Geometry { thetaLength: number; }; } - + export class TetrahedronBufferGeometry extends PolyhedronBufferGeometry { constructor(radius?: number, detail?: number); } diff --git a/types/three/three-effectcomposer.d.ts b/types/three/three-effectcomposer.d.ts index 3680a43658..0f30d45d04 100644 --- a/types/three/three-effectcomposer.d.ts +++ b/types/three/three-effectcomposer.d.ts @@ -23,3 +23,23 @@ export class EffectComposer { setSize(width: number, height: number): void; } + + +export class Pass{ + // if set to true, the pass is processed by the composer + enabled: boolean; + + // if set to true, the pass indicates to swap read and write buffer after rendering + needsSwap: boolean; + + // if set to true, the pass clears its buffer before rendering + clear: boolean; + + // if set to true, the result of the pass is rendered to screen + renderToScreen: boolean; + + setSize(width: number, height:number ): void; + + render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number, maskActive?: boolean): void; + +} \ No newline at end of file diff --git a/types/three/three-filmpass.d.ts b/types/three/three-filmpass.d.ts new file mode 100644 index 0000000000..0890ac8507 --- /dev/null +++ b/types/three/three-filmpass.d.ts @@ -0,0 +1,13 @@ +import { Camera, Scene, WebGLRenderTarget, WebGLRenderer, Material, Mesh, IUniform } from "./three-core"; +import {Pass} from "./three-effectcomposer"; + +export class FilmPass extends Pass { + constructor(noiseIntensity: number, scanlinesIntensity: number, scanlinesCount: number, grayscale: boolean); + + scene: Scene; + camera: Camera; + uniforms: IUniform; + material: Material; + quad: Mesh; + +} diff --git a/types/waypoints/index.d.ts b/types/waypoints/index.d.ts index 97ad8d3488..0bf0c488d8 100644 --- a/types/waypoints/index.d.ts +++ b/types/waypoints/index.d.ts @@ -1,18 +1,21 @@ // Type definitions for waypoints 4.x // Project: https://github.com/imakewebthings/waypoints -// Definitions by: Dominik Bułaj , Alexey Kolotovchenkov +// Definitions by: Dominik Bułaj , Alexey Kolotovchenkov , Sergei Dorogin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -interface WaypointOptions { - element: HTMLElement; - handler: (this: Waypoint, direction?: string) => void; +interface WaypointOptionsBase { offset?: string|number|(() => number); - context?: HTMLElement; continuous?: boolean; enabled?: boolean; group?: string; horizontal?: boolean; } +interface WaypointOptions extends WaypointOptionsBase { + element: HTMLElement; + handler: (this: Waypoint, direction?: string) => void; + context?: HTMLElement; +} declare class WaypointGroup { first: () => Waypoint; diff --git a/types/waypoints/jquery.d.ts b/types/waypoints/jquery.d.ts new file mode 100644 index 0000000000..d93b0ac18e --- /dev/null +++ b/types/waypoints/jquery.d.ts @@ -0,0 +1,13 @@ +/* Type definitions for jQuery Adapter for waypoints 4.0 */ + +/// + +interface JQuery { + waypoint(handler: (this: Waypoint, direction?: string) => void, options?: WaypointOptionsJQuery): JQuery; + waypoint(options?: WaypointOptionsJQuery): JQuery; +} + +interface WaypointOptionsJQuery extends WaypointOptionsBase { + handler?: (this: Waypoint, direction?: string) => void; + context?: HTMLElement|string; +} diff --git a/types/waypoints/tsconfig.json b/types/waypoints/tsconfig.json index c457df62f8..4acd5d77b4 100644 --- a/types/waypoints/tsconfig.json +++ b/types/waypoints/tsconfig.json @@ -19,6 +19,7 @@ }, "files": [ "index.d.ts", + "jquery.d.ts", "waypoints-tests.ts" ] } \ No newline at end of file diff --git a/types/waypoints/waypoints-tests.ts b/types/waypoints/waypoints-tests.ts index 658412f953..4ea425fbf8 100644 --- a/types/waypoints/waypoints-tests.ts +++ b/types/waypoints/waypoints-tests.ts @@ -4,7 +4,7 @@ declare function notify(text: string): void; // A Basic Waypoint // -------------------------------------------------------------------------------------------------------------------- -let waypoint1 = new Waypoint({ +const waypoint1 = new Waypoint({ element: document.getElementById('basic-waypoint')!, handler() { notify('Basic waypoint triggered'); @@ -13,7 +13,7 @@ let waypoint1 = new Waypoint({ // Directions // -------------------------------------------------------------------------------------------------------------------- -let waypoint2 = new Waypoint({ +const waypoint2 = new Waypoint({ element: document.getElementById('direction-waypoint')!, handler(direction) { notify('Direction: ' + direction); @@ -22,7 +22,7 @@ let waypoint2 = new Waypoint({ // Offsets // -------------------------------------------------------------------------------------------------------------------- -let waypoint3 = new Waypoint({ +const waypoint3 = new Waypoint({ element: document.getElementById('px-offset-waypoint')!, handler(direction) { notify('I am 20px from the top of the window'); @@ -32,10 +32,45 @@ let waypoint3 = new Waypoint({ // this? // -------------------------------------------------------------------------------------------------------------------- -let waypoint4 = new Waypoint({ +const waypoint4 = new Waypoint({ element: document.getElementById('element-waypoint')!, handler(direction) { notify(`${this.element.id} triggers at ${this.triggerPoint}`); }, offset: '75%' }); + +// JQuery adapter +// All code examples below taken from http://imakewebthings.com/waypoints/guides/jquery-zepto/ + +import $ = require('jquery'); + +// $.fn.waypoint +// -------------------------------------------------------------------------------------------------------------------- + +const waypoints10 = $('#options-only').waypoint({ + handler: function fn(this: Waypoint, direction?: string) { + notify(this.element.id + ' hit'); + } +}); + +const waypoints11 = $('#handler-first').waypoint(function() { + notify(this.element.id + ' hit 25% from top of window'); +}, { + offset: '25%' +}); + +const waypoints12 = $('#handler-only').waypoint(function() { + notify(this.element.id + ' hit'); +}); + +// Context Option +// -------------------------------------------------------------------------------------------------------------------- + +const waypoints13 = $('#context-example-offset').waypoint({ + handler: function fn(this: Waypoint, direction?: string) { + notify('Hit midpoint of my context'); + }, + context: '#overflow-scroll-offset', + offset: '50%' +}); diff --git a/types/webpack-env/index.d.ts b/types/webpack-env/index.d.ts index 9d866cbba8..1f03a25647 100644 --- a/types/webpack-env/index.d.ts +++ b/types/webpack-env/index.d.ts @@ -31,8 +31,7 @@ declare namespace __WebpackModuleApi { * * This creates a chunk. The chunk can be named. If a chunk with this name already exists, the dependencies are merged into that chunk and that chunk is used. */ - ensure(paths: string[], callback: (require: (id: string) => any) => void, chunkName?: string): void; - ensure(paths: string[], callback: (require: (id: string) => T) => void, chunkName?: string): void; + ensure(paths: string[], callback: (require: NodeRequire) => void, chunkName?: string): void; context(path: string, deep?: boolean, filter?: RegExp): RequireContext; /** * Returns the module id of a dependency. The call is sync. No request to the server is fired. The compiler ensures that the dependency is available. @@ -43,7 +42,7 @@ declare namespace __WebpackModuleApi { /** * Like require.resolve, but doesn’t include the module into the bundle. It’s a weak dependency. */ - resolveWeak(path: string): number; + resolveWeak(path: string): number | string; /** * Ensures that the dependency is available, but don’t execute it. This can be use for optimizing the position of a module in the chunks. */ diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index db8bb35c72..ccd809c46b 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -516,7 +516,7 @@ declare namespace webpack { * It is possible to exclude a huge folder like node_modules. * It is also possible to use anymatch patterns. */ - ignored?: string | RegExp; + ignored?: string | string[] | RegExp; /** Turn on polling by passing true, or specifying a poll interval in milliseconds. */ poll?: boolean | number; } diff --git a/types/zapier-platform-core/index.d.ts b/types/zapier-platform-core/index.d.ts index 0bea385f05..525421abbf 100644 --- a/types/zapier-platform-core/index.d.ts +++ b/types/zapier-platform-core/index.d.ts @@ -8,6 +8,9 @@ import * as http from "http"; +export function createAppHandler(appRawOrPath: object | string): (event: any, context: any, callback: any) => void; +export function createAppTester(appRawOrPath: object | string): Promise; +export function integrationTestHandler(event: any, context: any, callback: any): any; export const version: string; export interface HttpRequestOptions { diff --git a/types/zapier-platform-core/zapier-platform-core-tests.ts b/types/zapier-platform-core/zapier-platform-core-tests.ts index 76592204ae..6c6c490edd 100644 --- a/types/zapier-platform-core/zapier-platform-core-tests.ts +++ b/types/zapier-platform-core/zapier-platform-core-tests.ts @@ -1,10 +1,10 @@ -import { OAuth2Authentication } from "zapier-platform-core"; +import * as zapier from "zapier-platform-core"; const BASE_URL = "http://example.com"; const OAUTH2_CLIENT_ID = "12345"; const OAUTH2_CLIENT_SECRET = "abcdef"; -const authentication: OAuth2Authentication = { +const authentication: zapier.OAuth2Authentication = { type: "oauth2", connectionLabel: "User account", oauth2Config: { @@ -91,3 +91,10 @@ const authentication: OAuth2Authentication = { return true; } }; + +zapier.version; + +const testCreateAppTester = async () => { + const zapierApp = {}; + const appTester = await zapier.createAppTester(zapierApp); +};