diff --git a/README.es.md b/README.es.md index c3cff967db..df675cbe41 100644 --- a/README.es.md +++ b/README.es.md @@ -22,15 +22,15 @@ Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0 npm install --save-dev @types/node ``` -Los types deberían ser incluidos automaticamente por el compilador. +Los types deberían ser incluidos automáticamente por el compilador. Vea más en el [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). -Para un paquete NPM "foo", Estos `typings` estarán en "@types/foo". +Para un paquete NPM "foo", estos `typings` estarán en "@types/foo". Si no puedes encontrar tu paquete, búscalo en [TypeSearch](https://microsoft.github.io/TypeSearch/). Si aún no puedes encontrarlo, comprueba si el paquete ya [incluye](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) los typings. Esto es provisto usualmente en el campo `"types"` o `"typings"` en el `package.json`, -o solo busca por cualquier archivo ".d.ts" en el paquete e incluyelo manualmente con un `/// `. +o solo busca por cualquier archivo ".d.ts" en el paquete e inclúyelo manualmente con un `/// `. ### Otros métodos @@ -39,7 +39,7 @@ Estos pueden ser utilizados por TypeScript 1.0. * [Typings](https://github.com/typings/typings) * ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada) -* Descarguelo manualmente desde la `master` branch de este repositorio +* Descárguelo manualmente desde la `master` branch de este repositorio Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). @@ -88,7 +88,7 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re * `cd types/my-package-to-edit` * Haz cambios. Recuerda editar las pruebas. Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal). -* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete. +* También puede que quieras añadirle la sección "Definitions by" en el encabezado del paquete. - Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete. - Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice , Bob `. - O si hay más personas, puede ser multiline @@ -109,7 +109,7 @@ Si no lo hace, puedes hacerlo en el comentario asociado con el PR. Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en DefinitelyTyped. Si estás agregando typings para un paquete NPM, crea un directorio con el mismo nombre. -Si el paquete al que le estás agregando typings no es para NPM, asegurate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM. +Si el paquete al que le estás agregando typings no es para NPM, asegúrate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM. (Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.) Tu paquete debería tener esta estructura: @@ -126,7 +126,7 @@ Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen). También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`. -Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrian ralentizar el proceso. +Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrían ralentizar el proceso. Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js). @@ -135,7 +135,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy * Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). * Formatear: Ya sea utilizar todo en tabs, o siempre utiliza 4 espacios. -* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una funcion no escribe a sus parámetros. +* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una función no escribe a sus parámetros. * `interface Foo { new(): Foo; }`: Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`. * `const Class: { new(): IClass; }`: @@ -146,7 +146,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy Un ejemplo donde un tipo de parámetro es aceptable: `function id(value: T): T;`. Un ejemplo donde no es aceptable: `function parseJson(json: string): T;`. Una excepción: `new Map()` está bien. -* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más especifico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`. +* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más específico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`. * `var foo: string | any`: Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`. Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`. @@ -204,11 +204,11 @@ Este script utiliza [dtslint](https://github.com/Microsoft/dtslint). #### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM? -La `master` branch es automaticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher). +La `master` branch es automáticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher). #### He enviado un pull request. ¿Cuánto tardará en ser merged? -Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprovados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor se paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan on los PRs abiertos. +Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprobados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor sé paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan en los PRs abiertos. #### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM? @@ -216,12 +216,12 @@ Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado m #### Estoy escribiendo una definición que depende de otra definición. Debería utilizar `` o una import? -Si el modulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import. +Si el módulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import. Si el módulo al cual te refieres es un módulo ambiente (utiliza `declare module`, o simplemente declara las globales), utilice ``. #### He notado que algunos paquetes aquí tienen `package.json`. -Normalmente no lo necesitaras. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso. +Normalmente no lo necesitarás. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso. Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json). No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente. Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json. @@ -260,7 +260,7 @@ Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer Si planeas continuar actualizando la versión anterior del paquete, puedes crear una subcarpeta con la versión actual p.ej. `v2`, y copia los archivos existentes. Si es así, necesitarás: 1. Actualiza las rutas relativas en `tsconfig.json` al igual que `tslint.json`. -2. Añadir reglas de mapeo de rutas para asegurart de que la prueba se está ejecutando contra la versión prevista. +2. Añadir reglas de mapeo de rutas para asegurarte de que la prueba se está ejecutando contra la versión prevista. Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así: @@ -280,24 +280,24 @@ Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi } ``` -Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitaras mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior. +Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitarás mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior. Por ejemplo, `react-router` depende de `history@2`, así que [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) tiene una ruta mapeada a "history": `[ "history/v2" ]`; transitivo así mismo, `react-router-bootstrap` (que depende de `react-router`) también añade una ruta mapeada en su [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). -Además, `/// ` no trabajara con rutas mapeadas, así que las dependencias deberán utilizar `import`. +Además, `/// ` no trabajará con rutas mapeadas, así que las dependencias deberán utilizar `import`. #### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo? -El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), ademas [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada practicamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a travéz de una etiqueta script en una página web, o importada via require o imports estilo ES6. +El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), además [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada prácticamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a través de una etiqueta script en una página web, o importada vía require o imports estilo ES6. -Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas un propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js. +Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas una propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js. Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa. #### ¿Qué pasa con paquetes scoped? -Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guion bajo. +Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guión bajo. Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedades `paths` deberán ser adaptadas manualmente en el paquete generado `tsconfig.json` para referenciar correctamente el paquete scoped: diff --git a/types/ale-url-parser/ale-url-parser-tests.ts b/types/ale-url-parser/ale-url-parser-tests.ts new file mode 100644 index 0000000000..2a5d9fe632 --- /dev/null +++ b/types/ale-url-parser/ale-url-parser-tests.ts @@ -0,0 +1,22 @@ +import { parse, stringify } from 'ale-url-parser'; + +let url; +let urlObject; + +url = stringify({}); +console.log(url); + +url = stringify({ + protocol: 'protocol', + host: 'host', + path: ['foo', 'bar', 'baz'], + hash: 'hash', + query: { + foo: 1, + bar: [2, '3'] + } +}); +console.log(url); + +urlObject = parse('//any.dom.ain.co.m/foo/bar?test=1&test=2#hash'); +console.log(urlObject); diff --git a/types/ale-url-parser/index.d.ts b/types/ale-url-parser/index.d.ts new file mode 100644 index 0000000000..31b2d2fd03 --- /dev/null +++ b/types/ale-url-parser/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for ale-url-parser 0.10 +// Project: https://github.com/msn0/ale-url-parser#readme +// Definitions by: Michał Jezierski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export interface QueryParams { + [key: string]: any; +} + +export interface UrlObject { + protocol?: string; + host?: string; + path?: string[]; + query?: QueryParams; + hash?: string; +} + +/** + * Parse url string into url object. + * @return UrlObject + */ +export function parse(url: string): UrlObject; + +/** + * Stringify url object into url string. + * @return string + */ +export function stringify(urlObject: UrlObject): string; diff --git a/types/ale-url-parser/tsconfig.json b/types/ale-url-parser/tsconfig.json new file mode 100644 index 0000000000..2d18200901 --- /dev/null +++ b/types/ale-url-parser/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", + "ale-url-parser-tests.ts" + ] +} diff --git a/types/ale-url-parser/tslint.json b/types/ale-url-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ale-url-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index a43a8a3b79..cbd98d253a 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -21,6 +21,7 @@ let _algoliaResponse: Response = { processingTimeMS: 32, query: '', params: '', + index: '', }; let _clientOptions: ClientOptions = { @@ -103,7 +104,7 @@ let _algoliaQueryParameters: QueryParameters = { filters: '', attributesToRetrieve: [''], restrictSearchableAttributes: [''], - facets: '', + facets: [''], facetingAfterDistinct: true, maxValuesPerFacet: 2, attributesToHighlight: [''], @@ -121,28 +122,29 @@ let _algoliaQueryParameters: QueryParameters = { typoTolerance: false, allowTyposOnNumericTokens: false, ignorePlurals: false, - disableTypoToleranceOnAttributes: '', + disableTypoToleranceOnAttributes: [''], aroundLatLng: '', aroundLatLngViaIP: '', aroundRadius: 0, aroundPrecision: 0, minimumAroundRadius: 0, insideBoundingBox: [[0]], - queryType: '', + queryType: 'prefixAll', insidePolygon: [[0]], - removeWordsIfNoResults: '', + removeWordsIfNoResults: 'firstWords', advancedSyntax: false, optionalWords: [''], removeStopWords: [''], disableExactOnAttributes: [''], - exactOnSingleWordQuery: '', - alternativesAsExact: true, + exactOnSingleWordQuery: 'attribute', + alternativesAsExact: ["ignorePlurals"], distinct: 0, getRankingInfo: false, numericAttributesToIndex: [''], + numericAttributesForFiltering: [''], numericFilters: [''], - tagFilters: '', - facetFilters: '', + tagFilters: [''], + facetFilters: [''], analytics: false, analyticsTags: [''], synonyms: true, @@ -172,11 +174,11 @@ index.partialUpdateObjects([{}], false).then(() => {}); let indexName : string = index.indexName; // complete copy -client.copyIndex('from', 'to').then(()=>{}) -client.copyIndex('from', 'to', ()=> {}) +client.copyIndex('from', 'to').then(()=>{}); +client.copyIndex('from', 'to', ()=> {}); // with scope -client.copyIndex('from', 'to', ['settings']).then(()=>{}) -client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {}) +client.copyIndex('from', 'to', ['settings']).then(()=>{}); +client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {}); // Browsing const browser = index.browseAll(); @@ -199,9 +201,11 @@ browser.on('error', function onError(err) { throw err; }); -browser.stop() +browser.stop(); index.browse("", { advancedSyntax: false, attributesToRetrieve: ['dogs'] -}) +}); +client.copyIndex('from', 'to', ['settings']).then(()=>{}); +client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {}); diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index bcf19b9230..04291996ba 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -4,6 +4,7 @@ // Haroen Viaene // Aurélien Hervé // Samuel Vaillant +// Kai Eichinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -1122,120 +1123,121 @@ declare namespace algoliasearch { userToken?: string; } interface QueryParameters { + /** + * Query string used to perform the search + * default: '' + * https://www.algolia.com/doc/api-reference/api-parameters/query/ + */ + query?: string; + /** + * Filter the query with numeric, facet or/and tag filters + * default: "" + * https://www.algolia.com/doc/api-reference/api-parameters/filters/ + */ + filters?: string; + /** + * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. + * default: * + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/ + */ + attributesToRetrieve?: string[]; + /** + * List of attributes you want to use for textual search + * default: attributeToIndex + * https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/ + */ + restrictSearchableAttributes?: string[]; + /** + * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facets/ + */ + facets?: string[]; /** - * Query string used to perform the search - * default: '' - * https://github.com/algolia/algoliasearch-client-js#query - */ - query?: string; - /** - * Filter the query with numeric, facet or/and tag filters - * default: "" - * https://github.com/algolia/algoliasearch-client-js#filters - */ - filters?: string; - /** - * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. - * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve - */ - attributesToRetrieve?: string[]; - /** - * List of attributes you want to use for textual search - * default: attributeToIndex - * https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes - */ - restrictSearchableAttributes?: string[]; - /** - * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes - * default: "" - * https://github.com/algolia/algoliasearch-client-js#facets - */ - facets?: string | string[]; - /** * Force faceting to be applied after de-duplication (via the Distinct setting). - * When using the distinct setting in combination with faceting, facet counts may be higher than expected. - * This is because the engine, by default, computes faceting before applying de-duplication (distinct). + * When using the distinct setting in combination with faceting, facet counts may be higher than expected. + * This is because the engine, by default, computes faceting before applying de-duplication (distinct). * When facetingAfterDistinct is set to true, the engine calculates faceting after the de-duplication has been applied. * default "" + * https://www.algolia.com/doc/api-reference/api-parameters/facetingAfterDistinct/ */ facetingAfterDistinct?: boolean; /** * Limit the number of facet values returned for each facet. - * default: "" - * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + * default: 100 + * https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/ */ maxValuesPerFacet?: number; /** * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/ */ attributesToHighlight?: string[]; /** * Default list of attributes to snippet alongside the number of words to return * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/ */ attributesToSnippet?: string[]; /** * Specify the string that is inserted before the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightpretag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/ */ highlightPreTag?: string; /** * Specify the string that is inserted after the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightposttag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/ */ highlightPostTag?: string; /** * String used as an ellipsis indicator when a snippet is truncated. * default: … - * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + * https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/ */ snippetEllipsisText?: string; /** * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets * default: false - * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + * https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/ */ restrictHighlightAndSnippetArrays?: boolean; /** * Pagination parameter used to select the number of hits per page * default: 20 - * https://github.com/algolia/algoliasearch-client-js#hitsperpage + * https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/ */ hitsPerPage?: number; /** * Pagination parameter used to select the page to retrieve. * default: 0 - * https://github.com/algolia/algoliasearch-client-js#page + * https://www.algolia.com/doc/api-reference/api-parameters/page/ */ page?: number; /** * Offset of the first hit to return * default: null - * https://github.com/algolia/algoliasearch-client-js#offset + * https://www.algolia.com/doc/api-reference/api-parameters/offset/ */ offset?: number; /** * Number of hits to return. * default: null - * https://github.com/algolia/algoliasearch-client-js#length + * https://www.algolia.com/doc/api-reference/api-parameters/length/ */ length?: number; /** * The minimum number of characters needed to accept one typo. * default: 4 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/ */ minWordSizefor1Typo?: number; /** * The minimum number of characters needed to accept two typo. * fault: 8 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/ */ minWordSizefor2Typos?: number; /** @@ -1245,62 +1247,62 @@ declare namespace algoliasearch { * 'false' The typo tolerance is disabled. All results with typos will be hidden. * 'min' Only keep results with the minimum number of typos * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/ */ typoTolerance?: boolean; /** * If set to false, disables typo tolerance on numeric tokens (numbers). * default: - * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + * https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/ */ allowTyposOnNumericTokens?: boolean; /** * If set to true, plural won't be considered as a typo * default: false - * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + * https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/ */ ignorePlurals?: boolean; /** * List of attributes on which you want to disable typo tolerance - * default: "" - * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/ */ - disableTypoToleranceOnAttributes?: string; + disableTypoToleranceOnAttributes?: string[]; /** * Search for entries around a given location * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlng + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/ */ aroundLatLng?: string; /** * Search for entries around a given latitude/longitude automatically computed from user IP address. * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/ */ aroundLatLngViaIP?: string; /** * Control the radius associated with a geo search. Defined in meters. * default: null * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area - * https://github.com/algolia/algoliasearch-client-js#aroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/ */ aroundRadius?: number | 'all'; /** * Control the precision of a geo search * default: null - * https://github.com/algolia/algoliasearch-client-js#aroundprecision + * https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/ */ aroundPrecision?: number; /** * Define the minimum radius used for a geo search when aroundRadius is not set. * default: null - * https://github.com/algolia/algoliasearch-client-js#minimumaroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/ */ minimumAroundRadius?: number; /** * Search entries inside a given area defined by the two extreme points of a rectangle * default: null - * https://github.com/algolia/algoliasearch-client-js#insideboundingbox + * https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/ */ insideBoundingBox?: number[][]; /** @@ -1309,13 +1311,13 @@ declare namespace algoliasearch { * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. - * https://github.com/algolia/algoliasearch-client-js#querytype + * https://www.algolia.com/doc/api-reference/api-parameters/queryType/ */ - queryType?: any; + queryType?: "prefixAll"|"prefixLast"|"prefixNone"; /** * Search entries inside a given area defined by a set of points * defauly: '' - * https://github.com/algolia/algoliasearch-client-js#insidepolygon + * https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/ */ insidePolygon?: number[][]; /** @@ -1325,19 +1327,19 @@ declare namespace algoliasearch { * 'firstWords' When a query does not return any results, the first word will be added as optional * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional * 'none' No specific processing is done when a query does not return any results - * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + * https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/ */ - removeWordsIfNoResults?: string; + removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional"; /** * Enables the advanced query syntax * default: false - * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + * https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/ */ advancedSyntax?: boolean; /** * A string that contains the comma separated list of words that should be considered as optional when found in the query * default: [] - * https://github.com/algolia/algoliasearch-client-js#optionalwords + * https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/ */ optionalWords?: string[]; /** @@ -1345,13 +1347,13 @@ declare namespace algoliasearch { * default: false * true|false: enable or disable stop words for all 41 supported languages; or * a list of language ISO codes (as a comma-separated string) for which stop words should be enable - * https://github.com/algolia/algoliasearch-client-js#removestopwords + * https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/ */ - removeStopWords?: string[]; + removeStopWords?: boolean|string[]; /** * List of attributes on which you want to disable the computation of exact criteria * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + * https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/ */ disableExactOnAttributes?: string[]; /** @@ -1360,81 +1362,90 @@ declare namespace algoliasearch { * 'none': no exact on single word query * 'word': exact set to 1 if the query word is found in the record * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query - * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + * https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/ */ - exactOnSingleWordQuery?: string; + exactOnSingleWordQuery?: "attribute"|"none"|"word"; /** * Specify the list of approximation that should be considered as an exact match in the ranking formula * default: ['ignorePlurals', 'singleWordSynonym'] * 'ignorePlurals': alternative words added by the ignorePlurals feature * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") * 'multiWordsSynonym': multiple-words synonym - * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + * https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/ */ - alternativesAsExact?: any; + alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">; /** * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. - * https://github.com/algolia/algoliasearch-client-js#distinct + * https://www.algolia.com/doc/api-reference/api-parameters/distinct/ */ - distinct?: any; + distinct?: number|boolean; /** * If set to true, the result hits will contain ranking information in the _rankingInfo attribute. * default: false - * https://github.com/algolia/algoliasearch-client-js#getrankinginfo + * https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/ */ getRankingInfo?: boolean; /** + * @deprecated Use `numericAttributesForFiltering` instead * All numerical attributes are automatically indexed as numerical filters * default: '' - * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ */ numericAttributesToIndex?: string[]; + /** + * All numerical attributes are automatically indexed as numerical filters + * default: '' + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ + */ + numericAttributesForFiltering?: string[]; /** * @deprecated please use filters instead * A string that contains the comma separated list of numeric filters you want to apply. - * https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated + * https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/ */ numericFilters?: string[]; /** * @deprecated + * * Filter the query by a set of tags. - * https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/ */ - tagFilters?: string; + tagFilters?: string[]; /** - * @deprecated * Filter the query by a set of facets. - * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ */ - facetFilters?: string | string[] + facetFilters?: string[]|string[][]; /** * If set to false, this query will not be taken into account in the analytics feature. * default true - * https://github.com/algolia/algoliasearch-client-js#analytics + * https://www.algolia.com/doc/api-reference/api-parameters/analytics/ */ analytics?: boolean; /** * If set, tag your query with the specified identifiers - * default: null - * https://github.com/algolia/algoliasearch-client-js#analyticstags + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/ */ analyticsTags?: string[]; /** * If set to false, the search will not use the synonyms defined for the targeted index. * default: true - * https://github.com/algolia/algoliasearch-client-js#synonyms + * https://www.algolia.com/doc/api-reference/api-parameters/synonyms/ */ synonyms?: boolean; /** * If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result. * default: true - * https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight + * https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/ */ replaceSynonymsInHighlight?: boolean; /** * Configure the precision of the proximity ranking criterion * default: 1 - * https://github.com/algolia/algoliasearch-client-js#minproximity + * https://www.algolia.com/doc/api-reference/api-parameters/minProximity/ */ minProximity?: number; @@ -1487,7 +1498,7 @@ declare namespace algoliasearch { interface Task { taskID: number; createdAt: string; - objectID?: string; + objectID?: string; } interface TaskStatus { @@ -1770,42 +1781,42 @@ declare namespace algoliasearch { interface Response { /** * Contains all the hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hits: any[]; /** * Current page - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ page: number; /** * Number of total hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbHits: number; /** * Number of pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbPages: number; /** * Number of hits per pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hitsPerPage: number; /** * Engine processing time (excluding network transfer) - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ processingTimeMS: number; /** * Query used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ query: string; /** * GET parameters used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ params: string; facets?: { @@ -1819,6 +1830,16 @@ declare namespace algoliasearch { sum: number, }; }; + /** + * The index name is only set when searching multiple indices. + * https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response + */ + index?: string; + /** + * The cursor is only set when browsing the index. + * https://www.algolia.com/doc/api-reference/api-methods/browse/ + */ + cursor?: string; } interface MultiResponse { diff --git a/types/algoliasearch/lite/index.d.ts b/types/algoliasearch/lite/index.d.ts index 4db3ce12d3..ce58d6a428 100644 --- a/types/algoliasearch/lite/index.d.ts +++ b/types/algoliasearch/lite/index.d.ts @@ -5,6 +5,7 @@ // Aurélien Hervé // Samuel Vaillant // Claas Brüggemann +// Kai Eichinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -214,109 +215,109 @@ declare namespace algoliasearch { /** * Query string used to perform the search * default: '' - * https://github.com/algolia/algoliasearch-client-js#query + * https://www.algolia.com/doc/api-reference/api-parameters/query/ */ query?: string; /** * Filter the query with numeric, facet or/and tag filters * default: "" - * https://github.com/algolia/algoliasearch-client-js#filters + * https://www.algolia.com/doc/api-reference/api-parameters/filters/ */ filters?: string; /** * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/ */ attributesToRetrieve?: string[]; /** * List of attributes you want to use for textual search * default: attributeToIndex - * https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes + * https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/ */ restrictSearchableAttributes?: string[]; /** * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes - * default: "" - * https://github.com/algolia/algoliasearch-client-js#facets + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facets/ */ - facets?: string; + facets?: string[]; /** * Limit the number of facet values returned for each facet. - * default: "" - * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + * default: 100 + * https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/ */ maxValuesPerFacet?: number; /** * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/ */ attributesToHighlight?: string[]; /** * Default list of attributes to snippet alongside the number of words to return * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/ */ attributesToSnippet?: string[]; /** * Specify the string that is inserted before the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightpretag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/ */ highlightPreTag?: string; /** * Specify the string that is inserted after the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightposttag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/ */ highlightPostTag?: string; /** * String used as an ellipsis indicator when a snippet is truncated. * default: … - * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + * https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/ */ snippetEllipsisText?: string; /** * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets * default: false - * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + * https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/ */ restrictHighlightAndSnippetArrays?: boolean; /** * Pagination parameter used to select the number of hits per page * default: 20 - * https://github.com/algolia/algoliasearch-client-js#hitsperpage + * https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/ */ hitsPerPage?: number; /** * Pagination parameter used to select the page to retrieve. * default: 0 - * https://github.com/algolia/algoliasearch-client-js#page + * https://www.algolia.com/doc/api-reference/api-parameters/page/ */ page?: number; /** * Offset of the first hit to return * default: null - * https://github.com/algolia/algoliasearch-client-js#offset + * https://www.algolia.com/doc/api-reference/api-parameters/offset/ */ offset?: number; /** * Number of hits to return. * default: null - * https://github.com/algolia/algoliasearch-client-js#length + * https://www.algolia.com/doc/api-reference/api-parameters/length/ */ length?: number; /** * The minimum number of characters needed to accept one typo. * default: 4 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/ */ minWordSizefor1Typo?: number; /** * The minimum number of characters needed to accept two typo. * fault: 8 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/ */ minWordSizefor2Typos?: number; /** @@ -326,62 +327,62 @@ declare namespace algoliasearch { * 'false' The typo tolerance is disabled. All results with typos will be hidden. * 'min' Only keep results with the minimum number of typos * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/ */ typoTolerance?: boolean; /** * If set to false, disables typo tolerance on numeric tokens (numbers). * default: - * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + * https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/ */ allowTyposOnNumericTokens?: boolean; /** * If set to true, plural won't be considered as a typo * default: false - * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + * https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/ */ ignorePlurals?: boolean; /** * List of attributes on which you want to disable typo tolerance - * default: "" - * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/ */ - disableTypoToleranceOnAttributes?: string; + disableTypoToleranceOnAttributes?: string[]; /** * Search for entries around a given location * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlng + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/ */ aroundLatLng?: string; /** * Search for entries around a given latitude/longitude automatically computed from user IP address. * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/ */ aroundLatLngViaIP?: string; /** * Control the radius associated with a geo search. Defined in meters. * default: null * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area - * https://github.com/algolia/algoliasearch-client-js#aroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/ */ aroundRadius?: number | 'all'; /** * Control the precision of a geo search * default: null - * https://github.com/algolia/algoliasearch-client-js#aroundprecision + * https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/ */ aroundPrecision?: number; /** * Define the minimum radius used for a geo search when aroundRadius is not set. * default: null - * https://github.com/algolia/algoliasearch-client-js#minimumaroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/ */ minimumAroundRadius?: number; /** * Search entries inside a given area defined by the two extreme points of a rectangle * default: null - * https://github.com/algolia/algoliasearch-client-js#insideboundingbox + * https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/ */ insideBoundingBox?: number[][]; /** @@ -390,13 +391,13 @@ declare namespace algoliasearch { * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. - * https://github.com/algolia/algoliasearch-client-js#querytype + * https://www.algolia.com/doc/api-reference/api-parameters/queryType/ */ - queryType?: any; + queryType?: "prefixAll"|"prefixLast"|"prefixNone"; /** * Search entries inside a given area defined by a set of points * defauly: '' - * https://github.com/algolia/algoliasearch-client-js#insidepolygon + * https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/ */ insidePolygon?: number[][]; /** @@ -406,19 +407,19 @@ declare namespace algoliasearch { * 'firstWords' When a query does not return any results, the first word will be added as optional * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional * 'none' No specific processing is done when a query does not return any results - * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + * https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/ */ - removeWordsIfNoResults?: string; + removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional"; /** * Enables the advanced query syntax * default: false - * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + * https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/ */ advancedSyntax?: boolean; /** * A string that contains the comma separated list of words that should be considered as optional when found in the query * default: [] - * https://github.com/algolia/algoliasearch-client-js#optionalwords + * https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/ */ optionalWords?: string[]; /** @@ -426,13 +427,13 @@ declare namespace algoliasearch { * default: false * true|false: enable or disable stop words for all 41 supported languages; or * a list of language ISO codes (as a comma-separated string) for which stop words should be enable - * https://github.com/algolia/algoliasearch-client-js#removestopwords + * https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/ */ - removeStopWords?: string[]; + removeStopWords?: boolean|string[]; /** * List of attributes on which you want to disable the computation of exact criteria * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + * https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/ */ disableExactOnAttributes?: string[]; /** @@ -441,81 +442,90 @@ declare namespace algoliasearch { * 'none': no exact on single word query * 'word': exact set to 1 if the query word is found in the record * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query - * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + * https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/ */ - exactOnSingleWordQuery?: string; + exactOnSingleWordQuery?: "attribute"|"none"|"word"; /** * Specify the list of approximation that should be considered as an exact match in the ranking formula * default: ['ignorePlurals', 'singleWordSynonym'] * 'ignorePlurals': alternative words added by the ignorePlurals feature * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") * 'multiWordsSynonym': multiple-words synonym - * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + * https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/ */ - alternativesAsExact?: any; + alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">; /** * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. - * https://github.com/algolia/algoliasearch-client-js#distinct + * https://www.algolia.com/doc/api-reference/api-parameters/distinct/ */ - distinct?: any; + distinct?: number|boolean; /** * If set to true, the result hits will contain ranking information in the _rankingInfo attribute. * default: false - * https://github.com/algolia/algoliasearch-client-js#getrankinginfo + * https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/ */ getRankingInfo?: boolean; /** + * @deprecated Use `numericAttributesForFiltering` instead * All numerical attributes are automatically indexed as numerical filters * default: '' - * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ */ numericAttributesToIndex?: string[]; + /** + * All numerical attributes are automatically indexed as numerical filters + * default: '' + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ + */ + numericAttributesForFiltering?: string[]; /** * @deprecated please use filters instead * A string that contains the comma separated list of numeric filters you want to apply. - * https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated + * https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/ */ numericFilters?: string[]; /** * @deprecated + * * Filter the query by a set of tags. - * https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/ */ - tagFilters?: string; + tagFilters?: string[]; /** - * @deprecated * Filter the query by a set of facets. - * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ */ - facetFilters?: string; + facetFilters?: string[]|string[][]; /** * If set to false, this query will not be taken into account in the analytics feature. * default true - * https://github.com/algolia/algoliasearch-client-js#analytics + * https://www.algolia.com/doc/api-reference/api-parameters/analytics/ */ analytics?: boolean; /** * If set, tag your query with the specified identifiers - * default: null - * https://github.com/algolia/algoliasearch-client-js#analyticstags + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/ */ analyticsTags?: string[]; /** * If set to false, the search will not use the synonyms defined for the targeted index. * default: true - * https://github.com/algolia/algoliasearch-client-js#synonyms + * https://www.algolia.com/doc/api-reference/api-parameters/synonyms/ */ synonyms?: boolean; /** * If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result. * default: true - * https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight + * https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/ */ replaceSynonymsInHighlight?: boolean; /** * Configure the precision of the proximity ranking criterion * default: 1 - * https://github.com/algolia/algoliasearch-client-js#minproximity + * https://www.algolia.com/doc/api-reference/api-parameters/minProximity/ */ minProximity?: number; @@ -545,42 +555,42 @@ declare namespace algoliasearch { interface Response { /** * Contains all the hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hits: any[]; /** * Current page - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ page: number; /** * Number of total hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbHits: number; /** * Number of pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbPages: number; /** * Number of hits per pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hitsPerPage: number; /** * Engine processing time (excluding network transfer) - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ processingTimeMS: number; /** * Query used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ query: string; /** * GET parameters used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ params: string; facets?: { @@ -594,6 +604,16 @@ declare namespace algoliasearch { sum: number, }; }; + /** + * The index name is only set when searching multiple indices. + * https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response + */ + index?: string; + /** + * The cursor is only set when browsing the index. + * https://www.algolia.com/doc/api-reference/api-methods/browse/ + */ + cursor?: string; } interface MultiResponse { diff --git a/types/colresizable/colresizable-tests.ts b/types/colresizable/colresizable-tests.ts new file mode 100644 index 0000000000..9fc62512c1 --- /dev/null +++ b/types/colresizable/colresizable-tests.ts @@ -0,0 +1,61 @@ +$("#table").colResizable(); // $ExpectType JQuery + +$("#table").colResizable({ + resizeMode: "fit", + disable: false, + disabledColumns: [1, 2, 3], + liveDrag: true, + postbackSafe: false, + partialRefresh: true, + headerOnly: false, + gripInnerHtml: "", + draggingClass: ".myClass", + minWidth: 100, + hoverCursor: 'pointer', + dragCursor: 'e-resize', + flush: false, + marginLeft: "14px", + marginRight: "auto", + fixed: false, + + onResize(evt) { + evt.currentTarget; // $ExpectType Element + }, + onDrag(evt) { + evt.currentTarget; // $ExpectType Element + } +}); + +// Samples at http://www.bacubacu.com/colresizable +function onSampleResized(e: JQueryMouseEventObject) { + const table = $(e.currentTarget); // reference to the resized table +} + +$("#sample").colResizable({ + liveDrag: true, + gripInnerHtml: "
", + draggingClass: "dragging", + onResize: onSampleResized +}); + +function postbackSample() { + $("#updatePanelSample").colResizable({ + liveDrag: true, + postbackSafe: true, + partialRefresh: true + }); +} + +$("#flexSample").colResizable({resizeMode: 'flex'}); + +$("#overflowSample").colResizable({resizeMode: 'overflow'}); + +function onSlide() {} + +$("#sample5").colResizable({ + liveDrag: true, + draggingClass: "rangeDrag", + gripInnerHtml: "
", + onResize: onSlide, + minWidth: 8 +}); diff --git a/types/colresizable/index.d.ts b/types/colresizable/index.d.ts new file mode 100644 index 0000000000..693c40923c --- /dev/null +++ b/types/colresizable/index.d.ts @@ -0,0 +1,149 @@ +// Type definitions for colresizable 1.6 +// Project: http://bacubacu.com/colresizable/ +// Definitions by: Gilles Waeber +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +interface JQuery { + colResizable(param?: colResizable.Settings): JQuery; +} + +declare namespace colResizable { + interface Settings { + /** + * [default: 'fit'] It is used to set how the resize method works. Those are the possible values: + * - 'fit': this is default resizing model, in which resizing a column does not alter table width, which means that when a column is expanded the next one shrinks. + * - 'flex': in this mode tables can change its width and each column can shrink or expand independently if there is enough space in the parent container. + * If there is not enough space, columns will share its width as they are resized. Table will never get bigger than its parent. + * - 'overflow': allows to resize columns with overflow of parent container. + * [version: 1.6] + */ + resizeMode?: 'fit' | 'flex' | 'overflow'; + + /** + * [default: false] When set to true the table layout is updated while dragging column anchors. + * liveDrag enabled is more CPU consuming so it is not recommended for slow computers, specially when dealing with huge or extremely complicated tables. + * [version: 1.0] + */ + liveDrag?: boolean; + + /** + * @deprecated use resizeMode instead + * [default: true] It is used to set how the resize method works. + * In fixed mode resizing a column does not alter total table width, which means that when a column is expanded the next one shrinks. + * If fixed is set to false then table can change its width and each column can shrink or expand independently. + * [version: 1.5] + */ + fixed?: boolean; + + /** + * [default: false] This attribute can be used to specify that the manually selected column widths must remain unaltered after a postback or browser refresh. + * This feature is mainly oriented to those pages created with server-side logic (codebehind), such as PHP or .NET, and it is only compatible with browsers + * with sessionStorage support (all modern browsers). + * However, if you are targeting older browsers (such as IE7 and IE8) you can still emulate sessionStorage using sessionStorage.js. + * It is important to note that some browsers (IE and FF) doesn’t enable the sessionStorage object while running the website directly from the local file system, + * so if you want to test this feature it is recommended to view the website through a web server or use browsers such as Chrome or Opera which doesn’t have this limitation. + * Don't worry about compatibility issues, once your site is up on the internet, all browsers will act in exactly the same way. + * [version: 1.3] + */ + postbackSafe?: boolean; + + /** + * [default: false] This attribute should be set to true if the table is inside of an updatePanel or any other kind of partial page refresh using ajax. + * Table's ID should be same before and after the partial partial refresh. + * [version: 1.5] + */ + partialRefresh?: boolean; + + /** + * [default: false] This attribute can be used to prevent vertical expansion of the column anchors to fit the table height. + * If it is set to true, column handler's size will be bounded to the first row's vertical size. + * [version: 1.2] + */ + headerOnly?: boolean; + + /** + * [default: ""] Its purpose is to allow column anchor customization by defining the HTML to be used in the column grips to provide some visual feedback. + * It can be used in a wide range of ways to obtain very different outputs, and its flexibility can be increased by combining it with the draggingClass attribute. + * [version: 1.0] + */ + gripInnerHtml?: string; + + /** + * [default: (internal class)] This attribute is used as the css class assigned to column anchors while being dragged. It can be used for visual feedback purposes. + * [version: 1.0] + */ + draggingClass?: string; + + /** + * [default: false] When set to true it aims to remove all previously added enhancements such as events and additional DOM elements assigned by this plugin to + * a single or collection of tables. It is required to disable a previously colResized table prior its removal from the document object tree. + * [version: 1.0] + */ + disable?: boolean; + + /** + * [default: [ ] ] An array of column indexes to be excluded, so it will not be possible to drag them manually. + * [version: 1.6] + */ + disabledColumns?: number[]; + + /** + * [default: 15] This value specifies the minimum width (measured in pixels) that is allowed for the columns. + * [version: 1.1] + */ + minWidth?: number; + + /** + * [default: "e-resize"] This attribute can be used to customize the cursor that will be displayed when the user is positioned on the column anchors. + * [version: 1.3] + */ + hoverCursor?: string; + + /** + * [default: "e-resize"] Defines the cursor that will be used while the user is resizing a column. + * [version: 1.3] + */ + dragCursor?: string; + + /** + * [default: false] Flush is only effective when postbackSafe is enabled. + * Its purpose is to remove all previously stored data related to the current table layout to get it back to its original layout preventing width restoration after postback. + * [version: ] + */ + flush?: boolean; + + /** + * [default: null] If the target table contains an explicit margin-left CSS rule, the same value must be used in this attribute (for example: "auto", "20%", "10px"). + * The reason why it is needed it is because most browsers (all except of IE) don’t allow direct access to the current CSS rule applied to an element in + * its original units (such as "%", "em" or "auto" values). + * If you know any workaround which doesn’t involve iteration through all the styles defined in the site and any other external dependencies, please let me know! + * [version: 1.3] + */ + marginLeft?: string; + + /** + * [default: null] It behaves in exactly the same way than the marginLeft attribute but applied to the right margin. + * [version: 1.3] + */ + marginRight?: string; + + /** + * If a callback function is supplied it will be fired when the user has ended dragging a column anchor altering the previous table layout. + * The callback function can obtain a reference to the updated table through the currentTarget attribute of the event retrieved by parameters + * [version: 1.0] + */ + onResize?: FunctionCallback; + + /** + * This event is fired while dragging a column anchor if liveDrag is enabled. It can be useful if the table is being used as a multiple range slider. + * The callback function can obtain a reference to the updated table through the currentTarget attribute of the event retrieved by parameters + * [version: 1.1] + */ + onDrag?: FunctionCallback; + } + + type FunctionCallback = (e: JQueryMouseEventObject) => void; +} diff --git a/types/colresizable/tsconfig.json b/types/colresizable/tsconfig.json new file mode 100644 index 0000000000..35bf902824 --- /dev/null +++ b/types/colresizable/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", + "colresizable-tests.ts" + ] +} diff --git a/types/colresizable/tslint.json b/types/colresizable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/colresizable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cytoscape/cytoscape-tests.ts b/types/cytoscape/cytoscape-tests.ts index 0cffa42b31..dc0607a3c3 100644 --- a/types/cytoscape/cytoscape-tests.ts +++ b/types/cytoscape/cytoscape-tests.ts @@ -36,7 +36,8 @@ const showAllStyle: cytoscape.Stylesheet[] = [ 'text-halign': 'center', shape: 'rectangle', 'min-zoomed-font-size': 20, - opacity: 1 + opacity: 1, + width: 'mapData(weight, 40, 80, 20, 60)' } }, { @@ -125,7 +126,7 @@ cy.on('zoom', (event) => { cy.off('zoom'); // events(cy); - TODO -cy.add({ data: { id: 'g' }, position: {x: 200, y: 150} }); +cy.add({ data: { id: 'g', someOtherKey: 'value' }, position: {x: 200, y: 150} }); cy.add([ { data: { id: 'h' }, position: {x: 250, y: 100} } ]); diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index 59482ad507..7ea05577be 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -133,6 +133,8 @@ declare namespace cytoscape { } interface EdgeDataDefinition extends ElementDataDefinition { + id?: string; + /** * the source node id (edge comes from this node) */ @@ -141,6 +143,8 @@ declare namespace cytoscape { * the target node id (edge goes to this node) */ target: string; + + [key: string]: any; } interface NodeDefinition extends ElementDefinition { @@ -148,7 +152,9 @@ declare namespace cytoscape { } interface NodeDataDefinition extends ElementDataDefinition { + id?: string; parent?: string; + [key: string]: any; } interface CytoscapeOptions { @@ -3445,13 +3451,13 @@ declare namespace cytoscape { * This property can take on the special value label * so the width is automatically based on the node’s label. */ - "width"?: number | "label"; + "width"?: number | string; /** * The height of the node’s body. * This property can take on the special value label * so the height is automatically based on the node’s label. */ - "height"?: number | "label"; + "height"?: number | string; /** * The shape of the node’s body. */ @@ -3624,7 +3630,7 @@ declare namespace cytoscape { /** * The width of an edge’s line. */ - "width"?: number | "label"; + "width"?: number | string; /** * The curving method used to separate two or more edges between two nodes; * may be diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index 5c1c1bfae6..aa5d93858b 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -823,6 +823,35 @@ declare namespace Dockerode { context: string; src: string[]; } + + interface DockerVersion { + ApiVersion: string; + Arch: string; + BuildTime: Date; + Components: Array<{ + Details: { + ApiVersion: string; + Arch: string; + BuilTime: Date; + Experimental: string; + GitCommit: string; + GoVersion: string; + KernelVersion: string; + Os: string; + }; + Name: string; + Version: string; + }>; + GitCommit: string; + GoVersion: string; + KernelVersion: string; + MinAPIVersion: string; + Os: string; + Platform: { + Name: string; + }; + Version: string; + } } type Callback = (error?: any, result?: T) => void; @@ -949,8 +978,8 @@ declare class Dockerode { df(callback: Callback): void; df(): Promise; - version(callback: Callback): void; - version(): Promise; + version(callback: Callback): void; + version(): Promise; ping(callback: Callback): void; ping(): Promise; diff --git a/types/download/tsconfig.json b/types/download/tsconfig.json index edb8b7f471..809bed13d2 100644 --- a/types/download/tsconfig.json +++ b/types/download/tsconfig.json @@ -14,10 +14,15 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "paths": { + "got": [ + "got/v8" + ] + } }, "files": [ "index.d.ts", "download-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/factory-girl/factory-girl-tests.ts b/types/factory-girl/factory-girl-tests.ts new file mode 100644 index 0000000000..e996df56af --- /dev/null +++ b/types/factory-girl/factory-girl-tests.ts @@ -0,0 +1,94 @@ +import * as factory from "factory-girl"; + +interface User { + username?: string; + score?: number; + email?: string; + roles?: Role[]; + creditCard?: any; + boss?: User; +} + +interface Role { + id?: number; + name?: string; +} + +interface SuperUser extends User { + superpower: string; +} + +// Testing setAdapter +factory.setAdapter("my-adapter", "my-adapter-name"); + +// Testing define with seq, assoc, assocAttrs, assocMany +factory.define("user", {}, { + username: "Bob", + score: factory.seq("User.score", score => score + 1), + email: factory.seq("User.email", num => `email-${1}@users.com`), + roles: factory.assocMany("Role", 3, "id"), + creditCard: factory.assocAttrs("CreditCard", "creditCard", { number: "1234" }), + boss: factory.assoc("User", "boss") +}, { + afterBuild: (model, attrs, options) => {}, + afterCreate: (model, attrs, options) => {} +}); + +// Testing extend, with and without options +factory.extend("user", "superuser", { superpower: "flight" }); + +factory.extend("user", "superuser", { superpower: "flight" }, { + afterBuild: (model, attrs, options) => {}, + afterCreate: (model, attrs, options) => {} +}); + +// Testing attrs, with and without attributes +factory.attrs("user").then(attrs => null); +factory.attrs("user", { score: 10 }).then(attrs => null); + +// Testing attrsMany, with and without attributes +factory.attrsMany("user", 2).then(attrs => null); +factory.attrsMany("user", 2, [{ score: 10 }]).then(attrs => null); + +// Testing build, with and without attributes +factory.build("user").then(user => user.username); +factory.build("user", { score: 10 }).then(user => user.username); + +// Testing buildMany, with and without attributes and options +factory.buildMany("user", 3) + .then(users => users.map(user => user.username)); + +factory.buildMany("user", 3, { username: "John McClane" }) + .then(users => users.map(user => user.username)); + +// Testing buildMany with a list of attributes +factory.buildMany("user", [ + { username: "Jake Blues" }, + { username: "Elwood Blues" } +]).then(users => users.map(user => user.username)); + +// Testing create, with and without attributes +factory.create("user").then(user => user.username); +factory.create("user", { score: 10 }).then(user => user.username); + +// Testing createMany, with and without attributes +factory.createMany("user", 3) + .then(users => users.map(user => user.username)); + +factory.createMany("user", 3, { username: "Rocky Balboa" }) + .then(users => users.map(user => user.username)); + +// Testing createMany with options +factory.createMany("user", 3, { username: "John Rambo" }, { + afterBuild: (model, attrs, options) => {}, + afterCreate: (model, attrs, options) => {} +}).then(users => users.map(user => user.username)); + +// Testing createMany with a list of attributes +factory.createMany("user", [ + { username: "Emmett Brown" }, + { username: "Marty McFly" } +]).then(users => users.map(user => user.username)); + +// Testing cleanUp +factory.cleanUp(); diff --git a/types/factory-girl/index.d.ts b/types/factory-girl/index.d.ts new file mode 100644 index 0000000000..ebd6583885 --- /dev/null +++ b/types/factory-girl/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for factory-girl 5.0 +// Project: https://github.com/aexmachina/factory-girl#readme +// Definitions by: Stack Builders +// Sebastián Estrella +// Luis Fernando Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare const factory: factory.Static; + +declare namespace factory { + interface Static { + /** + * Associate the factory to other model + */ + assoc(model: string, attributes: string): any; + + /** + * Associate the factory to a model that's not persisted + */ + assocAttrs(name: string, key?: string, attributes?: any): any; + + /** + * Associate the factory to multiple other models + */ + assocMany(model: string, num: number, attributes: string): any[]; + + /** + * Generates and returns model attributes as an object hash instead of the model instance + */ + attrs(name: string, attrs?: Partial): Promise; + + /** + * Generates and returns a collection of model attributes as an object hash instead of the model instance + */ + attrsMany(name: string, num: number, attrs?: Array>): Promise; + + /** + * Builds a new model instance that is not persisted + */ + build(name: string, attrs?: Partial): Promise; + + /** + * Builds an array of model instances that are persisted + */ + buildMany(name: string, num: number, attrs?: Partial): Promise; + buildMany(name: string, attrs?: Array>): Promise; + + /** + * Destroys all of the created models + */ + cleanUp(): void; + + /** + * Builds a new model instance that is persisted + */ + create(name: string, attrs?: Partial): Promise; + + /** + * Builds an array of model instances that are persisted + */ + createMany(name: string, num: number, attrs?: Partial, buildOptions?: Options): Promise; + createMany(name: string, attrs?: Array>, buildOptions?: Options): Promise; + + /** + * Define a new factory with a set of options + */ + define(name: string, model: any, attrs: T, options?: Options): void; + + /** + * Extends a factory + */ + extend(parent: string, name: string, initializer: any, options?: Options): any; + + /** + * Generate values sequentially inside a factory + */ + seq(name: string, fn: (sequence: number) => T): T; + + /** + * Register an adapter, either as default or tied to a specific model + */ + setAdapter(adapter: any, name?: string): void; + } + + interface Options { + afterBuild?: Hook; + afterCreate?: Hook; + } + + type Hook = (model: any, attrs: T[], options: any) => void; +} + +export = factory; +export as namespace factory; diff --git a/types/factory-girl/tsconfig.json b/types/factory-girl/tsconfig.json new file mode 100644 index 0000000000..c6bb5f369e --- /dev/null +++ b/types/factory-girl/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "factory-girl-tests.ts" + ] +} diff --git a/types/factory-girl/tslint.json b/types/factory-girl/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/factory-girl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index 610ac87c26..934adfc9a8 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -7,6 +7,7 @@ import * as http from 'http'; import * as https from 'https'; import * as url from 'url'; import QuickLRU = require('quick-lru'); +import tough = require('tough-cookie'); let str: string; let buf: Buffer; @@ -260,3 +261,11 @@ got(new url.URL('http://todomvc.com')); got(url.parse('http://todomvc.com')); got('https://todomvc.com', { rejectUnauthorized: false }); + +got('/examples/angularjs', { baseUrl: 'http://todomvc.com' }); +got('http://todomvc.com', { headers: { foo: 'bar'} }); +got('http://todomvc.com', { cookieJar: new tough.CookieJar() }); +got('http://todomvc.com', { retry: 2 }); +got('http://todomvc.com', { retry: { retries: 2, methods: ['GET'], statusCodes: [408, 504], maxRetryAfter: 1 } }); +got('http://todomvc.com', { throwHttpErrors: false }); +got('http://todomvc.com', { hooks: { beforeRequest: [ () => 'foo']} }); diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 775985e581..6b0929fdcf 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for got 8.3 +// Type definitions for got 9.2 // Project: https://github.com/sindresorhus/got#readme // Definitions by: BendingBender // Linus Unnebäck // Konstantin Ikonnikov +// Stijn Van Nieuwenhuyse // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -12,6 +13,7 @@ import { Url, URL } from 'url'; import * as http from 'http'; import * as https from 'https'; import * as nodeStream from 'stream'; +import { CookieJar } from 'tough-cookie'; export = got; @@ -95,8 +97,12 @@ declare namespace got { type GotUrl = string | https.RequestOptions | Url | URL; + type Hook = (options: T) => any; + type Hooks = Record<'beforeRequest', Array>>; + interface GotBodyOptions extends GotOptions { body?: string | Buffer | nodeStream.Readable; + hooks?: Hooks>; } interface GotJSONOptions extends GotOptions { @@ -104,25 +110,29 @@ declare namespace got { body?: object; form?: boolean; json: true; + hooks?: Hooks; } interface GotFormOptions extends GotOptions { body?: {[key: string]: any}; form: true; json?: boolean; + hooks?: Hooks>; } interface GotOptions extends InternalRequestOptions { + baseUrl?: string; + cookieJar?: CookieJar; encoding?: E; query?: string | object; timeout?: number | TimeoutOptions; - retries?: number | RetryFunction; + retry?: number | RetryOptions; followRedirect?: boolean; decompress?: boolean; useElectronNet?: boolean; - cache?: Cache; - agent?: http.Agent | boolean | AgentOptions; throwHttpErrors?: boolean; + agent?: http.Agent | boolean | AgentOptions; + cache?: Cache; } interface TimeoutOptions { @@ -131,13 +141,20 @@ declare namespace got { request?: number; } + type RetryFunction = (retry: number, error: any) => number; + + interface RetryOptions { + retries?: number | RetryFunction; + methods?: Array<'GET' | 'PUT' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE'>; + statusCodes?: Array<408 | 413 | 429 | 500 | 502 | 503 | 504>; + maxRetryAfter?: number; + } + interface AgentOptions { http: http.Agent; https: https.Agent; } - type RetryFunction = (retry: number, error: any) => number; - interface Cache { set(key: string, value: any, ttl?: number): any; get(key: string): any; diff --git a/types/got/tslint.json b/types/got/tslint.json index 4a4f94c041..08b1465cd6 100644 --- a/types/got/tslint.json +++ b/types/got/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO "unified-signatures": false } } diff --git a/types/got/v8/got-tests.ts b/types/got/v8/got-tests.ts new file mode 100644 index 0000000000..610ac87c26 --- /dev/null +++ b/types/got/v8/got-tests.ts @@ -0,0 +1,262 @@ +import got = require('got'); +import cookie = require('cookie'); +import FormData = require('form-data'); +import Keyv = require('keyv'); +import * as fs from 'fs'; +import * as http from 'http'; +import * as https from 'https'; +import * as url from 'url'; +import QuickLRU = require('quick-lru'); + +let str: string; +let buf: Buffer; + +got('todomvc.com') + .then(response => { + str = response.body; + }) + .catch((error: got.GotError) => { + console.log(error.response.body); + }); + +got('todomvc.com').cancel(); + +got('todomvc.com', {json: true}).then((response) => { + response.body; // $ExpectType any +}); + +got('todomvc.com', {json: true, body: {}}).then((response) => { + response.body; // $ExpectType any +}); + +got('todomvc.com', {json: true, body: [{}]}).then((response) => { + response.body; // $ExpectType any +}); + +got('todomvc.com', {json: true, form: true}).then((response) => { + response.body; // $ExpectType any +}); + +got('todomvc.com', {json: true, form: true, encoding: null}).then((response) => { + response.body; // $ExpectType any +}); + +got('todomvc.com', {json: true, form: true, encoding: null, hostname: 'todomvc'}).then((response) => { + response.body; // $ExpectType any +}); + +got('todomvc.com', {form: true}).then(response => str = response.body); +got('todomvc.com', {form: true, body: {}}).then(response => str = response.body); +got('todomvc.com', {form: true, body: [{}]}).then(response => str = response.body); +got('todomvc.com', {form: true, body: [{}], encoding: null}).then(response => buf = response.body); +got('todomvc.com', {form: true, body: [{}], encoding: 'utf8'}).then(response => str = response.body); +got('todomvc.com', { + form: true, + body: [{}], + encoding: 'utf8', + hostname: 'todomvc' +}).then(response => str = response.body); +got('todomvc.com', { + form: true, + body: [{}], + encoding: 'utf8', + hostname: 'todomvc', + timeout: 2000 +}).then(response => str = response.body); +got('todomvc.com', { + form: true, + body: [{}], + encoding: 'utf8', + hostname: 'todomvc', + timeout: {connect: 20, request: 20, socket: 20} +}).then(response => str = response.body); +// following must lead to type checking error: got('todomvc.com', {form: true, body: ''}).then(response => str = response.body); + +got('todomvc.com', {encoding: null, hostname: 'todomvc'}).then(response => buf = response.body); +got('todomvc.com', {encoding: 'utf8', hostname: 'todomvc'}).then(response => str = response.body); + +got('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); + +got.get('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.post('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.put('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.patch('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.head('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.delete('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); + +got.stream('todomvc.com').pipe(fs.createWriteStream('index.html')); + +fs.createReadStream('index.html').pipe(got.stream.get('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.post('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.put('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.patch('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.head('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.delete('todomvc.com')); + +let req: http.ClientRequest; +let res: http.IncomingMessage | undefined; +let opts: got.GotOptions; +let err: got.GotError; +let href: string | undefined; +let progress: got.Progress; + +const stream = got.stream('todomvc.com'); +stream.addListener('request', (r) => req = r); +stream.addListener('response', (r) => res = r); +stream.addListener('redirect', (r, o) => { + res = r; + opts = o; + href = o.href; +}); +stream.addListener('error', (e, b, r) => { + err = e; + res = r; +}); +stream.addListener('downloadProgress', (p) => { + progress = p; +}); +stream.addListener('uploadProgress', (p) => { + progress = p; +}); + +stream.on('request', (r) => req = r); +stream.on('response', (r) => res = r); +stream.on('redirect', (r, o) => { + res = r; + opts = o; + href = o.href; +}); +stream.on('error', (e, b, r) => { + err = e; + res = r; +}); +stream.on('downloadProgress', (p) => { + progress = p; +}); +stream.on('uploadProgress', (p) => { + progress = p; +}); + +stream.once('request', (r) => req = r); +stream.once('response', (r) => res = r); +stream.once('redirect', (r, o) => { + res = r; + opts = o; + href = o.href; +}); +stream.once('error', (e, b, r) => { + err = e; + res = r; +}); +stream.once('downloadProgress', (p) => { + progress = p; +}); +stream.once('uploadProgress', (p) => { + progress = p; +}); + +stream.prependListener('request', (r) => req = r); +stream.prependListener('response', (r) => res = r); +stream.prependListener('redirect', (r, o) => { + res = r; + opts = o; + href = o.href; +}); +stream.prependListener('error', (e, b, r) => { + err = e; + res = r; +}); +stream.prependListener('downloadProgress', (p) => { + progress = p; +}); +stream.prependListener('uploadProgress', (p) => { + progress = p; +}); + +stream.prependOnceListener('request', (r) => req = r); +stream.prependOnceListener('response', (r) => res = r); +stream.prependOnceListener('redirect', (r, o) => { + res = r; + opts = o; + href = o.href; +}); +stream.prependOnceListener('error', (e, b, r) => { + err = e; + res = r; +}); +stream.prependOnceListener('downloadProgress', (p) => { + progress = p; +}); +stream.prependOnceListener('uploadProgress', (p) => { + progress = p; +}); + +stream.removeListener('request', (r) => req = r); +stream.removeListener('response', (r) => res = r); +stream.removeListener('redirect', (r, o) => { + res = r; + opts = o; + href = o.href; +}); +stream.removeListener('error', (e, b, r) => { + err = e; + res = r; +}); +stream.removeListener('downloadProgress', (p) => { + progress = p; +}); +stream.removeListener('uploadProgress', (p) => { + progress = p; +}); + +got('google.com', { + headers: { + cookie: cookie.serialize('foo', 'bar') + } +}); + +const form = new FormData(); + +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); + +got.post('google.com', { + body: form +}); + +got('todomvc.com', { + headers: { + 'user-agent': `my-module/ (https://github.com/username/my-module)` + } +}); + +got('https://httpbin.org/404') + .catch(err => err instanceof got.HTTPError && err.statusCode === 404); + +got('todomvc', { + throwHttpErrors: false +}); + +got('todomvc', { + agent: { + http: new http.Agent(), + https: new https.Agent() + } +}); + +got('todomvc', { + cache: new Map(), +}).then(res => res.fromCache); + +got('todomvc', { + cache: new Keyv(), +}).then(res => res.fromCache); + +got('todomvc', { + cache: new QuickLRU(), +}).then(res => res.fromCache); + +got(new url.URL('http://todomvc.com')); + +got(url.parse('http://todomvc.com')); + +got('https://todomvc.com', { rejectUnauthorized: false }); diff --git a/types/got/v8/index.d.ts b/types/got/v8/index.d.ts new file mode 100644 index 0000000000..775985e581 --- /dev/null +++ b/types/got/v8/index.d.ts @@ -0,0 +1,208 @@ +// Type definitions for got 8.3 +// Project: https://github.com/sindresorhus/got#readme +// Definitions by: BendingBender +// Linus Unnebäck +// Konstantin Ikonnikov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Url, URL } from 'url'; +import * as http from 'http'; +import * as https from 'https'; +import * as nodeStream from 'stream'; + +export = got; + +declare class RequestError extends StdError { + name: 'RequestError'; +} + +declare class ReadError extends StdError { + name: 'ReadError'; +} + +declare class ParseError extends StdError { + name: 'ParseError'; + statusCode: number; + statusMessage: string; +} + +declare class HTTPError extends StdError { + name: 'HTTPError'; + statusCode: number; + statusMessage: string; + headers: http.IncomingHttpHeaders; +} + +declare class MaxRedirectsError extends StdError { + name: 'MaxRedirectsError'; + statusCode: number; + statusMessage: string; + redirectUrls: string[]; +} + +declare class UnsupportedProtocolError extends StdError { + name: 'UnsupportedProtocolError'; +} + +declare class CancelError extends StdError { + name: 'CancelError'; +} + +declare class StdError extends Error { + code?: string; + host?: string; + hostname?: string; + method?: string; + path?: string; + protocol?: string; + url?: string; + response?: any; +} + +declare const got: got.GotFn & + Record<'get' | 'post' | 'put' | 'patch' | 'head' | 'delete', got.GotFn> & + { + stream: got.GotStreamFn & Record<'get' | 'post' | 'put' | 'patch' | 'head' | 'delete', got.GotStreamFn>; + RequestError: typeof RequestError; + ReadError: typeof ReadError; + ParseError: typeof ParseError; + HTTPError: typeof HTTPError; + MaxRedirectsError: typeof MaxRedirectsError; + UnsupportedProtocolError: typeof UnsupportedProtocolError; + CancelError: typeof CancelError; + }; + +interface InternalRequestOptions extends https.RequestOptions { + // Redeclare options with `any` type for allow specify types incompatible with http.RequestOptions. + timeout?: any; + agent?: any; +} + +declare namespace got { + interface GotFn { + (url: GotUrl): GotPromise; + (url: GotUrl, options: GotJSONOptions): GotPromise; + (url: GotUrl, options: GotFormOptions): GotPromise; + (url: GotUrl, options: GotFormOptions): GotPromise; + (url: GotUrl, options: GotBodyOptions): GotPromise; + (url: GotUrl, options: GotBodyOptions): GotPromise; + } + + type GotStreamFn = (url: GotUrl, options?: GotOptions) => GotEmitter & nodeStream.Duplex; + + type GotUrl = string | https.RequestOptions | Url | URL; + + interface GotBodyOptions extends GotOptions { + body?: string | Buffer | nodeStream.Readable; + } + + interface GotJSONOptions extends GotOptions { + // Body must be an object or array. See https://github.com/sindresorhus/got/issues/511 + body?: object; + form?: boolean; + json: true; + } + + interface GotFormOptions extends GotOptions { + body?: {[key: string]: any}; + form: true; + json?: boolean; + } + + interface GotOptions extends InternalRequestOptions { + encoding?: E; + query?: string | object; + timeout?: number | TimeoutOptions; + retries?: number | RetryFunction; + followRedirect?: boolean; + decompress?: boolean; + useElectronNet?: boolean; + cache?: Cache; + agent?: http.Agent | boolean | AgentOptions; + throwHttpErrors?: boolean; + } + + interface TimeoutOptions { + connect?: number; + socket?: number; + request?: number; + } + + interface AgentOptions { + http: http.Agent; + https: https.Agent; + } + + type RetryFunction = (retry: number, error: any) => number; + + interface Cache { + set(key: string, value: any, ttl?: number): any; + get(key: string): any; + delete(key: string): any; + } + + interface Response extends http.IncomingMessage { + body: B; + url: string; + requestUrl: string; + fromCache: boolean; + redirectUrls?: string[]; + } + + type GotPromise = Promise> & { cancel(): void }; + + interface GotEmitter { + addListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + addListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + addListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions & Url) => void): this; + addListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + addListener(event: 'downloadProgress', listener: (progress: Progress) => void): this; + addListener(event: 'uploadProgress', listener: (progress: Progress) => void): this; + + on(event: 'request', listener: (req: http.ClientRequest) => void): this; + on(event: 'response', listener: (res: http.IncomingMessage) => void): this; + on(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions & Url) => void): this; + on(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + on(event: 'downloadProgress', listener: (progress: Progress) => void): this; + on(event: 'uploadProgress', listener: (progress: Progress) => void): this; + + once(event: 'request', listener: (req: http.ClientRequest) => void): this; + once(event: 'response', listener: (res: http.IncomingMessage) => void): this; + once(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions & Url) => void): this; + once(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + once(event: 'downloadProgress', listener: (progress: Progress) => void): this; + once(event: 'uploadProgress', listener: (progress: Progress) => void): this; + + prependListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + prependListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + prependListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions & Url) => void): this; + prependListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + prependListener(event: 'downloadProgress', listener: (progress: Progress) => void): this; + prependListener(event: 'uploadProgress', listener: (progress: Progress) => void): this; + + prependOnceListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + prependOnceListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + prependOnceListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions & Url) => void): this; + prependOnceListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + prependOnceListener(event: 'downloadProgress', listener: (progress: Progress) => void): this; + prependOnceListener(event: 'uploadProgress', listener: (progress: Progress) => void): this; + + removeListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + removeListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + removeListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions & Url) => void): this; + removeListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + removeListener(event: 'downloadProgress', listener: (progress: Progress) => void): this; + removeListener(event: 'uploadProgress', listener: (progress: Progress) => void): this; + } + + type GotError = RequestError | ReadError | ParseError | HTTPError | MaxRedirectsError | UnsupportedProtocolError | CancelError; + + interface Progress { + percent: number; + transferred: number; + total: number | null; + } +} diff --git a/types/got/v8/tsconfig.json b/types/got/v8/tsconfig.json new file mode 100644 index 0000000000..a5ffba23b0 --- /dev/null +++ b/types/got/v8/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "got": [ + "got/v8" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "got-tests.ts" + ] +} diff --git a/types/got/v8/tslint.json b/types/got/v8/tslint.json new file mode 100644 index 0000000000..08b1465cd6 --- /dev/null +++ b/types/got/v8/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 2b351bbf70..2b378a6048 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -393,6 +393,36 @@ declare namespace jest { test(val: any): boolean; } + interface InverseAsymmetricMatchers { + /** + * `expect.not.arrayContaining(array)` matches a received array which + * does not contain all of the elements in the expected array. That is, + * the expected array is not a subset of the received array. It is the + * inverse of `expect.arrayContaining`. + */ + arrayContaining(arr: any[]): any; + /** + * `expect.not.objectContaining(object)` matches any received object + * that does not recursively match the expected properties. That is, the + * expected object is not a subset of the received object. Therefore, + * it matches a received object which contains properties that are not + * in the expected object. It is the inverse of `expect.objectContaining`. + */ + objectContaining(obj: {}): any; + /** + * `expect.not.stringMatching(string | regexp)` matches the received + * string that does not match the expected regexp. It is the inverse of + * `expect.stringMatching`. + */ + stringMatching(str: string | RegExp): any; + /** + * `expect.not.stringContaining(string)` matches the received string + * that does not contain the exact expected string. It is the inverse of + * `expect.stringContaining`. + */ + stringContaining(str: string): any; + } + /** * The `expect` function is used every time you want to test a value. * You will rarely call `expect` by itself. @@ -475,6 +505,8 @@ declare namespace jest { * Matches any received string that contains the exact expected string */ stringContaining(str: string): any; + + not: InverseAsymmetricMatchers; } interface Matchers { diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 18543b8f79..de1ba90456 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -746,6 +746,13 @@ describe("", () => { ghi: expect.stringMatching("foo"), })); + /* Inverse type matchers */ + + expect('How are you?').toEqual(expect.not.stringContaining('Hello world!')); + expect('How are you?').toEqual(expect.not.stringMatching(/Hello world!/)); + expect({bar: 'baz'}).toEqual(expect.not.objectContaining({foo: 'bar'})); + expect(['Alice', 'Bob', 'Eve']).toEqual(expect.not.arrayContaining(['Samantha'])); + /* Miscellaneous */ expect.hasAssertions(); diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index f1437d3928..096847a82c 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for joi 13.6 +// Type definitions for joi 14.0 // Project: https://github.com/hapijs/joi // Definitions by: Bart van der Schoor // Laurence Dougal Myers @@ -53,7 +53,6 @@ export interface ValidationOptions { * remove unknown elements from objects and arrays. Defaults to false * - when true, all unknown elements will be removed * - when an object: - * - arrays - set to true to remove unknown items from arrays. * - objects - set to true to remove unknown keys from objects */ stripUnknown?: boolean | { arrays?: boolean; objects?: boolean }; @@ -257,8 +256,7 @@ export interface AnySchema extends JoiObject { /** * Validates a value using the schema and options. */ - validate(value: T): ValidationResult; - validate(value: T, options: ValidationOptions): ValidationResult; + validate(value: T, options?: ValidationOptions): ValidationResult; validate(value: T, callback: (err: ValidationError, value: T) => R): R; validate(value: T, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; @@ -317,14 +315,12 @@ export interface AnySchema extends JoiObject { /** * Annotates the key */ - notes(notes: string): this; - notes(notes: string[]): this; + notes(notes: string | string[]): this; /** * Annotates the key */ - tags(notes: string): this; - tags(notes: string[]): this; + tags(notes: string | string[]): this; /** * Attaches metadata to the key. @@ -369,8 +365,7 @@ export interface AnySchema extends JoiObject { * Additionally, when specifying a method you must either have a description property on your method or the * second parameter is required. */ - default(value: any, description?: string): this; - default(): this; + default(value?: any, description?: string): this; /** * Returns a new type that is the result of adding the rules of one type to another. @@ -380,8 +375,7 @@ export interface AnySchema extends JoiObject { /** * Converts the type into an alternatives type where the conditions are merged into the type definition where: */ - when(ref: string, options: WhenOptions): AlternativesSchema; - when(ref: Reference, options: WhenOptions): AlternativesSchema; + when(ref: string | Reference, options: WhenOptions): AlternativesSchema; when(ref: Schema, options: WhenSchemaOptions): AlternativesSchema; /** @@ -485,29 +479,25 @@ export interface NumberSchema extends AnySchema { * Specifies the minimum value. * It can also be a reference to another field. */ - min(limit: number): this; - min(limit: Reference): this; + min(limit: number | Reference): this; /** * Specifies the maximum value. * It can also be a reference to another field. */ - max(limit: number): this; - max(limit: Reference): this; + max(limit: number | Reference): this; /** * Specifies that the value must be greater than limit. * It can also be a reference to another field. */ - greater(limit: number): this; - greater(limit: Reference): this; + greater(limit: number | Reference): this; /** * Specifies that the value must be less than limit. * It can also be a reference to another field. */ - less(limit: number): this; - less(limit: Reference): this; + less(limit: number | Reference): this; /** * Requires the number to be an integer (no floating point). @@ -552,16 +542,14 @@ export interface StringSchema extends AnySchema { * @param limit - the minimum number of string characters required. It can also be a reference to another field. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ - min(limit: number, encoding?: string): this; - min(limit: Reference, encoding?: string): this; + min(limit: number | Reference, encoding?: string): this; /** * Specifies the maximum number of string characters. * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ - max(limit: number, encoding?: string): this; - max(limit: Reference, encoding?: string): this; + max(limit: number | Reference, encoding?: string): this; /** * Specifies whether the string.max() limit should be used as a truncation. @@ -591,8 +579,7 @@ export interface StringSchema extends AnySchema { * @param limit - the required string length. It can also be a reference to another field. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ - length(limit: number, encoding?: string): this; - length(limit: Reference, encoding?: string): this; + length(limit: number | Reference, encoding?: string): this; /** * Defines a regular expression rule. @@ -610,8 +597,7 @@ export interface StringSchema extends AnySchema { * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. * @param replacement - the string that will replace the pattern. */ - replace(pattern: RegExp, replacement: string): this; - replace(pattern: string, replacement: string): this; + replace(pattern: RegExp | string, replacement: string): this; /** * Requires the string value to only contain a-z, A-Z, and 0-9. @@ -739,8 +725,7 @@ export interface ArraySchema extends AnySchema { /** * Specifies the exact number of items in the array. */ - length(limit: number): this; - length(limit: Reference): this; + length(limit: number | Reference): this; /** * Requires the array values to be unique. @@ -816,14 +801,12 @@ export interface ObjectSchema extends AnySchema { /** * Requires the presence of other keys whenever the specified key is present. */ - with(key: string, peers: string): this; - with(key: string, peers: string[]): this; + with(key: string, peers: string | string[]): this; /** * Forbids the presence of other keys whenever the specified is present. */ - without(key: string, peers: string): this; - without(key: string, peers: string[]): this; + without(key: string, peers: string | string[]): this; /** * Renames a key to another name (deletes the renamed key). @@ -833,8 +816,7 @@ export interface ObjectSchema extends AnySchema { /** * Verifies an assertion where. */ - assert(ref: string, schema: SchemaLike, message?: string): this; - assert(ref: Reference, schema: SchemaLike, message?: string): this; + assert(ref: string | Reference, schema: SchemaLike, message?: string): this; /** * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). @@ -847,6 +829,7 @@ export interface ObjectSchema extends AnySchema { * @param constructor - the constructor function that the object must be an instance of. * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. */ + // tslint:disable-next-line:ban-types type(constructor: Function, name?: string): this; /** @@ -987,8 +970,7 @@ export interface FunctionSchema extends AnySchema { export interface AlternativesSchema extends AnySchema { try(types: SchemaLike[]): this; try(...types: SchemaLike[]): this; - when(ref: string, options: WhenOptions): this; - when(ref: Reference, options: WhenOptions): this; + when(ref: string | Reference, options: WhenOptions): this; when(ref: Schema, options: WhenSchemaOptions): this; } @@ -1037,6 +1019,13 @@ export interface Err extends JoiObject { toString(): string; } +export interface LazyOptions { + /** + * If true the schema generator will only be called once and the result will be cached. + */ + once?: boolean; +} + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- /** @@ -1113,15 +1102,13 @@ export function alt(...types: SchemaLike[]): AlternativesSchema; * Supports the same methods of the any() type. * This is mostly useful for recursive schemas */ -export function lazy(cb: () => Schema): LazySchema; +export function lazy(cb: () => Schema, options?: LazyOptions): LazySchema; /** * Validates a value using the given schema and options. */ -export function validate(value: T, schema: SchemaLike): ValidationResult; +export function validate(value: T, schema: SchemaLike, options?: ValidationOptions): ValidationResult; export function validate(value: T, schema: SchemaLike, callback: (err: ValidationError, value: T) => R): R; - -export function validate(value: T, schema: SchemaLike, options: ValidationOptions): ValidationResult; export function validate(value: T, schema: SchemaLike, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; /** @@ -1161,8 +1148,7 @@ export function isRef(ref: any): ref is Reference; * Get a sub-schema of an existing schema based on a `path` that can be either a string or an array * of strings For string values path separator is a dot (`.`) */ -export function reach(schema: ObjectSchema, path: string): Schema; -export function reach(schema: ObjectSchema, path: string[]): Schema; +export function reach(schema: ObjectSchema, path: string | string[]): Schema; /** * Creates a new Joi instance customized with the extension(s) you provide included. @@ -1251,14 +1237,12 @@ export function description(desc: string): Schema; /** * Annotates the key */ -export function notes(notes: string): Schema; -export function notes(notes: string[]): Schema; +export function notes(notes: string | string[]): Schema; /** * Annotates the key */ -export function tags(notes: string): Schema; -export function tags(notes: string[]): Schema; +export function tags(notes: string | string[]): Schema; /** * Attaches metadata to the key. @@ -1293,8 +1277,7 @@ export function concat(schema: T): T; /** * Converts the type into an alternatives type where the conditions are merged into the type definition where: */ -export function when(ref: string, options: WhenOptions): AlternativesSchema; -export function when(ref: Reference, options: WhenOptions): AlternativesSchema; +export function when(ref: string | Reference, options: WhenOptions): AlternativesSchema; export function when(ref: Schema, options: WhenSchemaOptions): AlternativesSchema; /** diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 8c3c6f2e4e..716fc70c16 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -11,7 +11,7 @@ declare const exp: RegExp; declare const obj: object; declare const date: Date; declare const err: Error; -declare const func: Function; +declare const func: () => void; declare const numArr: number[]; declare const strArr: string[]; @@ -906,7 +906,7 @@ schema = Joi.alt(schema, anySchema, boolSchema); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -schema = Joi.lazy(() => schema); +schema = Joi.lazy(() => schema, { once: true }); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- diff --git a/types/joi/tsconfig.json b/types/joi/tsconfig.json index f6b8f170dc..57e6c47881 100644 --- a/types/joi/tsconfig.json +++ b/types/joi/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "joi-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/joi/tslint.json b/types/joi/tslint.json index c6e5f080fb..79fc0653dc 100644 --- a/types/joi/tslint.json +++ b/types/joi/tslint.json @@ -2,9 +2,7 @@ "extends": "dtslint/dt.json", "rules": { // All are TODOs - "ban-types": false, "no-empty-interface": false, - "no-self-import": false, - "unified-signatures": false + "no-self-import": false } } diff --git a/types/joi/v13/index.d.ts b/types/joi/v13/index.d.ts new file mode 100644 index 0000000000..f3432036cf --- /dev/null +++ b/types/joi/v13/index.d.ts @@ -0,0 +1,1305 @@ +// Type definitions for joi 13.6 +// Project: https://github.com/hapijs/joi +// Definitions by: Bart van der Schoor +// Laurence Dougal Myers +// Christopher Glantschnig +// David Broder-Rodgers +// Gael Magnan de Bornier +// Rytis Alekna +// Pavel Ivanov +// Youngrok Kim +// Dan Kraus +// Anjun Wang +// Rafael Kallis +// Conan Lai +// Peter Thorson +// Will Garcia +// Simon Schick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +// TODO express type of Schema in a type-parameter (.default, .valid, .example etc) + +export type Types = 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'lazy' | 'number' | 'object' | 'string'; + +export type LanguageOptions = string | boolean | null | { + [key: string]: LanguageOptions; +}; + +export type LanguageRootOptions = { + root?: string; + key?: string; + messages?: { wrapArrays?: boolean; }; +} & Partial> & { [key: string]: LanguageOptions; }; + +export interface ValidationOptions { + /** + * when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. + */ + abortEarly?: boolean; + /** + * when true, attempts to cast values to the required types (e.g. a string to a number). Defaults to true. + */ + convert?: boolean; + /** + * when true, allows object to contain unknown keys which are ignored. Defaults to false. + */ + allowUnknown?: boolean; + /** + * when true, ignores unknown keys with a function value. Defaults to false. + */ + skipFunctions?: boolean; + /** + * remove unknown elements from objects and arrays. Defaults to false + * - when true, all unknown elements will be removed + * - when an object: + * - arrays - set to true to remove unknown items from arrays. + * - objects - set to true to remove unknown keys from objects + */ + stripUnknown?: boolean | { arrays?: boolean; objects?: boolean }; + /** + * overrides individual error messages. Defaults to no override ({}). + */ + language?: LanguageRootOptions; + /** + * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'. + */ + presence?: 'optional' | 'required' | 'forbidden'; + /** + * provides an external data set to be used in references + */ + context?: Context; + /** + * when true, do not apply default values. Defaults to false. + */ + noDefaults?: boolean; +} + +export interface RenameOptions { + /** + * if true, does not delete the old key name, keeping both the new and old keys in place. Defaults to false. + */ + alias?: boolean; + /** + * if true, allows renaming multiple keys to the same destination where the last rename wins. Defaults to false. + */ + multiple?: boolean; + /** + * if true, allows renaming a key over an existing key. Defaults to false. + */ + override?: boolean; + /** + * if true, skip renaming of a key if it's undefined. Defaults to false. + */ + ignoreUndefined?: boolean; +} + +export interface EmailOptions { + /** + * Numerical threshold at which an email address is considered invalid + */ + errorLevel?: number | boolean; + /** + * Specifies a list of acceptable TLDs. + */ + tldWhitelist?: string[] | object; + /** + * Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. + */ + minDomainAtoms?: number; +} + +export interface HexOptions { + /** + * hex decoded representation must be byte aligned + */ + byteAligned: boolean; +} + +export interface IpOptions { + /** + * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture + */ + version?: string | string[]; + /** + * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden + */ + cidr?: string; +} + +export type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5'; + +export interface GuidOptions { + version: GuidVersions[] | GuidVersions; +} + +export interface UriOptions { + /** + * Specifies one or more acceptable Schemes, should only include the scheme name. + * Can be an Array or String (strings are automatically escaped for use in a Regular Expression). + */ + scheme?: string | RegExp | Array; + /** + * Allow relative URIs. Defaults to `false`. + */ + allowRelative?: boolean; + /** + * Restrict only relative URIs. Defaults to `false`. + */ + relativeOnly?: boolean; +} + +export interface DataUriOptions { + /** + * optional parameter defaulting to true which will require = padding if true or make padding optional if false + */ + paddingRequired?: boolean; +} + +export interface Base64Options { + /** + * optional parameter defaulting to true which will require = padding if true or make padding optional if false + */ + paddingRequired?: boolean; +} + +export interface WhenOptions { + /** + * the required condition joi type. + */ + is: SchemaLike; + /** + * the alternative schema type if the condition is true. Required if otherwise is missing. + */ + then?: SchemaLike; + /** + * the alternative schema type if the condition is false. Required if then is missing + */ + otherwise?: SchemaLike; +} + +export interface WhenSchemaOptions { + /** + * the alternative schema type if the condition is true. Required if otherwise is missing. + */ + then?: SchemaLike; + /** + * the alternative schema type if the condition is false. Required if then is missing + */ + otherwise?: SchemaLike; +} + +export interface ReferenceOptions { + separator?: string; + contextPrefix?: string; + default?: any; + strict?: boolean; + functions?: boolean; +} + +// tslint:disable-next-line:interface-name +export interface IPOptions { + version?: string[]; + cidr?: string; +} + +export interface StringRegexOptions { + name?: string; + invert?: boolean; +} + +export interface JoiObject { + isJoi: boolean; +} + +export interface ValidationError extends Error, JoiObject { + details: ValidationErrorItem[]; + annotate(): string; + _object: any; +} + +export interface ValidationErrorItem { + message: string; + type: string; + path: string[]; + options?: ValidationOptions; + context?: Context; +} + +export type ValidationErrorFunction = (errors: ValidationErrorItem[]) => string | ValidationErrorItem | ValidationErrorItem[] | Error; + +export interface ValidationResult extends Pick, 'then' | 'catch'> { + error: ValidationError; + value: T; +} + +export type SchemaLike = string | number | boolean | object | null | Schema | SchemaMap; + +export interface SchemaMap { + [key: string]: SchemaLike | SchemaLike[]; +} + +export type Schema = AnySchema + | ArraySchema + | AlternativesSchema + | BinarySchema + | BooleanSchema + | DateSchema + | FunctionSchema + | NumberSchema + | ObjectSchema + | StringSchema + | LazySchema; + +export interface AnySchema extends JoiObject { + schemaType?: Types | string; + + /** + * Validates a value using the schema and options. + */ + validate(value: T): ValidationResult; + validate(value: T, options: ValidationOptions): ValidationResult; + validate(value: T, callback: (err: ValidationError, value: T) => R): R; + validate(value: T, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + + /** + * Whitelists a value + */ + allow(...values: any[]): this; + allow(values: any[]): this; + + /** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ + valid(...values: any[]): this; + valid(values: any[]): this; + only(...values: any[]): this; + only(values: any[]): this; + equal(...values: any[]): this; + equal(values: any[]): this; + + /** + * Blacklists a value + */ + invalid(...values: any[]): this; + invalid(values: any[]): this; + disallow(...values: any[]): this; + disallow(values: any[]): this; + not(...values: any[]): this; + not(values: any[]): this; + + /** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ + required(): this; + exist(): this; + + /** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ + optional(): this; + + /** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ + forbidden(): this; + + /** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ + strip(): this; + + /** + * Annotates the key + */ + description(desc: string): this; + + /** + * Annotates the key + */ + notes(notes: string): this; + notes(notes: string[]): this; + + /** + * Annotates the key + */ + tags(notes: string): this; + tags(notes: string[]): this; + + /** + * Attaches metadata to the key. + */ + meta(meta: object): this; + + /** + * Annotates the key with an example value, must be valid. + */ + example(value: any): this; + + /** + * Annotates the key with an unit name. + */ + unit(name: string): this; + + /** + * Overrides the global validate() options for the current key and any sub-key. + */ + options(options: ValidationOptions): this; + + /** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ + strict(isStrict?: boolean): this; + + /** + * Sets a default value if the original value is undefined. + * @param value - the value. + * value supports references. + * value may also be a function which returns the default value. + * If value is specified as a function that accepts a single parameter, that parameter will be a context + * object that can be used to derive the resulting value. This clones the object however, which incurs some + * overhead so if you don't need access to the context define your method so that it does not accept any + * parameters. + * Without any value, default has no effect, except for object that will then create nested defaults + * (applying inner defaults of that object). + * + * Note that if value is an object, any changes to the object after default() is called will change the + * reference and any future assignment. + * + * Additionally, when specifying a method you must either have a description property on your method or the + * second parameter is required. + */ + default(value: any, description?: string): this; + default(): this; + + /** + * Returns a new type that is the result of adding the rules of one type to another. + */ + concat(schema: this): this; + + /** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + when(ref: Schema, options: WhenSchemaOptions): AlternativesSchema; + + /** + * Overrides the key name in error messages. + */ + label(name: string): this; + + /** + * Outputs the original untouched value instead of the casted value. + */ + raw(isRaw?: boolean): this; + + /** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ + empty(schema?: SchemaLike): this; + + /** + * Overrides the default joi error with a custom error if the rule fails where: + * @param err - can be: + * an instance of `Error` - the override error. + * a `function(errors)`, taking an array of errors as argument, where it must either: + * return a `string` - substitutes the error message with this text + * return a single ` object` or an `Array` of it, where: + * `type` - optional parameter providing the type of the error (eg. `number.min`). + * `message` - optional parameter if `template` is provided, containing the text of the error. + * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. + * `context` - optional parameter, to provide context to your error if you are using the `template`. + * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors. + * + * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the + * normal joi error properties. If validation fails and another error is found before the error + * override, that error will be returned and the override will be ignored (unless the `abortEarly` + * option has been set to `false`). + */ + error(err: Error | ValidationErrorFunction): this; + + /** + * Returns a plain object representing the schema's rules and properties + */ + describe(): Description; +} + +export interface Description { + type?: Types | string; + label?: string; + description?: string; + flags?: object; + notes?: string[]; + tags?: string[]; + meta?: any[]; + example?: any[]; + valids?: any[]; + invalids?: any[]; + unit?: string; + options?: ValidationOptions; + [key: string]: any; +} + +export interface Context { + [key: string]: any; + key?: string; + label?: string; +} + +export interface State { + key?: string; + path?: string; + parent?: any; + reference?: any; +} + +export interface BooleanSchema extends AnySchema { + /** + * Allows for additional values to be considered valid booleans by converting them to true during validation. + * Accepts a value or an array of values. String comparisons are by default case insensitive, + * see boolean.insensitive() to change this behavior. + * @param values - strings, numbers or arrays of them + */ + truthy(...values: Array): this; + + /** + * Allows for additional values to be considered valid booleans by converting them to false during validation. + * Accepts a value or an array of values. String comparisons are by default case insensitive, + * see boolean.insensitive() to change this behavior. + * @param values - strings, numbers or arrays of them + */ + falsy(...values: Array): this; + + /** + * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion + * (when not in strict() mode) to be matched in a case insensitive manner. + * @param enabled + */ + insensitive(enabled?: boolean): this; +} + +export interface NumberSchema extends AnySchema { + /** + * Specifies the minimum value. + * It can also be a reference to another field. + */ + min(limit: number): this; + min(limit: Reference): this; + + /** + * Specifies the maximum value. + * It can also be a reference to another field. + */ + max(limit: number): this; + max(limit: Reference): this; + + /** + * Specifies that the value must be greater than limit. + * It can also be a reference to another field. + */ + greater(limit: number): this; + greater(limit: Reference): this; + + /** + * Specifies that the value must be less than limit. + * It can also be a reference to another field. + */ + less(limit: number): this; + less(limit: Reference): this; + + /** + * Requires the number to be an integer (no floating point). + */ + integer(): this; + + /** + * Specifies the maximum number of decimal places where: + * @param limit - the maximum number of decimal places allowed. + */ + precision(limit: number): this; + + /** + * Specifies that the value must be a multiple of base. + */ + multiple(base: number): this; + + /** + * Requires the number to be positive. + */ + positive(): this; + + /** + * Requires the number to be negative. + */ + negative(): this; + + /** + * Requires the number to be a TCP port, so between 0 and 65535. + */ + port(): this; +} + +export interface StringSchema extends AnySchema { + /** + * Allows the value to match any whitelist of blacklist item in a case insensitive comparison. + */ + insensitive(): this; + + /** + * Specifies the minimum number string characters. + * @param limit - the minimum number of string characters required. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + min(limit: number, encoding?: string): this; + min(limit: Reference, encoding?: string): this; + + /** + * Specifies the maximum number of string characters. + * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + max(limit: number, encoding?: string): this; + max(limit: Reference, encoding?: string): this; + + /** + * Specifies whether the string.max() limit should be used as a truncation. + * @param enabled - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value. + */ + truncate(enabled?: boolean): this; + + /** + * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized. + * @param form - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this; + + /** + * Requires the string value to be a valid base64 string; does not check the decoded value. + * @param options - optional settings: The unicode normalization options to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + base64(options?: Base64Options): this; + + /** + * Requires the number to be a credit card number (Using Lunh Algorithm). + */ + creditCard(): this; + + /** + * Specifies the exact string length required + * @param limit - the required string length. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + length(limit: number, encoding?: string): this; + length(limit: Reference, encoding?: string): this; + + /** + * Defines a regular expression rule. + * @param pattern - a regular expression object the string value must match against. + * @param options - optional, can be: + * Name for patterns (useful with multiple patterns). Defaults to 'required'. + * An optional configuration object with the following supported properties: + * name - optional pattern name. + * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required. + */ + regex(pattern: RegExp, options?: string | StringRegexOptions): this; + + /** + * Replace characters matching the given pattern with the specified replacement string where: + * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement - the string that will replace the pattern. + */ + replace(pattern: RegExp, replacement: string): this; + replace(pattern: string, replacement: string): this; + + /** + * Requires the string value to only contain a-z, A-Z, and 0-9. + */ + alphanum(): this; + + /** + * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _. + */ + token(): this; + + /** + * Requires the string value to be a valid email address. + */ + email(options?: EmailOptions): this; + + /** + * Requires the string value to be a valid ip address. + */ + ip(options?: IpOptions): this; + + /** + * Requires the string value to be a valid RFC 3986 URI. + */ + uri(options?: UriOptions): this; + + /** + * Requires the string value to be a valid data URI string. + */ + dataUri(options?: DataUriOptions): this; + + /** + * Requires the string value to be a valid GUID. + */ + guid(options?: GuidOptions): this; + + /** + * Alias for `guid` -- Requires the string value to be a valid GUID + */ + uuid(options?: GuidOptions): this; + + /** + * Requires the string value to be a valid hexadecimal string. + */ + hex(options?: HexOptions): this; + + /** + * Requires the string value to be a valid hostname as per RFC1123. + */ + hostname(): this; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + isoDate(): this; + + /** + * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase. + */ + lowercase(): this; + + /** + * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase. + */ + uppercase(): this; + + /** + * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. + */ + trim(): this; +} + +export interface SymbolSchema extends AnySchema { + // TODO: support number and symbol index + map(iterable: Iterable<[string | number | boolean | symbol, symbol]> | { [key: string]: symbol }): this; +} + +export interface ArraySchema extends AnySchema { + /** + * Allow this array to be sparse. + * enabled can be used with a falsy value to go back to the default behavior. + */ + sparse(enabled?: any): this; + + /** + * Allow single values to be checked against rules as if it were provided as an array. + * enabled can be used with a falsy value to go back to the default behavior. + */ + single(enabled?: any): this; + + /** + * List the types allowed for the array values. + * type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item in the array. + * If a type is .forbidden() then it cannot appear in the array. + * Required items can be added multiple times to signify that multiple items must be found. + * Errors will contain the number of items that didn't match. + * Any unmatched item having a label will be mentioned explicitly. + * + * @param type - a joi schema object to validate each array item against. + */ + items(...types: SchemaLike[]): this; + items(types: SchemaLike[]): this; + + /** + * Lists the types in sequence order for the array values where: + * @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item with the same index position in the array. + * Errors will contain the number of items that didn't match. + * Any unmatched item having a label will be mentioned explicitly. + */ + ordered(...types: SchemaLike[]): this; + ordered(types: SchemaLike[]): this; + + /** + * Specifies the minimum number of items in the array. + */ + min(limit: number): this; + + /** + * Specifies the maximum number of items in the array. + */ + max(limit: number): this; + + /** + * Specifies the exact number of items in the array. + */ + length(limit: number): this; + length(limit: Reference): this; + + /** + * Requires the array values to be unique. + * Be aware that a deep equality is performed on elements of the array having a type of object, + * a performance penalty is to be expected for this kind of operation. + */ + unique(comparator?: string): this; + unique(comparator?: (a: T, b: T) => boolean): this; +} + +export interface ObjectSchema extends AnySchema { + /** + * Sets or extends the allowed object keys. + */ + keys(schema?: SchemaMap): this; + + /** + * Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied. + */ + append(schema?: SchemaMap): this; + + /** + * Specifies the minimum number of keys in the object. + */ + min(limit: number): this; + + /** + * Specifies the maximum number of keys in the object. + */ + max(limit: number): this; + + /** + * Specifies the exact number of keys in the object. + */ + length(limit: number): this; + + /** + * Specify validation rules for unknown keys matching a pattern. + * + * @param pattern - a pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names + * @param schema - the schema object matching keys must validate against + */ + pattern(pattern: RegExp | SchemaLike, schema: SchemaLike): this; + + /** + * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. + * @param peers - the key names of which if one present, all are required. peers can be a single string value, + * an array of string values, or each peer provided as an argument. + */ + and(...peers: string[]): this; + and(peers: string[]): this; + + /** + * Defines a relationship between keys where not all peers can be present at the same time. + * @param peers - the key names of which if one present, the others may not all be present. + * peers can be a single string value, an array of string values, or each peer provided as an argument. + */ + nand(...peers: string[]): this; + nand(peers: string[]): this; + + /** + * Defines a relationship between keys where one of the peers is required (and more than one is allowed). + */ + or(...peers: string[]): this; + or(peers: string[]): this; + + /** + * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: + */ + xor(...peers: string[]): this; + xor(peers: string[]): this; + + /** + * Requires the presence of other keys whenever the specified key is present. + */ + with(key: string, peers: string): this; + with(key: string, peers: string[]): this; + + /** + * Forbids the presence of other keys whenever the specified is present. + */ + without(key: string, peers: string): this; + without(key: string, peers: string[]): this; + + /** + * Renames a key to another name (deletes the renamed key). + */ + rename(from: string, to: string, options?: RenameOptions): this; + + /** + * Verifies an assertion where. + */ + assert(ref: string, schema: SchemaLike, message?: string): this; + assert(ref: Reference, schema: SchemaLike, message?: string): this; + + /** + * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). + */ + unknown(allow?: boolean): this; + + /** + * Requires the object to be an instance of a given constructor. + * + * @param constructor - the constructor function that the object must be an instance of. + * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + */ + type(constructor: Function, name?: string): this; + + /** + * Sets the specified children to required. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); + * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); + * + * Note that in this example '' means the current object, a is not required but b is, as well as c and d. + */ + requiredKeys(children: string[]): this; + requiredKeys(...children: string[]): this; + + /** + * Sets the specified children to optional. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * The behavior is exactly the same as requiredKeys. + */ + optionalKeys(children: string[]): this; + optionalKeys(...children: string[]): this; + + /** + * Sets the specified children to forbidden. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * const schema = Joi.object().keys({ a: { b: Joi.number().required() }, c: { d: Joi.string().required() } }); + * const optionalSchema = schema.forbiddenKeys('a.b', 'c.d'); + * + * The behavior is exactly the same as requiredKeys. + */ + forbiddenKeys(children: string[]): this; + forbiddenKeys(...children: string[]): this; +} + +export interface BinarySchema extends AnySchema { + /** + * Sets the string encoding format if a string input is converted to a buffer. + */ + encoding(encoding: string): this; + + /** + * Specifies the minimum length of the buffer. + */ + min(limit: number): this; + + /** + * Specifies the maximum length of the buffer. + */ + max(limit: number): this; + + /** + * Specifies the exact length of the buffer: + */ + length(limit: number): this; +} + +export interface DateSchema extends AnySchema { + /** + * Specifies the oldest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + min(date: Date): this; + min(date: number): this; + min(date: string): this; + min(date: Reference): this; + + /** + * Specifies the latest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + max(date: Date): this; + max(date: number): this; + max(date: string): this; + max(date: Reference): this; + + /** + * Specifies the allowed date format: + * @param format - string or array of strings that follow the moment.js format. + */ + format(format: string): this; + format(format: string[]): this; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + iso(): this; + + /** + * Requires the value to be a timestamp interval from Unix Time. + * @param type - the type of timestamp (allowed values are unix or javascript [default]) + */ + timestamp(type?: 'javascript' | 'unix'): this; +} + +export interface FunctionSchema extends AnySchema { + /** + * Specifies the arity of the function where: + * @param n - the arity expected. + */ + arity(n: number): this; + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + minArity(n: number): this; + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + maxArity(n: number): this; + + /** + * Requires the function to be a Joi reference. + */ + ref(): this; +} + +export interface AlternativesSchema extends AnySchema { + try(types: SchemaLike[]): this; + try(...types: SchemaLike[]): this; + when(ref: string, options: WhenOptions): this; + when(ref: Reference, options: WhenOptions): this; + when(ref: Schema, options: WhenSchemaOptions): this; +} + +export interface LazySchema extends AnySchema { +} + +export interface Reference extends JoiObject { + (value: any, validationOptions: ValidationOptions): any; + isContext: boolean; + key: string; + path: string; + toString(): string; +} + +export type ExtensionBoundSchema = Schema & { + /** + * Creates a joi error object. + * Used in conjunction with custom rules. + * @param type - the type of rule to create the error for. + * @param context - provide properties that will be available in the `language` templates. + * @param state - should the context passed into the `validate` function in a custom rule + * @param options - should the context passed into the `validate` function in a custom rule + */ + createError(type: string, context: Context, state: State, options: ValidationOptions): Err; +}; + +export interface Rules

{ + name: string; + params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; + setup?(this: ExtensionBoundSchema, params: P): Schema | void; + validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): any; + description?: string | ((params: P) => string); +} + +export interface Extension { + name: string; + base?: Schema; + language?: LanguageOptions; + coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any; + pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any; + describe?(this: Schema, description: Description): Description; + rules?: Rules[]; +} + +export interface Err extends JoiObject { + toString(): string; +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +/** + * Current version of the joi package. + */ +export const version: string; + +/** + * Generates a schema object that matches any data type. + */ +export function any(): AnySchema; + +/** + * Generates a schema object that matches an array data type. + */ +export function array(): ArraySchema; + +/** + * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool(). + */ +export function bool(): BooleanSchema; + +export function boolean(): BooleanSchema; + +/** + * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers). + */ +export function binary(): BinarySchema; + +/** + * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds). + */ +export function date(): DateSchema; + +/** + * Generates a schema object that matches a function type. + */ +export function func(): FunctionSchema; + +/** + * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers). + */ +export function number(): NumberSchema; + +/** + * Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects). + */ +export function object(schema?: SchemaMap): ObjectSchema; + +/** + * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow(''). + */ +export function string(): StringSchema; + +/** + * Generates a schema object that matches any symbol. + */ +export function symbol(): SymbolSchema; + +/** + * Generates a type that will match one of the provided alternative schemas + */ +export function alternatives(types: SchemaLike[]): AlternativesSchema; +export function alternatives(...types: SchemaLike[]): AlternativesSchema; + +/** + * Alias for `alternatives` + */ +export function alt(types: SchemaLike[]): AlternativesSchema; +export function alt(...types: SchemaLike[]): AlternativesSchema; + +/** + * Generates a placeholder schema for a schema that you would provide with the fn. + * Supports the same methods of the any() type. + * This is mostly useful for recursive schemas + */ +export function lazy(cb: () => Schema): LazySchema; + +/** + * Validates a value using the given schema and options. + */ +export function validate(value: T, schema: SchemaLike): ValidationResult; +export function validate(value: T, schema: SchemaLike, callback: (err: ValidationError, value: T) => R): R; + +export function validate(value: T, schema: SchemaLike, options: ValidationOptions): ValidationResult; +export function validate(value: T, schema: SchemaLike, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + +/** + * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). + */ +export function compile(schema: SchemaLike): Schema; + +/** + * Validates a value against a schema and throws if validation fails. + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ +export function assert(value: any, schema: SchemaLike, message?: string | Error): void; + +/** + * Validates a value against a schema, returns valid object, and throws if validation fails where: + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ +export function attempt(value: T, schema: SchemaLike, message?: string | Error): T; + +/** + * Generates a reference to the value of the named key. + */ +export function ref(key: string, options?: ReferenceOptions): Reference; + +/** + * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages. + */ +export function isRef(ref: any): ref is Reference; + +/** + * Get a sub-schema of an existing schema based on a `path` that can be either a string or an array + * of strings For string values path separator is a dot (`.`) + */ +export function reach(schema: ObjectSchema, path: string): Schema; +export function reach(schema: ObjectSchema, path: string[]): Schema; + +/** + * Creates a new Joi instance customized with the extension(s) you provide included. + */ +export function extend(extension: Extension|Extension[], ...extensions: Array): any; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +import * as Module from 'joi'; +export type Root = typeof Module; +export type DefaultsFunction = (root: Schema) => Schema; + +/** + * Creates a new Joi instance that will apply defaults onto newly created schemas + * through the use of the fn function that takes exactly one argument, the schema being created. + * + * @param fn - The function must always return a schema, even if untransformed. + */ +export function defaults(fn: DefaultsFunction): Root; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +// Below are undocumented APIs. use at your own risk +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +/** + * Returns a plain object representing the schema's rules and properties + */ +export function describe(schema: Schema): Description; + +/** + * Whitelists a value + */ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values: any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values: any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values: any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values: any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Alias of `required`. + */ +export function exist(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; +export function when(ref: Schema, options: WhenSchemaOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any): Schema; diff --git a/types/joi/v13/joi-tests.ts b/types/joi/v13/joi-tests.ts new file mode 100644 index 0000000000..832858c7e9 --- /dev/null +++ b/types/joi/v13/joi-tests.ts @@ -0,0 +1,1150 @@ +import Joi = require('joi'); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let x: any = null; +declare const value: any; +let num = 0; +let str = ''; +declare const bool: boolean; +declare const exp: RegExp; +declare const obj: object; +declare const date: Date; +declare const err: Error; +declare const func: Function; + +declare const numArr: number[]; +declare const strArr: string[]; +declare const expArr: RegExp[]; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let schema: Joi.Schema = null; +declare const schemaLike: Joi.SchemaLike; + +let anySchema: Joi.AnySchema = null; +let numSchema: Joi.NumberSchema = null; +let strSchema: Joi.StringSchema = null; +let arrSchema: Joi.ArraySchema = null; +let boolSchema: Joi.BooleanSchema = null; +let binSchema: Joi.BinarySchema = null; +let dateSchema: Joi.DateSchema = null; +let funcSchema: Joi.FunctionSchema = null; +let objSchema: Joi.ObjectSchema = null; +let altSchema: Joi.AlternativesSchema = null; + +declare const schemaArr: Joi.Schema[]; + +let ref: Joi.Reference = null; +let description: Joi.Description = null; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let validOpts: Joi.ValidationOptions = null; + +validOpts = { abortEarly: bool }; +validOpts = { convert: bool }; +validOpts = { allowUnknown: bool }; +validOpts = { skipFunctions: bool }; +validOpts = { stripUnknown: bool }; +validOpts = { stripUnknown: { arrays: bool } }; +validOpts = { stripUnknown: { objects: bool } }; +validOpts = { stripUnknown: { arrays: bool, objects: bool } }; +validOpts = { presence: 'optional' || 'required' || 'forbidden' }; +validOpts = { context: obj }; +validOpts = { noDefaults: bool }; +validOpts = { + language: { + root: str, + key: str, + messages: { wrapArrays: bool }, + string: { base: str }, + number: { base: str }, + object: { + base: false, + children: { childRule: str } + }, + customType: { + customRule: str + } + } +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let renOpts: Joi.RenameOptions = null; + +renOpts = { alias: bool }; +renOpts = { multiple: bool }; +renOpts = { override: bool }; +renOpts = { ignoreUndefined: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let emailOpts: Joi.EmailOptions = null; + +emailOpts = { errorLevel: num }; +emailOpts = { errorLevel: bool }; +emailOpts = { tldWhitelist: strArr }; +emailOpts = { tldWhitelist: obj }; +emailOpts = { minDomainAtoms: num }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let hexOpts: Joi.HexOptions = null; + +hexOpts = { byteAligned: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let ipOpts: Joi.IpOptions = null; + +ipOpts = { version: str }; +ipOpts = { version: strArr }; +ipOpts = { cidr: str }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let uriOpts: Joi.UriOptions = null; + +uriOpts = { scheme: str }; +uriOpts = { scheme: exp }; +uriOpts = { scheme: strArr }; +uriOpts = { scheme: expArr }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let base64Opts: Joi.Base64Options = null; + +base64Opts = { paddingRequired: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let dataUriOpts: Joi.DataUriOptions = null; + +dataUriOpts = { paddingRequired: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let whenOpts: Joi.WhenOptions = null; + +whenOpts = { is: x }; +whenOpts = { is: schema, then: schema }; +whenOpts = { is: schema, otherwise: schema }; +whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let whenSchemaOpts: Joi.WhenSchemaOptions = null; + +whenSchemaOpts = { then: schema }; +whenSchemaOpts = { otherwise: schema }; +whenSchemaOpts = { then: schemaLike, otherwise: schemaLike }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let refOpts: Joi.ReferenceOptions = null; + +refOpts = { separator: str }; +refOpts = { contextPrefix: str }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let stringRegexOpts: Joi.StringRegexOptions = null; + +stringRegexOpts = { name: str }; +stringRegexOpts = { invert: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +declare const validErr: Joi.ValidationError; +let validErrItem: Joi.ValidationErrorItem; +let validErrFunc: Joi.ValidationErrorFunction; + +validErrItem = { + message: str, + type: str, + path: [str] +}; + +validErrItem = { + message: str, + type: str, + path: [str], + options: validOpts, + context: obj +}; + +validErrFunc = errs => errs; +validErrFunc = errs => errs[0]; +validErrFunc = errs => 'Some error'; +validErrFunc = errs => err; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = anySchema; +schema = numSchema; +schema = strSchema; +schema = arrSchema; +schema = boolSchema; +schema = binSchema; +schema = dateSchema; +schema = funcSchema; +schema = objSchema; + +anySchema = anySchema; +anySchema = numSchema; +anySchema = strSchema; +anySchema = arrSchema; +anySchema = boolSchema; +anySchema = binSchema; +anySchema = dateSchema; +anySchema = funcSchema; +anySchema = objSchema; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let schemaMap: Joi.SchemaMap = null; + +schemaMap = { + a: numSchema, + b: strSchema +}; +schemaMap = { + a: numSchema, + b: { + b1: strSchema, + b2: anySchema + } +}; +schemaMap = { + a: numSchema, + b: [ + { b1: strSchema }, + { b2: anySchema } + ], + c: arrSchema, + d: schemaLike +}; +schemaMap = { + a: 1, + b: { + b1: '1', + b2: 2 + }, + c: [ + { c1: true }, + { c2: null } + ] +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +anySchema = Joi.any(); + +{ // common + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); + + anySchema = anySchema.default(); + anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); + + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); + + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); + + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); + + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); + anySchema = anySchema.concat(x); + + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); + altSchema = anySchema.when(schema, whenSchemaOpts); + + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); + + anySchema = anySchema.error(err); + anySchema = anySchema.error(validErrFunc); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +arrSchema = Joi.array(); + +arrSchema = arrSchema.sparse(); +arrSchema = arrSchema.sparse(bool); +arrSchema = arrSchema.single(); +arrSchema = arrSchema.single(bool); +arrSchema = arrSchema.ordered(anySchema); +arrSchema = arrSchema.ordered(anySchema, numSchema, strSchema, arrSchema, boolSchema, binSchema, dateSchema, funcSchema, objSchema, schemaLike); +arrSchema = arrSchema.ordered(schemaMap); +arrSchema = arrSchema.ordered([schemaMap, schemaMap, schemaLike]); +arrSchema = arrSchema.min(num); +arrSchema = arrSchema.max(num); +arrSchema = arrSchema.length(num); +arrSchema = arrSchema.length(ref); +arrSchema = arrSchema.unique(); +arrSchema = arrSchema.unique((a, b) => a.test === b.test); +arrSchema = arrSchema.unique('customer.id'); + +arrSchema = arrSchema.items(numSchema); +arrSchema = arrSchema.items(numSchema, strSchema, schemaLike); +arrSchema = arrSchema.items([numSchema, strSchema, schemaLike]); +arrSchema = arrSchema.items(schemaMap); +arrSchema = arrSchema.items(schemaMap, schemaMap, schemaLike); +arrSchema = arrSchema.items([schemaMap, schemaMap, schemaLike]); + +// - - - - - - - - + +{ // common copy paste + // use search & replace from any + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); + + arrSchema = arrSchema.default(x); + + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); + + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); + + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); + + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); + + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); + altSchema = arrSchema.when(schema, whenSchemaOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +boolSchema = Joi.bool(); +boolSchema = Joi.boolean(); + +{ // common copy paste + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); + + boolSchema = boolSchema.default(x); + + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); + + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); + + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); + + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); + + boolSchema = boolSchema.truthy(str); + boolSchema = boolSchema.truthy(num); + boolSchema = boolSchema.truthy(strArr); + boolSchema = boolSchema.truthy(numArr); + boolSchema = boolSchema.truthy(str, str); + boolSchema = boolSchema.truthy(strArr, str); + boolSchema = boolSchema.truthy(str, strArr); + boolSchema = boolSchema.truthy(strArr, strArr); + boolSchema = boolSchema.falsy(str); + boolSchema = boolSchema.falsy(num); + boolSchema = boolSchema.falsy(strArr); + boolSchema = boolSchema.falsy(numArr); + boolSchema = boolSchema.falsy(str, str); + boolSchema = boolSchema.falsy(strArr, str); + boolSchema = boolSchema.falsy(str, strArr); + boolSchema = boolSchema.falsy(strArr, strArr); + boolSchema = boolSchema.insensitive(bool); + + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); + altSchema = boolSchema.when(schema, whenSchemaOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +binSchema = Joi.binary(); + +binSchema = binSchema.encoding(str); +binSchema = binSchema.min(num); +binSchema = binSchema.max(num); +binSchema = binSchema.length(num); + +{ // common + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); + + binSchema = binSchema.default(x); + + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); + + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); + + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); + + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); + + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); + altSchema = binSchema.when(schema, whenSchemaOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +dateSchema = Joi.date(); + +dateSchema = dateSchema.min(date); +dateSchema = dateSchema.max(date); + +dateSchema = dateSchema.min(str); +dateSchema = dateSchema.max(str); + +dateSchema = dateSchema.min(num); +dateSchema = dateSchema.max(num); + +dateSchema = dateSchema.min(ref); +dateSchema = dateSchema.max(ref); + +dateSchema = dateSchema.format(str); +dateSchema = dateSchema.format(strArr); + +dateSchema = dateSchema.iso(); + +dateSchema = dateSchema.timestamp(); +dateSchema = dateSchema.timestamp('javascript'); +dateSchema = dateSchema.timestamp('unix'); + +{ // common + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); + + dateSchema = dateSchema.default(x); + + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); + + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); + + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); + + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); + + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); + altSchema = dateSchema.when(schema, whenSchemaOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +funcSchema = Joi.func(); + +funcSchema = funcSchema.arity(num); +funcSchema = funcSchema.minArity(num); +funcSchema = funcSchema.maxArity(num); +funcSchema = funcSchema.ref(); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +numSchema = Joi.number(); + +numSchema = numSchema.min(num); +numSchema = numSchema.min(ref); +numSchema = numSchema.max(num); +numSchema = numSchema.max(ref); +numSchema = numSchema.greater(num); +numSchema = numSchema.greater(ref); +numSchema = numSchema.less(num); +numSchema = numSchema.less(ref); +numSchema = numSchema.integer(); +numSchema = numSchema.precision(num); +numSchema = numSchema.multiple(num); +numSchema = numSchema.positive(); +numSchema = numSchema.negative(); +numSchema = numSchema.port(); + +{ // common + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); + + numSchema = numSchema.default(x); + + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); + + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); + + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); + + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); + + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); + altSchema = numSchema.when(schema, whenSchemaOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +objSchema = Joi.object(); +objSchema = Joi.object(schemaMap); + +objSchema = objSchema.keys(); +objSchema = objSchema.keys(schemaMap); + +objSchema = objSchema.append(); +objSchema = objSchema.append(schemaMap); + +objSchema = objSchema.min(num); +objSchema = objSchema.max(num); +objSchema = objSchema.length(num); + +objSchema = objSchema.pattern(exp, schema); +objSchema = objSchema.pattern(exp, schemaLike); + +objSchema = objSchema.and(str); +objSchema = objSchema.and(str, str); +objSchema = objSchema.and(str, str, str); +objSchema = objSchema.and(strArr); + +objSchema = objSchema.nand(str); +objSchema = objSchema.nand(str, str); +objSchema = objSchema.nand(str, str, str); +objSchema = objSchema.nand(strArr); + +objSchema = objSchema.or(str); +objSchema = objSchema.or(str, str); +objSchema = objSchema.or(str, str, str); +objSchema = objSchema.or(strArr); + +objSchema = objSchema.xor(str); +objSchema = objSchema.xor(str, str); +objSchema = objSchema.xor(str, str, str); +objSchema = objSchema.xor(strArr); + +objSchema = objSchema.with(str, str); +objSchema = objSchema.with(str, strArr); + +objSchema = objSchema.without(str, str); +objSchema = objSchema.without(str, strArr); + +objSchema = objSchema.rename(str, str); +objSchema = objSchema.rename(str, str, renOpts); + +objSchema = objSchema.assert(str, schema); +objSchema = objSchema.assert(str, schema, str); +objSchema = objSchema.assert(ref, schema); +objSchema = objSchema.assert(ref, schema, str); + +objSchema = objSchema.unknown(); +objSchema = objSchema.unknown(bool); + +objSchema = objSchema.type(func); +objSchema = objSchema.type(func, str); + +objSchema = objSchema.requiredKeys(str); +objSchema = objSchema.requiredKeys(str, str); +objSchema = objSchema.requiredKeys(strArr); + +objSchema = objSchema.optionalKeys(str); +objSchema = objSchema.optionalKeys(str, str); +objSchema = objSchema.optionalKeys(strArr); + +objSchema = objSchema.forbiddenKeys(str); +objSchema = objSchema.forbiddenKeys(str, str); +objSchema = objSchema.forbiddenKeys(strArr); + +{ // common + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); + + objSchema = objSchema.default(x); + + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); + + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); + + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); + + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); + + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); + altSchema = objSchema.when(schema, whenSchemaOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +strSchema = Joi.string(); + +strSchema = strSchema.insensitive(); +strSchema = strSchema.min(num); +strSchema = strSchema.min(num, str); +strSchema = strSchema.min(ref); +strSchema = strSchema.min(ref, str); +strSchema = strSchema.max(num); +strSchema = strSchema.max(num, str); +strSchema = strSchema.max(ref); +strSchema = strSchema.max(ref, str); +strSchema = strSchema.creditCard(); +strSchema = strSchema.length(num); +strSchema = strSchema.length(num, str); +strSchema = strSchema.length(ref); +strSchema = strSchema.length(ref, str); +strSchema = strSchema.regex(exp); +strSchema = strSchema.regex(exp, str); +strSchema = strSchema.regex(exp, stringRegexOpts); +strSchema = strSchema.replace(exp, str); +strSchema = strSchema.replace(str, str); +strSchema = strSchema.alphanum(); +strSchema = strSchema.token(); +strSchema = strSchema.email(); +strSchema = strSchema.email(emailOpts); +strSchema = strSchema.ip(); +strSchema = strSchema.ip(ipOpts); +strSchema = strSchema.uri(); +strSchema = strSchema.uri(uriOpts); +strSchema = strSchema.guid(); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: 'uuidv4' }); +strSchema = strSchema.hex(); +strSchema = strSchema.hex(hexOpts); +strSchema = strSchema.hostname(); +strSchema = strSchema.isoDate(); +strSchema = strSchema.lowercase(); +strSchema = strSchema.uppercase(); +strSchema = strSchema.trim(); +strSchema = strSchema.truncate(); +strSchema = strSchema.truncate(false); +strSchema = strSchema.normalize(); +strSchema = strSchema.normalize('NFKC'); +strSchema = strSchema.base64(); +strSchema = strSchema.base64(base64Opts); +strSchema = strSchema.dataUri(); +strSchema = strSchema.dataUri(dataUriOpts); + +{ // common + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); + + strSchema = strSchema.default(x); + + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); + + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); + + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); + + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); + + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); + altSchema = strSchema.when(schema, whenSchemaOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.alternatives(); +schema = Joi.alternatives().try(schemaArr); +schema = Joi.alternatives().try(schema, schema); + +schema = Joi.alternatives(schemaArr); +schema = Joi.alternatives(schema, anySchema, boolSchema); + +schema = Joi.alt(); +schema = Joi.alt().try(schemaArr); +schema = Joi.alt().try(schema, schema); + +schema = Joi.alt(schemaArr); +schema = Joi.alt(schema, anySchema, boolSchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.lazy(() => schema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +{ // validate tests + { + Joi.validate(value, obj); + Joi.validate(value, schema); + Joi.validate(value, schema, validOpts); + Joi.validate(value, schema, validOpts, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path[0]; + str = err.details[0].message; + str = err.details[0].type; + }); + Joi.validate(value, schema, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path.join('.'); + str = err.details[0].message; + str = err.details[0].type; + }); + // variant + Joi.validate(num, schema, validOpts, (err, value) => { + num = value; + }); + + // plain opts + Joi.validate(value, {}); + } + + { + let value = { username: 'example', password: 'example' }; + const schema = Joi.object().keys({ + username: Joi.string().max(255).required(), + password: Joi.string().regex(/^[a-zA-Z0-9]{3,255}$/).required(), + }); + let returnValue: Joi.ValidationResult; + + returnValue = schema.validate(value); + value = schema.validate(value, (err, value) => value); + + returnValue = Joi.validate(value, schema); + returnValue = Joi.validate(value, obj); + value = Joi.validate(value, obj, (err, value) => value); + value = Joi.validate(value, schema, (err, value) => value); + + returnValue = Joi.validate(value, schema, validOpts); + returnValue = Joi.validate(value, obj, validOpts); + value = Joi.validate(value, obj, validOpts, (err, value) => value); + value = Joi.validate(value, schema, validOpts, (err, value) => value); + + returnValue = schema.validate(value); + returnValue = schema.validate(value, validOpts); + value = schema.validate(value, (err, value) => value); + value = schema.validate(value, validOpts, (err, value) => value); + + returnValue + .then(val => JSON.stringify(val, null, 2)) + .then(val => { throw new Error('one error'); }) + .catch(e => {}); + } +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.compile(obj); +schema = Joi.compile(schemaMap); + +Joi.assert(obj, schema); +Joi.assert(obj, schema, str); +Joi.assert(obj, schema, err); +Joi.assert(obj, schemaLike); + +Joi.attempt(obj, schema); +Joi.attempt(obj, schema, str); +Joi.attempt(obj, schema, err); +Joi.attempt(obj, schemaLike); + +ref = Joi.ref(str, refOpts); +ref = Joi.ref(str); + +Joi.isRef(ref); + +description = Joi.describe(schema); +description = schema.describe(); + +schema = Joi.reach(objSchema, ''); +schema = Joi.reach(objSchema, []); + +const Joi2 = Joi.extend({ name: '', base: schema }); + +const Joi3 = Joi.extend({ + base: Joi.string(), + name: 'string', + language: { + asd: 'must be exactly asd(f)', + }, + pre(value, state, options) { + return value; + }, + describe(description) { + return description; + }, + rules: [ + { + name: 'asd', + params: { + allowFalse: Joi.boolean().default(false), + }, + setup(params) { + const fIsAllowed = params.allowFalse; + }, + validate(params, value: boolean, state, options) { + if (value || params.allowFalse && !value) { + return value; + } + return this.createError('asd', { v: value }, state, options); + }, + }, + ], +}); + +const Joi4 = Joi.extend([{ name: '', base: schema }, { name: '', base: schema }]); + +const Joi5 = Joi.extend({ name: '', base: schema }, { name: '', base: schema }); + +const Joi6 = Joi.extend({ name: '', base: schema }, [{ name: '', base: schema }, { name: '', base: schema }]); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +const defaultsJoi = Joi.defaults((schema) => { + switch (schema.schemaType) { + case 'string': + return schema.allow(''); + case 'object': + return (schema as Joi.ObjectSchema).min(1); + default: + return schema; + } +}); + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); +schema = Joi.when(schema, whenSchemaOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.exist(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); +schema = Joi.when(schema, whenSchemaOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); + +schema = Joi.symbol(); +schema = Joi.symbol().map(new Map()); +schema = Joi.symbol().map({ + key: Symbol('asd'), +}); diff --git a/types/joi/v13/tsconfig.json b/types/joi/v13/tsconfig.json new file mode 100644 index 0000000000..30da076bfb --- /dev/null +++ b/types/joi/v13/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "joi": [ + "joi/v13" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "joi-tests.ts" + ] +} diff --git a/types/joi/v13/tslint.json b/types/joi/v13/tslint.json new file mode 100644 index 0000000000..c6e5f080fb --- /dev/null +++ b/types/joi/v13/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "ban-types": false, + "no-empty-interface": false, + "no-self-import": false, + "unified-signatures": false + } +} diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 58522f752c..7d31585d32 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1121,7 +1121,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): this; + depopulate(path?: string): this; /** * Returns true if the Document stores the same data as doc. diff --git a/types/n3/index.d.ts b/types/n3/index.d.ts index 75a8c4efef..0c8c992030 100644 --- a/types/n3/index.d.ts +++ b/types/n3/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/RubenVerborgh/N3.js // Definitions by: Fred Eisele // Ruben Taelman +// Laurens Rietveld // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -16,91 +17,119 @@ export interface Prefixes { [key: string]: I; } +export type Term = NamedNode | BlankNode | Literal | Variable | DefaultGraph; export type PrefixedToIri = (suffix: string) => RDF.NamedNode; -export class Term implements RDF.Term { - termType: "NamedNode" | "BlankNode" | "Literal" | "Variable" | "DefaultGraph"; - id: string; +export class NamedNode implements RDF.NamedNode { + termType: "NamedNode"; value: string; constructor(iri: string); - toJSON(): string; + id: string; + toJSON(): {}; equals(other: RDF.Term): boolean; static subclass(type: any): void; } -export class NamedNode extends Term implements RDF.NamedNode { - termType: "NamedNode"; - value: string; - constructor(iri: string); -} - -export class BlankNode extends Term implements RDF.BlankNode { +export class BlankNode implements RDF.BlankNode { static nextId: number; termType: "BlankNode"; value: string; constructor(name: string); + id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; } -export class Variable extends Term implements RDF.Variable { +export class Variable implements RDF.Variable { termType: "Variable"; value: string; constructor(name: string); + id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; } -export class Literal extends Term implements RDF.Literal { +export class Literal implements RDF.Literal { static readonly langStringDatatype: NamedNode; termType: "Literal"; value: string; + id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; language: string; - datatype: RDF.NamedNode; + datatype: NamedNode; datatypeString: string; constructor(id: string); } -export class DefaultGraph extends Term implements RDF.DefaultGraph { +export class DefaultGraph implements RDF.DefaultGraph { termType: "DefaultGraph"; value: ""; constructor(); + id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; } -export class Quad implements RDF.Quad { - constructor(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term); - subject: RDF.Term; - predicate: RDF.Term; - object: RDF.Term; - graph: RDF.Term; - equals(other: RDF.Quad): boolean; +export type Quad_Subject = NamedNode | BlankNode | Variable; +export type Quad_Predicate = NamedNode | Variable; +export type Quad_Object = NamedNode | Literal | BlankNode | Variable; +export type Quad_Graph = DefaultGraph | NamedNode | BlankNode | Variable; + +export class BaseQuad implements RDF.BaseQuad { + constructor(subject: Term, predicate: Term, object: Term, graph?: Term); + subject: Term; + predicate: Term; + object: Term; + graph: Term; + equals(other: RDF.BaseQuad): boolean; + toJSON(): string; +} + +export class Quad extends BaseQuad implements RDF.Quad { + constructor(subject: Term, predicate: Term, object: Term, graph?: Term); + subject: Quad_Subject; + predicate: Quad_Predicate; + object: Quad_Object; + graph: Quad_Graph; + equals(other: RDF.BaseQuad): boolean; toJSON(): string; } export class Triple extends Quad implements RDF.Triple {} export namespace DataFactory { - function namedNode(value: string): RDF.NamedNode; - function blankNode(value?: string): RDF.BlankNode; - function literal(value: string | number, languageOrDatatype?: string | RDF.NamedNode): RDF.Literal; - function variable(value: string): RDF.Variable; - function defaultGraph(): RDF.DefaultGraph; - function triple(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term): RDF.Quad; - function quad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term): RDF.Quad; + function namedNode(value: string): NamedNode; + function blankNode(value?: string): BlankNode; + function literal(value: string | number, languageOrDatatype?: string | RDF.NamedNode): Literal; + function variable(value: string): Variable; + function defaultGraph(): DefaultGraph; + function quad(subject: RDF.Quad_Subject, predicate: RDF.Quad_Predicate, object: RDF.Quad_Object, graph?: RDF.Quad_Graph): Quad; + function quad(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object'], graph?: Q_In['graph']): Q_Out; + function triple(subject: RDF.Quad_Subject, predicate: RDF.Quad_Predicate, object: RDF.Quad_Object): Quad; + function triple(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object']): Q_Out; } export type ErrorCallback = (err: Error, result: any) => void; -export type QuadCallback = (result: Quad) => void; -export type QuadPredicate = (result: Quad) => boolean; +export type QuadCallback = (result: Q) => void; +export type QuadPredicate = (result: Q) => boolean; export type OTerm = RDF.Term | string | null; export type Logger = (message?: any, ...optionalParams: any[]) => void; -export interface BlankTriple { - predicate: RDF.Term; - object: RDF.Term; +export interface BlankTriple { + predicate: Q['predicate']; + object: Q['object']; } export interface ParserConstructor { - new (options?: ParserOptions): N3Parser; - (options?: ParserOptions): N3Parser; + new (options?: ParserOptions): N3Parser; + (options?: ParserOptions): N3Parser; } export const Parser: ParserConstructor; @@ -111,19 +140,19 @@ export interface ParserOptions { baseIRI?: string; } -export type ParseCallback = (error: Error, quad: Quad, prefixes: Prefixes) => void; +export type ParseCallback = (error: Error, quad: Q, prefixes: Prefixes) => void; -export interface N3Parser { - parse(input: string, callback: ParseCallback): void; +export interface N3Parser { + parse(input: string, callback: ParseCallback): void; } export interface StreamParserConstructor { - new (options?: ParserOptions): N3StreamParser; - (options?: ParserOptions): N3StreamParser; + new (options?: ParserOptions): N3StreamParser; + (options?: ParserOptions): N3StreamParser; } export const StreamParser: StreamParserConstructor; -export interface N3StreamParser extends RDF.Stream, NodeJS.WritableStream, RDF.Sink { +export interface N3StreamParser extends RDF.Stream, NodeJS.WritableStream, RDF.Sink { // Below are the NodeJS.ReadableStream methods, // we can not extend the interface directly, // as `read` clashes with RDF.Sink. @@ -133,10 +162,10 @@ export interface N3StreamParser extends RDF.Stream, NodeJS.WritableStream, RDF.S pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: NodeJS.WritableStream | RDF.Stream): void; + pipe>(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: NodeJS.WritableStream | RDF.Stream): void; unshift(chunk: string | Buffer): void; - wrap(oldStream: NodeJS.ReadableStream | RDF.Stream): NodeJS.ReadableStream; + wrap(oldStream: NodeJS.ReadableStream | RDF.Stream): NodeJS.ReadableStream; } export interface WriterOptions { @@ -146,66 +175,66 @@ export interface WriterOptions { } export interface WriterConstructor { - new (options?: WriterOptions): N3Writer; - new (fd: any, options?: WriterOptions): N3Writer; - (options?: WriterOptions): N3Writer; - (fd: any, options?: WriterOptions): N3Writer; + new (options?: WriterOptions): N3Writer; + new (fd: any, options?: WriterOptions): N3Writer; + (options?: WriterOptions): N3Writer; + (fd: any, options?: WriterOptions): N3Writer; } export const Writer: WriterConstructor; -export interface N3Writer { - quadToString(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term): string; +export interface N3Writer { + quadToString(subject: Q['subject'], predicate: Q['predicate'], object: Q['object'], graph?: Q['graph']): string; quadsToString(quads: RDF.Quad[]): string; - addQuad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term | RDF.Term[], graph?: RDF.Term, done?: () => void): void; + addQuad(subject: Q['subject'], predicate: Q['predicate'], object: Q['object'] | Array, graph?: Q['graph'], done?: () => void): void; addQuad(quad: RDF.Quad): void; addQuads(quads: RDF.Quad[]): void; addPrefix(prefix: string, iri: RDF.NamedNode | string , done?: () => void): void; addPrefixes(prefixes: Prefixes, done?: () => void): void; end(err?: ErrorCallback, result?: string): void; - blank(predicate: RDF.Term, object: RDF.Term): RDF.Term; - blank(triple: BlankTriple | RDF.Quad | BlankTriple[] | RDF.Quad[]): RDF.Term; - list(triple: RDF.Term[]): RDF.Term[]; + blank(predicate: Q['predicate'], object: Q['object']): BlankNode; + blank(triple: BlankTriple | RDF.Quad | BlankTriple[] | RDF.Quad[]): BlankNode; + list(triple: Array): Quad_Object[]; } export interface StreamWriterConstructor { - new (options?: WriterOptions): N3StreamWriter; - new (fd: any, options?: WriterOptions): N3StreamWriter; - (options?: WriterOptions): N3StreamWriter; - (fd: any, options?: WriterOptions): N3StreamWriter; + new (options?: WriterOptions): N3StreamWriter; + new (fd: any, options?: WriterOptions): N3StreamWriter; + (options?: WriterOptions): N3StreamWriter; + (fd: any, options?: WriterOptions): N3StreamWriter; } export const StreamWriter: StreamWriterConstructor; -export interface N3StreamWriter extends NodeJS.ReadWriteStream, RDF.Source {} +export interface N3StreamWriter extends NodeJS.ReadWriteStream, RDF.Source {} -export interface N3Store extends RDF.Sink { +export interface N3Store extends RDF.Sink { readonly size: number; - addQuad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term | RDF.Term[], graph?: RDF.Term, done?: () => void): void; - addQuad(quad: RDF.Quad): void; - addQuads(quads: RDF.Quad[]): void; - removeQuad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term | RDF.Term[], graph?: RDF.Term, done?: () => void): void; - removeQuad(quad: RDF.Quad): void; - removeQuads(quads: RDF.Quad[]): void; + addQuad(subject: Q_RDF['subject'], predicate: Q_RDF['predicate'], object: Q_RDF['object'] | Array, graph?: Q_RDF['graph'], done?: () => void): void; + addQuad(quad: Q_RDF): void; + addQuads(quads: Q_RDF[]): void; + removeQuad(subject: Q_RDF['subject'], predicate: Q_RDF['predicate'], object: Q_RDF['object'] | Array, graph?: Q_RDF['graph'], done?: () => void): void; + removeQuad(quad: Q_RDF): void; + removeQuads(quads: Q_RDF[]): void; getQuads(subject: OTerm, predicate: OTerm, object: OTerm | OTerm[], graph: OTerm): Quad[]; countQuads(subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): number; - forEach(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): void; - every(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; - some(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; - getSubjects(predicate: OTerm, object: OTerm, graph: OTerm): RDF.Term[]; - forSubjects(callback: QuadCallback, predicate: OTerm, object: OTerm, graph: OTerm): void; - getPredicates(subject: OTerm, object: OTerm, graph: OTerm): RDF.Term[]; - forPredicates(callback: QuadCallback, subject: OTerm, object: OTerm, graph: OTerm): void; - getObjects(subject: OTerm, predicate: OTerm, graph: OTerm): RDF.Term[]; - forObjects(callback: QuadCallback, subject: OTerm, predicate: OTerm, graph: OTerm): void; - getGraphs(subject: OTerm, predicate: OTerm, object: OTerm): RDF.Term[]; - forGraphs(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm): void; + forEach(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): void; + every(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; + some(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; + getSubjects(predicate: OTerm, object: OTerm, graph: OTerm): Array; + forSubjects(callback: QuadCallback, predicate: OTerm, object: OTerm, graph: OTerm): void; + getPredicates(subject: OTerm, object: OTerm, graph: OTerm): Array; + forPredicates(callback: QuadCallback, subject: OTerm, object: OTerm, graph: OTerm): void; + getObjects(subject: OTerm, predicate: OTerm, graph: OTerm): Array; + forObjects(callback: QuadCallback, subject: OTerm, predicate: OTerm, graph: OTerm): void; + getGraphs(subject: OTerm, predicate: OTerm, object: OTerm): Array; + forGraphs(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm): void; createBlankNode(suggestedName?: string): BlankNode; // match, removeMatches and deleteGraph are missing for full RDF.Store adherence remove(stream: stream.Stream): EventEmitter; } export interface StoreConstructor { - new (triples?: RDF.Quad[], options?: StoreOptions): N3Store; - (triples?: RDF.Quad[], options?: StoreOptions): N3Store; + new (triples?: Q_RDF[], options?: StoreOptions): N3Store; + (triples?: Q_RDF[], options?: StoreOptions): N3Store; } export const Store: StoreConstructor; diff --git a/types/n3/n3-tests.ts b/types/n3/n3-tests.ts index f7b2db2409..58d10892da 100644 --- a/types/n3/n3-tests.ts +++ b/types/n3/n3-tests.ts @@ -77,7 +77,13 @@ function test_doc_rdf_to_triples_2() { } function test_doc_rdf_stream_to_triples_1() { - const parser: N3.N3Parser = new N3.Parser(); + interface QuadBnode extends N3.BaseQuad { + subject: N3.BlankNode; + predicate: N3.BlankNode; + object: N3.BlankNode; + graph: N3.BlankNode; + } + const parser: N3.N3Parser = new N3.Parser({factory: N3.DataFactory}); parser.parse('abc', console.log); const streamParser: N3.N3StreamParser = N3.StreamParser(); @@ -178,7 +184,26 @@ function test_doc_storing() { const bnode2: RDF.BlankNode = store.createBlankNode('abc'); const mickey: RDF.Quad = store.getQuads(N3.DataFactory.namedNode('http://ex.org/Mickey'), null, null, null)[0]; + if (mickey.object.termType === "Literal") { + console.log(mickey.object.datatype); + } console.log(mickey.subject, mickey.predicate, mickey.object, '.'); + + interface N3QuadGeneralized extends N3.BaseQuad { + subject: N3.Quad_Subject | N3.BlankNode | N3.Literal; + predicate: N3.Quad_Predicate | N3.BlankNode | N3.Literal; + object: N3.Quad_Object | N3.BlankNode | N3.Literal; + graph: N3.Quad_Graph | N3.BlankNode | N3.Literal; + } + interface RDFQuadGeneralized extends RDF.BaseQuad { + subject: RDF.Quad_Subject | RDF.BlankNode | RDF.Literal; + predicate: RDF.Quad_Predicate | RDF.BlankNode | RDF.Literal; + object: RDF.Quad_Object | RDF.BlankNode | RDF.Literal; + graph: RDF.Quad_Graph | RDF.BlankNode | RDF.Literal; + } + const storeGeneralized = new N3.Store(); + // storeGeneralized. + storeGeneralized.addQuad(N3.DataFactory.namedNode('http://ex.org/Pluto'), N3.DataFactory.blankNode(), N3.DataFactory.namedNode('http://ex.org/Dog')); } function test_doc_utility() { diff --git a/types/n3/tslint.json b/types/n3/tslint.json index d88586e5bd..e27ad90359 100644 --- a/types/n3/tslint.json +++ b/types/n3/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 999e1c2b5c..51f6c8a3fc 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -7351,7 +7351,7 @@ declare namespace Office { declare namespace Office { namespace MailboxEnums { /** - * Specifies which string formatting to apply to an attachment's content. + * Specifies the formatting that applies to an attachment's content. * * [Api set: Mailbox Preview] * diff --git a/types/pbf/index.d.ts b/types/pbf/index.d.ts index fdcb9b53ce..692ca491bf 100644 --- a/types/pbf/index.d.ts +++ b/types/pbf/index.d.ts @@ -9,7 +9,7 @@ declare class Pbf { type: number; length: number; - constructor(buffer?: Uint8Array); + constructor(buffer?: Uint8Array|ArrayBuffer); destroy(): void; readFields(readField: (tag: number, result?: T, pbf?: Pbf) => void, result?: T, end?: number): T; diff --git a/types/pbf/pbf-tests.ts b/types/pbf/pbf-tests.ts index c0a8556c42..f6914f5e13 100644 --- a/types/pbf/pbf-tests.ts +++ b/types/pbf/pbf-tests.ts @@ -2,6 +2,7 @@ import Pbf = require('pbf'); const pbf = new Pbf(new Uint8Array(1)); new Pbf(); +new Pbf(new ArrayBuffer(8)); pbf.buf; pbf.pos; pbf.type; diff --git a/types/prompts/index.d.ts b/types/prompts/index.d.ts new file mode 100644 index 0000000000..152d6326e8 --- /dev/null +++ b/types/prompts/index.d.ts @@ -0,0 +1,76 @@ +// Type definitions for prompts 1.1 +// Project: https://github.com/terkelg/prompts +// Definitions by: Berkay GURSOY +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = prompts; + +declare function prompts(questions: prompts.PromptObject | prompts.PromptObject[], options?: prompts.Options): any; + +declare namespace prompts { + // Circular reference from prompts + const prompt: any; + + function inject(obj: any): void; + + namespace inject { + const prototype: { + }; + } + + namespace prompts { + function autocomplete(args: PromptObject): any; + + function confirm(args: PromptObject): void; + + function invisible(args: PromptObject): any; + + function list(args: PromptObject): any; + + function multiselect(args: PromptObject): any; + + function number(args: PromptObject): void; + + function password(args: PromptObject): any; + + function select(args: PromptObject): void; + + function text(args: PromptObject): void; + + function toggle(args: PromptObject): void; + } + + interface Choice { + title: string; + value: string; + } + + interface Options { + onSubmit: (prompt: PromptObject, answer: any, answers: any[]) => void; + onCancel: (prompt: PromptObject, answers: any) => void; + } + + interface PromptObject { + type: string | ((prev: any, values: any, prompt: PromptObject) => void); + name: string | ((prev: any, values: any, prompt: PromptObject) => void); + message?: string | ((prev: any, values: any, prompt: PromptObject) => void); + initial?: string; + style?: string; + format?: ((prev: any, values: any, prompt: PromptObject) => void); + validate?: ((prev: any, values: any, prompt: PromptObject) => void); + onState?: ((prev: any, values: any, prompt: PromptObject) => void); + min?: number; + max?: number; + float?: boolean; + round?: number; + increment?: number; + seperator?: string; + active?: string; + inactive?: string; + choices?: Choice[]; + hint?: string; + suggest?: ((prev: any, values: any, prompt: PromptObject) => void); + limit?: number; + } +} diff --git a/types/prompts/prompts-tests.ts b/types/prompts/prompts-tests.ts new file mode 100644 index 0000000000..0b89cb3721 --- /dev/null +++ b/types/prompts/prompts-tests.ts @@ -0,0 +1,8 @@ +import prompts = require("prompts"); + +const response = prompts({ + type: 'number', + name: 'value', + message: 'Input value to double:', + validate: (value: any) => value < 0 ? `Cant be less than zero` : true +}); diff --git a/types/prompts/tsconfig.json b/types/prompts/tsconfig.json new file mode 100644 index 0000000000..e8a46be254 --- /dev/null +++ b/types/prompts/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", + "prompts-tests.ts" + ] +} \ No newline at end of file diff --git a/types/prompts/tslint.json b/types/prompts/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/prompts/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/puppeteer-core/index.d.ts b/types/puppeteer-core/index.d.ts new file mode 100644 index 0000000000..0afa8ae704 --- /dev/null +++ b/types/puppeteer-core/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for puppeteer-core 1.9 +// Project: https://github.com/GoogleChrome/puppeteer#readme +// Definitions by: Fumiaki Matsushima +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export * from "puppeteer"; diff --git a/types/puppeteer-core/puppeteer-core-tests.ts b/types/puppeteer-core/puppeteer-core-tests.ts new file mode 100644 index 0000000000..6e5c38c98e --- /dev/null +++ b/types/puppeteer-core/puppeteer-core-tests.ts @@ -0,0 +1,12 @@ +import * as puppeteer from "puppeteer-core"; + +(async () => { + const browser = await puppeteer.connect(); + const page = await browser.newPage(); + await page.goto("https://example.com", { + referer: 'http://google.com', + }); + await page.screenshot({ path: "example.png" }); + + browser.close(); +})(); diff --git a/types/puppeteer-core/tsconfig.json b/types/puppeteer-core/tsconfig.json new file mode 100644 index 0000000000..d22fa100f6 --- /dev/null +++ b/types/puppeteer-core/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom", "es2017"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "puppeteer-core-tests.ts"] +} diff --git a/types/puppeteer-core/tslint.json b/types/puppeteer-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/puppeteer-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rdf-data-model/index.d.ts b/types/rdf-data-model/index.d.ts index 9c15063eee..ea82a0e8f7 100644 --- a/types/rdf-data-model/index.d.ts +++ b/types/rdf-data-model/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rdf-ext/rdf-data-model // Definitions by: Ruben Taelman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as RDF from "rdf-js"; diff --git a/types/rdf-js/index.d.ts b/types/rdf-js/index.d.ts index 9911043b48..41491d8d09 100644 --- a/types/rdf-js/index.d.ts +++ b/types/rdf-js/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for the RDFJS specification 1.0 +// Type definitions for the RDFJS specification 2.0 // Project: https://github.com/rdfjs/representation-task-force // Definitions by: Ruben Taelman +// Laurens Rietveld // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -12,32 +14,19 @@ import { EventEmitter } from "events"; /* https://github.com/rdfjs/representation-task-force/blob/master/interface-spec.md#data-interfaces */ /** - * Abstract interface for RDF terms (subject, predicate, object or graph). + * Contains an Iri, RDF blank Node, RDF literal, variable name, or a default graph + * @see NamedNode + * @see BlankNode + * @see Literal + * @see Variable + * @see DefaultGraph */ -export interface Term { - /** - * Contains a value that identifies the concrete interface of the term, - * since Term itself is not directly instantiated. - * - * Possible values include "NamedNode", "BlankNode", "Literal", "Variable" and "DefaultGraph". - */ - termType: "NamedNode" | "BlankNode" | "Literal" | "Variable" | "DefaultGraph"; - /** - * Refined by each interface which extends Term - */ - value: string; - - /** - * @param other The term to compare with. - * @return If the termType is equal and the contents are equal (as defined by concrete subclasses). - */ - equals(other: Term): boolean; -} +export type Term = NamedNode | BlankNode | Literal | Variable | DefaultGraph; /** * Contains an IRI. */ -export interface NamedNode extends Term { +export interface NamedNode { /** * Contains the constant "NamedNode". */ @@ -57,7 +46,7 @@ export interface NamedNode extends Term { /** * Contains an RDF blank node. */ -export interface BlankNode extends Term { +export interface BlankNode { /** * Contains the constant "BlankNode". */ @@ -80,7 +69,7 @@ export interface BlankNode extends Term { /** * An RDF literal, containing a string with an optional language tag and/or datatype. */ -export interface Literal extends Term { +export interface Literal { /** * Contains the constant "Literal". */ @@ -111,7 +100,7 @@ export interface Literal extends Term { /** * A variable name. */ -export interface Variable extends Term { +export interface Variable { /** * Contains the constant "Variable". */ @@ -132,7 +121,7 @@ export interface Variable extends Term { * An instance of DefaultGraph represents the default graph. * It's only allowed to assign a DefaultGraph to the .graph property of a Quad. */ -export interface DefaultGraph extends Term { +export interface DefaultGraph { /** * Contains the constant "DefaultGraph". */ @@ -149,45 +138,101 @@ export interface DefaultGraph extends Term { equals(other: Term): boolean; } +/** + * The subject, which is a NamedNode, BlankNode or Variable. + * @see NamedNode + * @see BlankNode + * @see Variable + */ +export type Quad_Subject = NamedNode | BlankNode | Variable; + +/** + * The predicate, which is a NamedNode or Variable. + * @see NamedNode + * @see Variable + */ +export type Quad_Predicate = NamedNode | Variable; + +/** + * The object, which is a NamedNode, Literal, BlankNode or Variable. + * @see NamedNode + * @see Literal + * @see BlankNode + * @see Variable + */ +export type Quad_Object = NamedNode | Literal | BlankNode | Variable; + +/** + * The named graph, which is a DefaultGraph, NamedNode, BlankNode or Variable. + * @see DefaultGraph + * @see NamedNode + * @see BlankNode + * @see Variable + */ +export type Quad_Graph = DefaultGraph | NamedNode | BlankNode | Variable; + +/** + * An RDF quad, taking any Term in its positions, containing the subject, predicate, object and graph terms. + */ +export interface BaseQuad { + /** + * The subject. + * @see Quad_Subject + */ + subject: Term; + /** + * The predicate. + * @see Quad_Predicate + */ + predicate: Term; + /** + * The object. + * @see Quad_Object + */ + object: Term; + /** + * The named graph. + * @see Quad_Graph + */ + graph: Term; + + /** + * @param other The term to compare with. + * @return True if and only if the argument is a) of the same type b) has all components equal. + */ + equals(other: BaseQuad): boolean; +} + /** * An RDF quad, containing the subject, predicate, object and graph terms. */ -export interface Quad { +export interface Quad extends BaseQuad { /** - * The subject, which is a NamedNode, BlankNode or Variable. - * @see NamedNode - * @see BlankNode - * @see Variable + * The subject. + * @see Quad_Subject */ - subject: Term; + subject: Quad_Subject; /** - * The predicate, which is a NamedNode or Variable. - * @see NamedNode - * @see Variable + * The predicate. + * @see Quad_Predicate */ - predicate: Term; + predicate: Quad_Predicate; /** - * The object, which is a NamedNode, Literal, BlankNode or Variable. - * @see NamedNode - * @see Literal - * @see BlankNode - * @see Variable + * The object. + * @see Quad_Object */ - object: Term; + object: Quad_Object; /** - * The named graph, which is a DefaultGraph, NamedNode, BlankNode or Variable. - * @see DefaultGraph - * @see NamedNode - * @see BlankNode - * @see Variable + * The named graph. + * @see Quad_Graph */ - graph: Term; + graph: Quad_Graph; /** * @param other The term to compare with. * @return True if and only if the argument is a) of the same type b) has all components equal. */ - equals(other: Quad): boolean; + equals(other: BaseQuad): boolean; } /** @@ -252,7 +297,7 @@ export interface DataFactory { * @see Triple * @see DefaultGraph */ - triple(subject: Term, predicate: Term, object: Term): Quad; + triple(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object']): Q_Out; /** * @param subject The quad subject term. @@ -262,7 +307,7 @@ export interface DataFactory { * @return A new instance of Quad. * @see Quad */ - quad(subject: Term, predicate: Term, object: Term, graph?: Term): Quad; + quad(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object'], graph?: Q_In['graph']): Q_Out; } /* Stream Interfaces */ @@ -281,14 +326,14 @@ export interface DataFactory { * Optional events: * * prefix(prefix: string, iri: RDF.NamedNode): This event is emitted every time a prefix is mapped to some IRI. */ -export interface Stream extends EventEmitter { +export interface Stream extends EventEmitter { /** * This method pulls a quad out of the internal buffer and returns it. * If there is no quad available, then it will return null. * * @return A quad from the internal buffer, or null if none is available. */ - read(): Quad; + read(): Q; } /** @@ -298,7 +343,7 @@ export interface Stream extends EventEmitter { * * For example, parsers and transformations which generate quads can implement the Source interface. */ -export interface Source { +export interface Source { /** * Returns a stream that processes all quads matching the pattern. * @@ -308,8 +353,7 @@ export interface Source { * @param graph The optional exact graph or graph regex to match. * @return The resulting quad stream. */ - match(subject?: Term | RegExp, predicate?: Term | RegExp, object?: Term | RegExp, graph?: Term | RegExp) - : Stream; + match(subject?: Term | RegExp, predicate?: Term | RegExp, object?: Term | RegExp, graph?: Term | RegExp): Stream; } /** @@ -319,7 +363,7 @@ export interface Source { * * For example parsers, serializers, transformations and stores can implement the Sink interface. */ -export interface Sink { +export interface Sink { /** * Consumes the given stream. * @@ -330,7 +374,7 @@ export interface Sink { * @param stream The stream that will be consumed. * @return The resulting event emitter. */ - import(stream: Stream): EventEmitter; + import(stream: Stream): EventEmitter; } /** @@ -341,7 +385,7 @@ export interface Sink { * * Access to stores LDP or SPARQL endpoints can be implemented with a Store inteface. */ -export interface Store extends Source, Sink { +export interface Store extends Source, Sink { /** * Removes all streamed quads. * @@ -351,7 +395,7 @@ export interface Store extends Source, Sink { * @param stream The stream that will be consumed. * @return The resulting event emitter. */ - remove(stream: Stream): EventEmitter; + remove(stream: Stream): EventEmitter; /** * All quads matching the pattern will be removed. @@ -377,5 +421,5 @@ export interface Store extends Source, Sink { * @param graph The graph term or string to match. * @return The resulting event emitter. */ - deleteGraph(graph: Term | string): EventEmitter; + deleteGraph(graph: Q['graph'] | string): EventEmitter; } diff --git a/types/rdf-js/rdf-js-tests.ts b/types/rdf-js/rdf-js-tests.ts index 5dad2d1ce9..eb55002149 100644 --- a/types/rdf-js/rdf-js-tests.ts +++ b/types/rdf-js/rdf-js-tests.ts @@ -1,5 +1,5 @@ -import { BlankNode, DataFactory, DefaultGraph, Literal, NamedNode, Quad, Sink, Source, Store, Stream, Triple, Term, - Variable } from "rdf-js"; +import { BlankNode, DataFactory, DefaultGraph, Literal, NamedNode, Quad, BaseQuad, Sink, Source, Store, Stream, Triple, Term, + Variable, Quad_Graph } from "rdf-js"; import { EventEmitter } from "events"; function test_terms() { @@ -7,6 +7,9 @@ function test_terms() { // so this does not have to be functional. const someTerm: Term = {}; + if (someTerm.termType === 'Literal') { + console.log(someTerm.datatype); + } const namedNode: NamedNode = {}; const termType1: string = namedNode.termType; const value1: string = namedNode.value; @@ -66,9 +69,16 @@ function test_datafactory() { const variable: Variable = dataFactory.variable ? dataFactory.variable('v1') : {}; - const term: Term = {}; + const term: NamedNode = {}; const triple: Quad = dataFactory.triple(term, term, term); - const quad: Quad = dataFactory.quad(term, term, term, term); + interface QuadBnode extends BaseQuad { + subject: Term; + predicate: Term; + object: Term; + graph: Term; + } + const quad = dataFactory.quad(literal1, blankNode1, term, term); + const hasBnode = quad.predicate.termType === "BlankNode"; } function test_stream() { @@ -88,6 +98,7 @@ function test_stream() { const matchStream9: Stream = source.match(term, term, term, /.*/); const sink: Sink = {}; + const graph: Quad_Graph = {}; const eventEmitter1: EventEmitter = sink.import(stream); const store: Store = {}; @@ -103,6 +114,6 @@ function test_stream() { const eventEmitter9: EventEmitter = store.removeMatches(term, term, /.*/); const eventEmitter10: EventEmitter = store.removeMatches(term, term, term, term); const eventEmitter11: EventEmitter = store.removeMatches(term, term, term, /.*/); - const eventEmitter12: EventEmitter = store.deleteGraph(term); + const eventEmitter12: EventEmitter = store.deleteGraph(graph); const eventEmitter13: EventEmitter = store.deleteGraph('http://example.org'); } diff --git a/types/rdf-js/tslint.json b/types/rdf-js/tslint.json index 3db14f85ea..e27ad90359 100644 --- a/types/rdf-js/tslint.json +++ b/types/rdf-js/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/react-images/index.d.ts b/types/react-images/index.d.ts new file mode 100644 index 0000000000..4f3e1c8893 --- /dev/null +++ b/types/react-images/index.d.ts @@ -0,0 +1,157 @@ +// Type definitions for react-images 0.5 +// Project: http://jossmac.github.io/react-images +// Definitions by: Konstantin Lukaschenko +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +declare class Lightbox extends React.Component { + constructor(props: LightboxProps); +} + +export interface LightboxProps { + /** + * Array of image objects. Required. + */ + images: Image[]; + + /** + * Allow users to exit the lightbox by clicking the backdrop. Default value: false. + */ + backdropClosesModal?: boolean; + + /** + * Supports keyboard input - esc, arrow left, and arrow right. Default value: true + */ + enableKeyboardInput?: boolean; + + /** + * The index of the image to display initially. Default value: 0 + */ + currentImage?: number; + + /** + * An array of elements to display as custom controls on the top of lightbox. Default value: undefined + */ + customControls?: Array>; + + /** + * Whether or not the lightbox is displayed. Default value: false; + */ + isOpen?: boolean; + + /** + * Based on the direction the user is navigating, preload the next available image. Default value: true + */ + preloadNextImage?: boolean; + + /** + * Optionally display a close "X" button in top right corner. Default value: true + */ + showCloseButton?: boolean; + + /** + * Optionally display image index, e.g., "3 of 20". Default value: true + */ + showImageCount?: boolean; + + /** + * Maximum width of the carousel; defaults to 1024px + */ + width?: number; + + /** + * Spinner component. + */ + spinner?: () => React.ReactElement; + + /** + * Color of spinner. Default value: 'white' + */ + spinnerColor?: string; + + /** + * Size of spinner. Default value: 100 + */ + spinnerSize?: number; + + /** + * Determines whether scrolling is prevented via react-scrolllock. Default value: true + */ + preventScroll?: boolean; + + /** + * Optionally display thumbnails beneath the Lightbox + */ + showThumbnails?: boolean; + + /** + * The image count separator. Default value: ' of ' + */ + imageCountSeparator?: string; + + /** + * Customize right arrow title. Default value: ' Next (Right arrow key) ' + */ + rightArrowTitle?: string; + + /** + * Custom of left arrow title. Default value: ' Previous (Left arrow key) ' + */ + leftArrowTitle?: string; + + /** + * Custom close esc title. Default value: ' Close (Esc) ' + */ + closeButtonTitle?: string; + + /** + * Handle closing of the lightbox. Required. + */ + onClose: () => void; + + /** + * Fired on request of the previous image. + */ + onClickPrev?: () => void; + + /** + * Fired on request of the next image. + */ + onClickNext?: () => void; + + /** + * Handle click on image. + */ + onClickImage?: (e: React.MouseEvent) => void; + + /** + * Handle click on thumbnail. + */ + onClickThumbnail?: (index: number) => void; +} + +export interface Image { + /** + * The source of the image. Required. + */ + src: string; + + /** + * array of strings or string + */ + srcSet?: string | string[]; + + /** + * The image caption. + */ + caption?: string; + + /** + * The alt text for the image. + */ + alt?: string; +} + +export default Lightbox; diff --git a/types/react-images/react-images-tests.tsx b/types/react-images/react-images-tests.tsx new file mode 100644 index 0000000000..8b63d4bc8a --- /dev/null +++ b/types/react-images/react-images-tests.tsx @@ -0,0 +1,39 @@ +import * as React from 'react'; +import Lightbox, { Image } from 'react-images'; + +interface ImageGalerieState { + selectedImage: number; + showLightbox: boolean; +} + +class ImageGalerie extends React.Component { + constructor(props: undefined) { + super(props); + this.state = {selectedImage: 0, showLightbox: true}; + } + + render() { + const images: Image[] = [ + { + src: "http://localhost:8080/img1.jpg", + alt: "Image 1", + caption: "Image 1", + }, + { + src: "http://localhost:8080/img2.jpg", + alt: "Image 2", + caption: "Image 2", + }]; + + return this.setState({showLightbox: false})} + onClickImage={e => {}} + onClickNext={() => this.setState({selectedImage: (this.state.selectedImage + 1) % images.length})} + onClickPrev={() => this.setState({selectedImage: this.state.selectedImage === 0 ? images.length : this.state.selectedImage - 1})} + showThumbnails={true} + onClickThumbnail={(index) => this.setState({selectedImage: index})} + />; + } +} diff --git a/types/react-images/tsconfig.json b/types/react-images/tsconfig.json new file mode 100644 index 0000000000..3a505430d8 --- /dev/null +++ b/types/react-images/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-images-tests.tsx" + ] +} diff --git a/types/react-images/tslint.json b/types/react-images/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-images/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index 928be92c6c..2184deed0b 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for redux-first-router 1.10 +// Type definitions for redux-first-router 2.1 // Project: https://github.com/faceyspacey/redux-first-router#readme // Definitions by: Valbrand // viggyfresh // janb87 // corydeppen // jscinoz +// surgeboris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -64,8 +65,10 @@ export interface ReceivedActionMeta { }; } +export type HistoryEntries = Array<{ pathname: string }>; + export interface HistoryData { - entries: Array<{ pathname: string }>; + entries: HistoryEntries; index: number; length: number; } @@ -203,6 +206,8 @@ export interface Options { initialDispatch?: boolean; querySerializer?: QuerySerializer; navigators?: NavigatorsConfig; + initialEntries?: HistoryEntries; + createHistory?(): History; } export type Params = object; @@ -227,9 +232,8 @@ export function canGoBack(): boolean; export function canGoForward(): boolean; export function connectRoutes( - history: History, routesMap: RoutesMap, - options?: Options + options?: Options, ): { reducer: Reducer>; middleware: Middleware; diff --git a/types/redux-first-router/redux-first-router-tests.ts b/types/redux-first-router/redux-first-router-tests.ts index cf3f772d9e..5297be4175 100644 --- a/types/redux-first-router/redux-first-router-tests.ts +++ b/types/redux-first-router/redux-first-router-tests.ts @@ -58,7 +58,7 @@ const { enhancer, initialDispatch, thunk, -} = connectRoutes(history, routesMap, { +} = connectRoutes(routesMap, { initialDispatch: false, onBeforeChange: (dispatch, getState) => { dispatch; // $ExpectType Dispatch @@ -71,7 +71,8 @@ const { title: state => { const title = state.location.pathname; // $ExpectType string return title; - } + }, + createHistory: () => history, }); const dumbMiddleware: Middleware = store => next => action => next(action); diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index b6871ca3c4..f80d5acc40 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -139,7 +139,7 @@ declare namespace sequelize { * @see http://docs.sequelizejs.com/en/latest/api/associations/belongs-to/ * @see Instance */ - interface BelongsToCreateAssociationMixin { + interface BelongsToCreateAssociationMixin { /** * Create a new instance of the associated model and associate it with this. * @param values The values used to create the association. @@ -148,7 +148,7 @@ declare namespace sequelize { ( values?: TAttributes, options?: BelongsToCreateAssociationMixinOptions | CreateOptions | BelongsToSetAssociationMixinOptions - ): Promise; + ): Promise; } /** diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index 0592a36df4..4e0aa9a73d 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -220,7 +220,7 @@ barcode.setProduct(product, { save: true }).then(() => { }); barcode.createProduct(); barcode.createProduct({ id: 1, name: 'Crowbar' }); -barcode.createProduct({ id: 1 }, { save: true, silent: true }).then((product) => { }); +barcode.createProduct({ id: 1 }, { save: true, silent: true }).then((product: ProductInstance) => { }); product.getWarehouse(); product.getWarehouse({ scope: null }).then(w => w.capacity); @@ -365,7 +365,7 @@ interface ProductInstance extends Sequelize.Instance, Product // belongsTo association mixins: getWarehouse: Sequelize.BelongsToGetAssociationMixin; setWarehouse: Sequelize.BelongsToSetAssociationMixin; - createWarehouse: Sequelize.BelongsToCreateAssociationMixin; + createWarehouse: Sequelize.BelongsToCreateAssociationMixin; }; interface BarcodeAttributes { @@ -378,7 +378,7 @@ interface BarcodeInstance extends Sequelize.Instance, Barcode // belongsTo association mixins: getProduct: Sequelize.BelongsToGetAssociationMixin; setProduct: Sequelize.BelongsToSetAssociationMixin; - createProduct: Sequelize.BelongsToCreateAssociationMixin; + createProduct: Sequelize.BelongsToCreateAssociationMixin; }; interface WarehouseAttributes { diff --git a/types/subtitle/index.d.ts b/types/subtitle/index.d.ts new file mode 100644 index 0000000000..f6048acc4a --- /dev/null +++ b/types/subtitle/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for subtitle 2.0 +// Project: https://github.com/gsantiago/subtitle.js#readme +// Definitions by: Low Jeng Lam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface subTitleType { + start: number | string; + end: number | string; + text: string; + setting?: string; +} + +export function parse(srtOrVtt: string): subTitleType[]; +export function stringify(captions: ReadonlyArray): string; +export function resync(captions: ReadonlyArray, time: number): subTitleType[]; +export function toMs(timestamp: string): number; +export function toSrtTime(timestamp: number): string; +export function toVttTime(timestamp: number): string; diff --git a/types/subtitle/subtitle-tests.ts b/types/subtitle/subtitle-tests.ts new file mode 100644 index 0000000000..2f733b4a54 --- /dev/null +++ b/types/subtitle/subtitle-tests.ts @@ -0,0 +1,27 @@ +import * as Subtitle from 'subtitle'; + +Subtitle.parse(""); + +const subtitles = [ + { + start: '00:00:20,000', + end: '00:00:24,400', + text: 'Bla Bla Bla Bla' + }, + { + start: 24600, + end: 27800, + text: 'Bla Bla Bla Bla', + settings: 'align:middle line:90%' + } + ]; + +const srt = Subtitle.stringify(subtitles); + +const newSubtitles: Subtitle.subTitleType[] = Subtitle.resync(subtitles, 1000); + +Subtitle.toMs('00:00:24,400'); + +Subtitle.toSrtTime(24400); + +Subtitle.toVttTime(24400); diff --git a/types/subtitle/tsconfig.json b/types/subtitle/tsconfig.json new file mode 100644 index 0000000000..b4463890d2 --- /dev/null +++ b/types/subtitle/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", + "subtitle-tests.ts" + ] +} diff --git a/types/subtitle/tslint.json b/types/subtitle/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/subtitle/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sumo-logger/index.d.ts b/types/sumo-logger/index.d.ts index 8e3cd3a27e..555e15a919 100644 --- a/types/sumo-logger/index.d.ts +++ b/types/sumo-logger/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for js-logging-sdk 1.3 -// Project: https://github.com/SumoLogic/js-logging-sdk +// Type definitions for js-sumo-logger 1.6 +// Project: https://github.com/SumoLogic/js-sumo-logger // Definitions by: forabi // clementallen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -70,9 +70,14 @@ declare namespace SumoLogger { sourceName?: string; /** - * This value enabled and disables sending data as graphite metrics + * This value enables and disables sending data as graphite metrics */ graphite?: boolean; + + /** + * This value enables and disables sending data as a raw string + */ + raw?: boolean; } interface PerMessageOptions { diff --git a/types/v-chart-plugin/index.d.ts b/types/v-chart-plugin/index.d.ts new file mode 100644 index 0000000000..d7c0e6659d --- /dev/null +++ b/types/v-chart-plugin/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for v-chart-plugin 0.2 +// Project: https://github.com/ignoreintuition/v-chart-plugin +// Definitions by: Nate Mara +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { PluginObject } from 'vue'; + +declare const Chart: PluginObject; + +export default Chart; diff --git a/types/v-chart-plugin/package.json b/types/v-chart-plugin/package.json new file mode 100644 index 0000000000..faefc1b2f7 --- /dev/null +++ b/types/v-chart-plugin/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "vue": ">=2.0.0" + } +} diff --git a/types/v-chart-plugin/tsconfig.json b/types/v-chart-plugin/tsconfig.json new file mode 100644 index 0000000000..675dead5d7 --- /dev/null +++ b/types/v-chart-plugin/tsconfig.json @@ -0,0 +1,16 @@ +{ + "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", "v-chart-plugin-tests.ts"] +} diff --git a/types/v-chart-plugin/tslint.json b/types/v-chart-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/v-chart-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/v-chart-plugin/v-chart-plugin-tests.ts b/types/v-chart-plugin/v-chart-plugin-tests.ts new file mode 100644 index 0000000000..ef320b492f --- /dev/null +++ b/types/v-chart-plugin/v-chart-plugin-tests.ts @@ -0,0 +1,5 @@ +import Vue from 'vue'; + +import Chart from 'v-chart-plugin'; + +Vue.use(Chart); diff --git a/types/yazl/index.d.ts b/types/yazl/index.d.ts index 45288eaad5..41b18b8a15 100644 --- a/types/yazl/index.d.ts +++ b/types/yazl/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for yazl 2.4 // Project: https://github.com/thejoshwolfe/yazl // Definitions by: taoqf +// Sean Marvi Oliver Genabe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 /// -import { Readable, Writable } from 'stream'; +import { Readable } from 'stream'; import { Buffer } from 'buffer'; export interface Options { @@ -36,7 +37,7 @@ export interface DosDateTime { export class ZipFile { addFile(realPath: string, metadataPath: string, options?: Partial): void; - outputStream: Writable; + outputStream: Readable; addReadStream(input: Readable, metadataPath: string, options?: Partial): void; addBuffer(buffer: Buffer, metadataPath: string, options?: Partial): void; end(optoins?: EndOptions, finalSizeCallback?: () => void): void; diff --git a/types/yazl/yazl-tests.ts b/types/yazl/yazl-tests.ts index dfc5cd3c27..50e371a62a 100644 --- a/types/yazl/yazl-tests.ts +++ b/types/yazl/yazl-tests.ts @@ -1,4 +1,5 @@ import { ZipFile } from "yazl"; +import { Readable } from "stream"; import fs = require('fs'); const zipfile = new ZipFile(); @@ -6,6 +7,8 @@ zipfile.addFile("file1.txt", "file1.txt"); // (add only files, not directories) zipfile.addFile("path/to/file.txt", "path/in/zipfile.txt"); // pipe() can be called any time after the constructor +// $ExpectType Readable +zipfile.outputStream; zipfile.outputStream.pipe(fs.createWriteStream("output.zip")).on("close", () => { console.log("done"); });