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/notNeededPackages.json b/notNeededPackages.json index 010aa98828..f81984b338 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -930,6 +930,12 @@ "sourceRepoURL": "https://github.com/blakeembrey/lower-case-first", "asOfVersion": "1.0.1" }, + { + "libraryName": "mali", + "typingsPackageName": "mali", + "sourceRepoURL": "https://github.com/malijs/mali", + "asOfVersion": "0.9.2" + }, { "libraryName": "maquette", "typingsPackageName": "maquette", @@ -1200,6 +1206,12 @@ "sourceRepoURL": "https://github.com/react-ga/react-ga", "asOfVersion": "2.3.0" }, + { + "libraryName": "react-i18next", + "typingsPackageName": "react-i18next", + "sourceRepoURL": "https://github.com/i18next/react-i18next", + "asOfVersion": "8.1.0" + }, { "libraryName": "react-monaco-editor", "typingsPackageName": "react-monaco-editor", 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/react-i18next/tslint.json b/types/ale-url-parser/tslint.json similarity index 100% rename from types/react-i18next/tslint.json rename to types/ale-url-parser/tslint.json diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index b148e84599..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,8 +174,38 @@ 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(); +index.browseAll('query'); +index.browseAll('', { + filters: 'dog', +}); + +let hits: Object[] = []; + +browser.on('result', function onResult(content) { + hits = hits.concat(content.hits); +}); + +browser.on('end', function onEnd() { + const _message = `We got ${hits.length} hits` +}); + +browser.on('error', function onError(err) { + throw err; +}); + +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 a0bb0e0e45..04291996ba 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1,11 +1,14 @@ -// Type definitions for algoliasearch-client-js 3.27.0 +// Type definitions for algoliasearch-client-js 3.30.0 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene // Aurélien Hervé // Samuel Vaillant +// Kai Eichinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.8 + +type Omit = Pick> declare namespace algoliasearch { /** @@ -611,6 +614,11 @@ declare namespace algoliasearch { options: SearchForFacetValues.Parameters, cb: (err: Error, res: SearchForFacetValues.Response) => void ): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void; /** * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -620,7 +628,7 @@ declare namespace algoliasearch { * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string): Promise; + browse(query: string, parameters?: BrowseParameters): Promise; /** * Browse an index from a cursor * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -638,7 +646,7 @@ declare namespace algoliasearch { * Browse an entire index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseAll(): Promise; + browseAll(query?: string, parameters?: BrowseParameters): Browser; /** * Clear an index content * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex @@ -966,6 +974,22 @@ declare namespace algoliasearch { query: string; processingTimeMS: number; } + type BrowseParameters = Omit< + QueryParameters, + | "typoTolerance" + | "distinct" + | "facets" + | "getRankingInfo" + | "attributesToHighlight" + | "attributesToSnippet" + > + interface Browser { + on(type: "error", cb: (err: Error) => void): void + on(type: "end", cb: () => void): void + on(type: "stop", cb: () => void): void + on(type: "result", cb: (content: BrowseResponse) => void): void + stop(): void + } /** * Describes a synonym object */ @@ -1099,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; /** @@ -1222,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[][]; /** @@ -1286,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[][]; /** @@ -1302,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[]; /** @@ -1322,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[]; /** @@ -1337,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; @@ -1464,7 +1498,7 @@ declare namespace algoliasearch { interface Task { taskID: number; createdAt: string; - objectID?: string; + objectID?: string; } interface TaskStatus { @@ -1747,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?: { @@ -1796,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 4f068d5647..ce58d6a428 100644 --- a/types/algoliasearch/lite/index.d.ts +++ b/types/algoliasearch/lite/index.d.ts @@ -1,12 +1,15 @@ -// Type definitions for algoliasearch-client-js 3.27.0 +// Type definitions for algoliasearch-client-js 3.30.0 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene // Aurélien Hervé // Samuel Vaillant // Claas Brüggemann +// Kai Eichinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.8 + +type Omit = Pick> declare namespace algoliasearch { /** @@ -130,6 +133,11 @@ declare namespace algoliasearch { options: SearchForFacetValues.Parameters, cb: (err: Error, res: SearchForFacetValues.Response) => void ): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void; /** * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -139,7 +147,7 @@ declare namespace algoliasearch { * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string): Promise; + browse(query: string, parameters?: BrowseParameters): Promise; /** * Browse an index from a cursor * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -194,114 +202,122 @@ declare namespace algoliasearch { query: string; processingTimeMS: number; } - + type BrowseParameters = Omit< + QueryParameters, + | "typoTolerance" + | "distinct" + | "facets" + | "getRankingInfo" + | "attributesToHighlight" + | "attributesToSnippet" + > interface QueryParameters { /** * 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; /** @@ -311,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[][]; /** @@ -375,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[][]; /** @@ -391,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[]; /** @@ -411,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[]; /** @@ -426,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; @@ -530,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?: { @@ -579,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/ali-app/ali-app-tests.ts b/types/ali-app/ali-app-tests.ts new file mode 100644 index 0000000000..a42301aed1 --- /dev/null +++ b/types/ali-app/ali-app-tests.ts @@ -0,0 +1,2153 @@ +(() => { + // https://docs.alipay.com/mini/api/ui-navigate + my.navigateTo({ + url: 'new_page?count=100' + }); + // test.js + Page({ + onLoad(query: any) { + my.alert({ + content: JSON.stringify(query), + }); + } + }); + my.redirectTo({ + url: 'new_page?count=100' + }); + // 注意:调用 navigateTo 跳转时,调用该方法的页面会被加入堆栈, + // 而 redirectTo 方法则不会。见下方示例代码 + + // 此处是one页面 + my.navigateTo({ + url: 'two?pageId=10000' + }); + + // 此处是two页面 + my.navigateTo({ + url: 'one?pageId=99999' + }); + + // 在three页面内 navigateBack,将返回one页面 + my.navigateBack({ + delta: 2 + }); + my.reLaunch({ + url: '/page/index' + }); + my.setNavigationBar({ + title: '你好', + backgroundColor: '#108ee9', + success() { + my.alert({ + content: '设置成功', + }); + }, + fail() { + my.alert({ + content: '设置是失败', + }); + }, + }); + my.showNavigationBarLoading(); + my.hideNavigationBarLoading(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-tabbar + my.switchTab({ + url: '/home' + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-feedback + my.alert({ + title: '亲', + content: '您本月的账单已出', + buttonText: '我知道了', + success: () => { + my.alert({ + title: '用户点击了「我知道了」', + }); + }, + }); + my.confirm({ + title: '温馨提示', + content: '您是否想查询快递单号:1234567890', + confirmButtonText: '马上查询', + cancelButtonText: '暂不需要', + success: (result) => { + my.alert({ + title: `${result.confirm}`, + }); + }, + }); + my.prompt({ + title: '标题单行', + message: '说明当前状态、提示用户解决方案,最好不要超过两行。', + placeholder: '给朋友留言', + okButtonText: '确定', + cancelButtonText: '取消', + success: (result) => { + my.alert({ + title: JSON.stringify(result), + }); + }, + }); + my.showToast({ + type: 'success', + content: '操作成功', + duration: 3000, + success: () => { + my.alert({ + title: 'toast 消失了', + }); + }, + }); + my.hideToast(); + my.showLoading({ + content: '加载中...', + delay: 1000, + }); + + my.hideLoading(); + + Page({ + onLoad() { + my.showLoading(); + const that = this; + setTimeout(() => { + my.hideLoading({ + page: that, // 防止执行时已经切换到其它页面,page指向不准确 + }); + }, 4000); + } + }); + my.showNavigationBarLoading(); + my.hideNavigationBarLoading(); + my.showActionSheet({ + title: '支付宝-ActionSheet', + items: ['菜单一', '菜单二', '菜单三', '菜单四', '菜单五'], + badges: [ + { index: 0, type: 'none' }, + { index: 1, type: 'point' }, + { index: 2, type: 'num', text: '99' }, + { index: 3, type: 'text', text: '推荐' }, + { index: 4, type: 'more' }], + cancelButtonText: '取消好了', + success: (res) => { + const btn = res.index === -1 ? '取消' : `第${res.index}个`; + my.alert({ + title: `你点了${btn}按钮` + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-pulldown + Page({ + onPullDownRefresh() { + my.stopPullDownRefresh(); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-contact + my.choosePhoneContact({ + success: (res) => { + my.alert({ + content: `姓名:${res.name}\n号码:${res.mobile}` + }); + } + }); + my.chooseAlipayContact({ + count: 2, + success: (res) => { + my.alert({ + content: 'chooseAlipayContact response: ' + JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + content: 'chooseAlipayContact response: ' + JSON.stringify(res) + }); + } + }); + my.chooseContact({ + chooseType: 'multi', // 多选模式 + includeMe: true, // 包含自己 + includeMobileContactMode: 'known', // 仅包含双向手机通讯录联系人,也即双方手机通讯录都存有对方号码的联系人 + multiChooseMax: 3, // 最多能选择三个联系人 + multiChooseMaxTips: '超过选择的最大人数了', + success: (res) => { + my.alert({ + content: 'chooseContact : ' + JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + content: 'chooseContact : ' + JSON.stringify(res) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-city + my.chooseCity({ + cities: [ + { + city: '朝阳区', + adCode: '110105', + spell: 'chaoyang' + }, + { + city: '海淀区', + adCode: '110108', + spell: 'haidian' + }, + { + city: '丰台区', + adCode: '110106', + spell: 'fengtai' + }, + { + city: '东城区', + adCode: '110101', + spell: 'dongcheng' + }, + { + city: '西城区', + adCode: '110102', + spell: 'xicheng' + }, + { + city: '房山区', + adCode: '110111', + spell: 'fangshan' + } + ], + hotCities: [ + { + city: '朝阳区', + adCode: '110105' + }, + { + city: '海淀区', + adCode: '110108' + }, + { + city: '丰台区', + adCode: '110106' + } + ], + success: (res) => { + my.alert({ + content: `${res.city}:${res.adCode}` + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-date + my.datePicker({ + format: 'yyyy-MM-dd', + currentDate: '2012-12-12', + startDate: '2012-12-10', + endDate: '2012-12-15', + success: (res) => { + my.alert({ + content: res.date, + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-animation + const animation = my.createAnimation({ + transformOrigin: "top right", + duration: 3000, + timeFunction: "ease-in-out", + delay: 100, + }); + Page({ + data: { + animationInfo: {} + }, + onShow() { + const animation = my.createAnimation({ + duration: 1000, + timeFunction: 'ease-in-out', + }); + + this.animation = animation; + + animation.scale(3, 3).rotate(60).step(); + + this.setData({ + animationInfo: animation.export() + }); + + setTimeout(() => { + animation.translate(35).step(); + this.setData({ + animationInfo: animation.export(), + }); + }, 1500); + }, + rotateAndScale(this: my.Page) { + // 旋转同时放大 + this.animation.rotate(60).scale(3, 3).step(); + this.setData({ + animationInfo: this.animation.export(), + }); + }, + rotateThenScale(this: my.Page) { + // 先旋转后放大 + this.animation.rotate(60).step(); + this.animation.scale(3, 3).step(); + this.setData({ + animationInfo: this.animation.export(), + }); + }, + rotateAndScaleThenTranslate(this: my.Page) { + // 先旋转同时放大,然后平移 + this.animation.rotate(60).scale(3, 3).step(); + this.animation.translate(100, 100).step({ duration: 2000 }); + this.setData({ + animationInfo: this.animation.export() + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-canvas + const ctx = my.createCanvasContext('awesomeCanvas'); + ctx.toTempFilePath({ + success() { }, + }); + + ctx.setTextAlign("left"); + ctx.fillText("Hello world", 0, 100); + + ctx.setTextBaseline("top"); + ctx.fillText("Hello world", 0, 100); + + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 100, 175); + ctx.draw(); + + ctx.setStrokeStyle('blue'); + ctx.strokeRect(50, 50, 100, 175); + ctx.draw(); + + ctx.setFillStyle('red'); + ctx.setShadow(15, 45, 45, 'yellow'); + ctx.fillRect(20, 20, 100, 175); + ctx.draw(); + + const grd = ctx.createLinearGradient(10, 10, 150, 10); + grd.addColorStop(0, 'yellow'); + grd.addColorStop(1, 'blue'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + grd.addColorStop(0.36, 'orange'); + grd.addColorStop(0.56, 'cyan'); + grd.addColorStop(0.63, 'yellow'); + grd.addColorStop(0.76, 'blue'); + grd.addColorStop(0.54, 'green'); + grd.addColorStop(1, 'purple'); + grd.addColorStop(0.4, 'red'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.lineTo(250, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(20, 35); + ctx.lineTo(250, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(20); + ctx.moveTo(20, 50); + ctx.lineTo(250, 55); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(25); + ctx.moveTo(20, 80); + ctx.lineTo(250, 85); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(150, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(20); + ctx.moveTo(20, 70); + ctx.lineTo(250, 80); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(25, 80); + ctx.lineTo(250, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(35, 47); + ctx.lineTo(230, 120); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(20, 30); + ctx.lineTo(150, 70); + ctx.lineTo(20, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(20); + ctx.moveTo(100, 20); + ctx.lineTo(280, 80); + ctx.lineTo(100, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(20); + ctx.moveTo(60, 25); + ctx.lineTo(180, 80); + ctx.lineTo(90, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(15); + ctx.moveTo(130, 70); + ctx.lineTo(250, 50); + ctx.lineTo(230, 100); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.draw(); + + ctx.rect(20, 20, 250, 80); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); + + ctx.fillRect(20, 20, 250, 80); + ctx.setFillStyle('blue'); + ctx.draw(); + + ctx.setStrokeStyle('blue'); + ctx.strokeRect(20, 20, 250, 80); + ctx.draw(); + + ctx.setFillStyle('blue'); + ctx.fillRect(250, 10, 250, 200); + ctx.setFillStyle('yellow'); + ctx.fillRect(0, 0, 150, 200); + ctx.clearRect(10, 10, 150, 75); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(200, 20); + ctx.lineTo(200, 200); + ctx.fill(); + ctx.draw(); + + ctx.rect(20, 20, 110, 40); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.rect(20, 30, 150, 40); + + ctx.setFillStyle('yellow'); + ctx.fillRect(20, 80, 150, 40); + + ctx.rect(20, 150, 150, 40); + + ctx.setFillStyle('red'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 10); + ctx.lineTo(150, 150); + ctx.stroke(); + ctx.draw(); + + ctx.rect(10, 10, 100, 30); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 50); + + ctx.setStrokeStyle('yellow'); + ctx.strokeRect(15, 75, 200, 35); + + ctx.rect(20, 200, 150, 30); + + ctx.setStrokeStyle('red'); + ctx.stroke(); + ctx.draw(); + + ctx.rect(20, 20, 150, 50); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 40); + + ctx.setFillStyle('yellow'); + ctx.fillRect(20, 170, 150, 40); + + ctx.rect(10, 100, 100, 30); + + ctx.setFillStyle('red'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 20); + ctx.lineTo(150, 150); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); + + ctx.rect(20, 20, 150, 50); + ctx.closePath(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 40); + + ctx.setFillStyle('red'); + ctx.fillRect(20, 80, 120, 30); + + ctx.rect(20, 150, 150, 40); + + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 15); + + ctx.moveTo(20, 55); + ctx.lineTo(120, 60); + ctx.stroke(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.rect(20, 20, 80, 30); + ctx.lineTo(120, 80); + ctx.stroke(); + ctx.draw(); + + ctx.arc(200, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('#CCCCCC'); + ctx.fill(); + + ctx.beginPath(); + ctx.moveTo(50, 65); + ctx.lineTo(170, 80); + ctx.moveTo(200, 35); + ctx.lineTo(200, 235); + ctx.setStrokeStyle('#AAAAAA'); + ctx.stroke(); + + ctx.setFontSize(12); + ctx.setFillStyle('yellow'); + ctx.fillText('0', 165, 78); + ctx.fillText('0.6*PI', 96, 148); + ctx.fillText('1*PI', 15, 57); + ctx.fillText('1.7*PI', 94, 20); + + ctx.beginPath(); + ctx.arc(200, 85, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(200, 35, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(450, 60, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(150, 35, 50, 0, 1.8 * Math.PI); + ctx.setStrokeStyle('#666666'); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.arc(30, 30, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(250, 25, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(20, 100, 2, 0, 2 * Math.PI); + ctx.arc(200, 100, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.setFillStyle('yellow'); + ctx.setFontSize(14); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.lineTo(30, 100); + ctx.lineTo(150, 75); + + ctx.moveTo(250, 30); + ctx.lineTo(250, 80); + ctx.lineTo(70, 75); + ctx.setStrokeStyle('#EEEEEE'); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.bezierCurveTo(30, 150, 250, 150, 180, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.arc(30, 30, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(250, 20, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(30, 200, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.setFillStyle('black'); + ctx.setFontSize(12); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.lineTo(30, 150); + ctx.lineTo(250, 30); + ctx.setStrokeStyle('#AAAAAA'); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.quadraticCurveTo(30, 150, 250, 25); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); + + ctx.strokeRect(15, 15, 30, 25); + ctx.scale(3, 3); + ctx.strokeRect(15, 15, 30, 25); + ctx.scale(3, 3); + ctx.strokeRect(15, 15, 30, 25); + + ctx.draw(); + + ctx.strokeRect(200, 20, 180, 150); + ctx.rotate(30 * Math.PI / 180); + ctx.strokeRect(200, 20, 180, 150); + ctx.rotate(30 * Math.PI / 180); + ctx.strokeRect(200, 20, 180, 150); + + ctx.draw(); + + ctx.strokeRect(20, 20, 250, 80); + ctx.translate(30, 30); + ctx.strokeRect(20, 20, 250, 80); + ctx.translate(30, 30); + ctx.strokeRect(20, 20, 250, 80); + + ctx.draw(); + + ctx.setFontSize(14); + ctx.fillText('14', 20, 20); + ctx.setFontSize(22); + ctx.fillText('22', 40, 40); + ctx.setFontSize(30); + ctx.fillText('30', 60, 60); + ctx.setFontSize(38); + ctx.fillText('38', 90, 90); + + ctx.draw(); + + ctx.setFontSize(42); + ctx.fillText('Hello', 30, 30); + ctx.fillText('alipay', 200, 200); + + ctx.draw(); + + ctx.drawImage('https://img.alicdn.com/tfs/TB1GvVMj2BNTKJjy0FdXXcPpVXa-520-280.jpg', 2, 2, 250, 80); + ctx.draw(); + + ctx.setFillStyle('yellow'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('red'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); + + ctx.setLineDash([5, 15, 25]); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + + ctx.draw(); + + ctx.rotate(45 * Math.PI / 180); + ctx.setFillStyle('red'); + ctx.fillRect(70, 0, 100, 30); + + ctx.transform(1, 1, 0, 1, 0, 0); + ctx.setFillStyle('#000'); + ctx.fillRect(0, 0, 100, 100); + + ctx.draw(); + + ctx.rotate(45 * Math.PI / 180); + ctx.setFillStyle('red'); + ctx.fillRect(70, 0, 100, 30); + + ctx.setTransform(1, 1, 0, 1, 0, 0); + ctx.setFillStyle('#000'); + ctx.fillRect(0, 0, 100, 100); + + ctx.draw(); + + ctx.save(); + ctx.setFillStyle('red'); + ctx.fillRect(20, 20, 250, 80); + + ctx.restore(); + ctx.fillRect(60, 60, 155, 130); + + ctx.draw(); + + ctx.setFillStyle('blue'); + ctx.fillRect(20, 20, 180, 80); + ctx.draw(); + ctx.fillRect(60, 60, 250, 120); + ctx.draw(true); + + ctx.font = 'italic bold 50px cursive'; + const { width } = ctx.measureText('hello world'); + console.log(width); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-map + Page({ + onReady() { + // 使用 my.createMapContext 获取 map 上下文 + this.mapCtx = my.createMapContext('userMap'); + }, + getCenterLocation(this: my.Page) { + (this.mapCtx as my.MapContext).getCenterLocation({ + success(res) { + console.log(res.longitude); + console.log(res.latitude); + } + }); + }, + moveToLocation() { + this.mapCtx.moveToLocation(); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-hidekeyboard + my.hideKeyboard(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/scroll + my.pageScrollTo({ + scrollTop: 100 + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/selector-query + Page({ + onReady() { + my.createSelectorQuery() + .select('#non-exists').boundingClientRect() + .select('#one').boundingClientRect() + .selectAll('.all').boundingClientRect() + .select('#scroll').scrollOffset() + .selectViewport().boundingClientRect() + .selectViewport().scrollOffset().exec((ret) => { + console.log(JSON.stringify(ret, null, 2)); + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ewdxl3 + my.multiLevelSelect({ + title: 'nihao', // 级联选择标题 + list: [ + { + name: "杭州市", // 条目名称 + subList: [ + { + name: "西湖区", + subList: [ + { + name: "古翠街道" + }, + { + name: "文新街道" + } + ] + }, + { + name: "上城区", + subList: [ + { + name: "延安街道" + }, + { + name: "龙翔桥街道" + } + ] + } + ]// 级联子数据列表 + } + ]// 级联数据列表 + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/openapi-authorize + my.getAuthCode({ + scopes: 'auth_user', + success: (res) => { + my.alert({ + content: res.authCode, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/userinfo + my.getAuthCode({ + scopes: 'auth_user', + success: (res) => { + my.getAuthUserInfo({ + success: (userInfo) => { + my.alert({ + content: userInfo.nickName + }); + my.alert({ + content: userInfo.avatar + }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/openapi-pay + my.tradePay({ + tradeNO: '201711152100110410533667792', // 调用统一收单交易创建接口(alipay.trade.create),获得返回字段支付宝交易号trade_no + success: (res) => { + my.alert({ + content: JSON.stringify(res), + }); + }, + fail: (res) => { + my.alert({ + content: JSON.stringify(res), + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/pay-sign + my.paySignCenter({ + // tslint:disable-next-line:max-line-length + signStr: 'biz_content%3D%257B%2522access_params%2522%253A%257B%2522channel%2522%253A%2522ALIPAYAPP%2522%257D%252C%2522external_agreement_no%2522%253A%2522xidong___2317%2522%252C%2522external_logon_id%2522%253A%252213852852877%2522%252C%2522personal_product_code%2522%253A%2522GENERAL_WITHHOLDING_P%2522%252C%2522product_code%2522%253A%2522GENERAL_WITHHOLDING%2522%252C%2522sign_scene%2522%253A%2522INDUSTRY%257CCARRENTAL%2522%252C%2522third_party_type%2522%253A%2522PARTNER%2522%257D%26sign%3Df3pjBDTRftOwXWnCqAMAnkBfGTFlcMmZI8hEgmV6uREZRXVDuLsSjD8WO%252FeZ1fjDG8GqVO9t1AN7q6yCUHKX%252Bw%252FE7efXwpVDWldr4iVuXDtNd3UJDJUiRJhIm6b73czWacVzm1XIery%252F2DyKI2y08tBf5NNWuQCC3d%252FITxziTl8%253D%26timestamp%3D2017-06-27%2B14%253A44%253A00%26sign_type%3DRSA%26notify_url%3Dhttp%253A%252F%252Fapi.test.alipay.net%252Fatinterface%252Freceive_notify.htm%26charset%3DUTF-8%26app_id%3D2017060101317939%26method%3Dalipay.user.agreement.page.sign%26return_url%3Dhttp%253A%252F%252Fapi.test.alipay.net%252Fatinterface%252Freceive_notify.htm%26version%3D1.0', + success: (res) => { + my.alert({ + title: 'success', // alert框的标题 + content: JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + title: 'fail', // alert框的标题 + content: JSON.stringify(res) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/card-voucher-ticket + my.openCardList(); + my.openMerchantCardList({ partnerId: '2088xxxxx' }); + // 传入passId来打开 + my.openCardDetail({ passId: "11xxxxx" }); + my.openVoucherList(); + my.openMerchantVoucherList({ partnerId: '2088xxxx' }); + // 传入passId来打开 + my.openVoucherDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openVoucherDetail({ + partnerId: "2018xxxx", + serialNumber: "20170921" + }); + // 传入passId来打开 + my.openKBVoucherDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openKBVoucherDetail({ + partnerId: "2088xxxx", + serialNumber: "20170921" + }); + my.openTicketList(); + my.openMerchantTicketList({ partnerId: '2088xxxx' }); + // 传入passId来打开 + my.openTicketDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openTicketDetail({ + partnerId: "2088xxxx", + serialNumber: "20170921" + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/add-card-auth + my.addCardAuth({ + url: '从 openapi 接口获取到的 url', + success: (res) => { + my.alert({ content: '授权成功' }); + }, + fail: (res) => { + my.alert({ content: '授权失败' }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/zm-service + my.startZMVerify({ + bizNo: 'your-biz-no', + success: (res) => { + my.alert({ title: 'success:' + JSON.stringify(res) }); + }, + fail: (res) => { + my.alert({ title: 'fail: ' + JSON.stringify(res) }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/zmcreditborrow + my.zmCreditBorrow({ + credit_biz: "", + out_order_no: "", + borrow_shop_name: "", + goods_name: "", + product_code: "w1010100000000002858", + rent_unit: "HOUR_YUAN", + rent_amount: "0.10", + deposit_amount: "0.50", + deposit_state: "Y", + invoke_return_url: "", + invoke_type: "TINYAPP", + borrow_time: "2017-04-27 10:01:01", + expiry_time: "2017-05-27 10:01:01", + rent_info: "2hour-free", + success: (res) => { + try { + const { resultStatus, result } = res; + switch (resultStatus) { + case '9000': + const callbackData = result.callbackData; + const decodedCallbackData = decodeURIComponent(callbackData); + const json = JSON.parse(decodedCallbackData.match(/{.*}/)!.toString()); + const jsonStr = JSON.stringify(json, null, 4); + if (json.success === true || json.success === 'true') { + // 创建订单成功, 此时可以跳转到订单详情页面 + my.alert({ content: '下单成功: ' + jsonStr }); + } else { + // 创建订单失败, 请提示用户创建失败 + my.alert({ content: '下单失败: ' + jsonStr }); + } + // (this as any as my.Page).setData({ + // callbackData, + // decodedCallbackData, + // parsedJSON: jsonStr, + // }); + break; + case '6001': + // 用户点击返回, 取消此次服务, 此时可以给提示 + my.alert({ content: '取消' }); + break; + default: + break; + } + } catch (error) { + // 异常, 请在这里提示用户稍后重试 + my.alert({ + content: '异常' + JSON.stringify(error, null, 4) + }); + } + }, + fail: (error) => { + // 调用接口失败, 请在这里提示用户稍后重试 + my.alert({ + content: '调用失败' + JSON.stringify(error, null, 4) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/templatemessage +})(); + +(() => { + // https://docs.alipay.com/mini/api/text-identification + my.textRiskIdentification({ + content: '加我支付宝', + type: ['keyword', '0', '1', '2', '3'], + success: (res) => { + my.alert({ + title: 'ok', // alert 框的标题 + content: JSON.stringify(res), + }); + }, + fail: (res) => { + my.alert({ + title: 'fail', // alert 框的标题 + content: JSON.stringify(res), + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/open-miniprogram + my.navigateToMiniProgram({ + appId: 'xxxx', + extraData: { + data1: "test" + }, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.navigateBackMiniProgram({ + extraData: { + data1: "test" + }, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + console.log(JSON.stringify(res)); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/webview-context + Page({ + onLoad() { + this.webViewContext = my.createWebViewContext('web-view-1'); + }, + // 接收来自H5的消息 + onMessage(e: any) { + console.log(e); // {'sendToMiniProgram': '0'} + // 向H5发送消息 + this.webViewContext.postMessage({ sendToWebView: '1' }); + } + }); + // H5的js代码中需要先定义my.onMessage 用于接收来自小程序的消息。 + my.onMessage = (e) => { + console.log(e); // {'sendToWebView': '1'} + }; + // H5想小程序发送消息 + my.postMessage({ sendToMiniProgram: '0' }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/media-image + const img = null as any as HTMLImageElement; + my.chooseImage({ + count: 2, + success: (res) => { + img.src = res.apFilePaths[0]; + }, + }); + my.previewImage({ + current: 2, + urls: [ + 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg', + 'https://img.alicdn.com/tps/TB1pfG4IFXXXXc6XXXXXXXXXXXX.jpg', + 'https://img.alicdn.com/tps/TB1h9xxIFXXXXbKXXXXXXXXXXXX.jpg' + ], + }); + my.saveImage({ + url: 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg' + }); + my.compressImage({ + apFilePaths: ['https://resource/apmlcc0ed184daffc5a0d8da86b2f518cf7b.image'], + // level: 1, + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + // 网络图片路径 + my.getImageInfo({ + src: 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + + // apFilePath + my.chooseImage({ + success: (res) => { + my.getImageInfo({ + src: res.apFilePaths[0], + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + }, + }); + + // 相对路径 + my.getImageInfo({ + src: 'image/api.png', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/storage + my.setStorage({ + key: 'currentCity', + data: { + cityName: '杭州', + adCode: '330100', + spell: ' hangzhou', + }, + success() { + my.alert({ content: '写入成功' }); + } + }); + my.setStorageSync({ + key: 'currentCity', + data: { + cityName: '杭州', + adCode: '330100', + spell: ' hangzhou', + } + }); + my.getStorage({ + key: 'currentCity', + success(res) { + my.alert({ content: '获取成功:' + res.data.cityName }); + }, + fail(res) { + my.alert({ content: res.errorMessage }); + } + }); + const res = my.getStorageSync({ key: 'currentCity' }); + my.alert({ + content: JSON.stringify(res.data), + }); + my.removeStorage({ + key: 'currentCity', + success() { + my.alert({ content: '删除成功' }); + } + }); + my.removeStorageSync({ + key: 'currentCity', + }); + my.clearStorage(); + my.clearStorageSync(); + my.getStorageInfo({ + success(res) { + console.log(res.keys); + console.log(res.currentSize); + console.log(res.limitSize); + } + }); + const res1 = my.getStorageInfoSync(); + console.log(res1.keys); + console.log(res1.currentSize); + console.log(res1.limitSize); +})(); + +(() => { + // https://docs.alipay.com/mini/api/file + my.chooseImage({ + success: (res) => { + my.saveFile({ + apFilePath: res.apFilePaths[0], + success: (res) => { + console.log(JSON.stringify(res)); + }, + }); + }, + }); + my.getFileInfo({ + apFilePath: 'https://resource/apml953bb093ebd2834530196f50a4413a87.video', + digestAlgorithm: 'sha1', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileInfo({ + apFilePath: 'https://resource/apml953bb093ebd2834530196f50a4413a87.video', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileList({ + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileList({ + success: (res) => { + my.removeSavedFile({ + apFilePath: res.fileList[0].apFilePath, + success: (res) => { + console.log('remove success'); + } + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/location + my.getLocation({ + success(res) { + my.hideLoading(); + console.log(res); + /* that对象为Page可以设置数据刷新界面 + that.setData({ + hasLocation: true, + location: formatLocation(res.longitude, res.latitude) + }) + */ + }, + fail() { + my.hideLoading(); + my.alert({ title: '定位失败' }); + }, + }); + my.openLocation({ + longitude: '121.549697', + latitude: '31.227250', + name: '支付宝', + address: '杨高路地铁站', + }); + my.chooseLocation({ + success: (res) => { + console.log(res); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/network + my.httpRequest({ + url: 'http://httpbin.org/post', + method: 'POST', + data: { + from: '支付宝', + production: 'AlipayJSAPI', + }, + dataType: 'json', + success(res) { + my.alert({ content: 'success' }); + }, + fail(res) { + my.alert({ content: 'fail' }); + }, + complete(res) { + my.hideLoading(); + my.alert({ content: 'complete' }); + } + }); + my.uploadFile({ + url: '请使用自己服务器地址', + fileType: 'image', + fileName: 'file', + filePath: '...', + success: (res) => { + my.alert({ + content: '上传成功' + }); + }, + }); + my.downloadFile({ + url: 'http://img.alicdn.com/tfs/TB1x669SXXXXXbdaFXXXXXXXXXX-520-280.jpg', + success({ apFilePath }) { + my.previewImage({ + urls: [apFilePath], + }); + }, + fail(res) { + my.alert({ + content: res.errorMessage || res.error, + }); + }, + }); + my.connectSocket({ + url: 'test.php', + data: {}, + header: { + 'content-type': 'application/json' + }, + method: 'GET' + }); + my.connectSocket({ + url: 'test.php', + }); + + my.onSocketOpen(() => { + console.log('WebSocket 连接已打开!'); + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onSocketOpen(this.callback); + }, + onUnload() { + my.offSocketOpen(this.callback); + }, + callback() { + }, + }); + my.connectSocket({ + url: '开发者的服务器地址' + }); + + my.onSocketOpen(() => { + console.log('WebSocket 连接已打开!'); + }); + + my.onSocketError(() => { + console.log('WebSocket 连接打开失败,请检查!'); + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onSocketError(this.callback); + }, + onUnload() { + my.offSocketError(this.callback); + }, + callback() { + my.sendSocketMessage({ + data: this.data.toSendMessage, // 需要发送的内容 + success: (res) => { + my.alert({ content: '数据发送!' + this.data.toSendMessage }); + }, + }); + }, + }); + my.connectSocket({ + url: '服务器地址' + }); + + my.onSocketMessage((res) => { + console.log('收到服务器内容:' + res.data); + }); + my.onSocketOpen(() => { + my.closeSocket(); + }); + + my.onSocketClose(() => { + console.log('WebSocket 已关闭!'); + }); + Page({ + // onLoad() { + onLaunch() { + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketClose(() => { + my.alert({ content: '连接已关闭!' }); + this.setData({ + sendMessageAbility: false, + closeLinkAbility: false, + }); + }); + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketOpen(() => { + my.alert({ content: '连接已打开!' }); + this.setData({ + sendMessageAbility: true, + closeLinkAbility: true, + }); + }); + + my.onSocketError((res) => { + my.alert({ content: 'WebSocket 连接打开失败,请检查!' + res }); + }); + + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketMessage((res) => { + my.alert({ content: '收到数据!' + JSON.stringify(res) }); + }); + }, + connect_start() { + my.connectSocket({ + url: '服务器地址', // 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名 + success: (res) => { + my.showToast({ + content: 'success', // 文字内容 + }); + }, + fail: () => { + my.showToast({ + content: 'fail', // 文字内容 + }); + } + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/can-i-use + my.canIUse('getFileInfo'); + my.canIUse('closeSocket.object.code'); + my.canIUse('getLocation.object.type'); + my.canIUse('getSystemInfo.return.brand'); + my.canIUse('lifestyle'); + my.canIUse('button.open-type.share'); +})(); + +(() => { + // https://docs.alipay.com/mini/api/sdk-version + console.log(my.SDKVersion); +})(); + +(() => { + // https://docs.alipay.com/mini/api/system-info + Page({ + data: { + systemInfo: {} + }, + getSystemInfoPage(this: my.Page) { + my.getSystemInfo({ + success: (res) => { + this.setData({ + systemInfo: res + }); + } + }); + }, + }); + Page({ + data: { + systemInfo: {} + }, + getSystemInfoSyncPage(this: my.Page) { + this.setData({ + systemInfo: my.getSystemInfoSync() + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/network-status + Page({ + data: { + hasNetworkType: false + }, + getNetworkType(this: my.Page) { + my.getNetworkType({ + success: (res) => { + this.setData({ + hasNetworkType: true, + networkType: res.networkType + }); + } + }); + }, + clear(this: my.Page) { + this.setData({ + hasNetworkType: false, + networkType: '' + }); + }, + }); + my.onNetworkStatusChange((res) => { + console.log(JSON.stringify(res)); + }); + my.offNetworkStatusChange(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/clipboard + Page({ + data: { + text: '3.1415926', + copy: '', + }, + + handlePaste(this: my.Page) { + my.getClipboard({ + success: ({ text }) => { + this.setData({ copy: text }); + }, + }); + }, + }); + Page({ + data: { + text: '3.1415926', + copy: '', + }, + + handleCopy() { + my.setClipboard({ + text: this.data.text, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/shake + Page({ + watchShake() { + my.watchShake({ + success() { + console.log('动起来了'); + my.alert({ title: '动起来了 o.o' }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/vibrate + Page({ + vibrate() { + my.vibrate({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); + Page({ + vibrateLong() { + my.vibrateLong({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); + Page({ + vibrateShort() { + my.vibrateShort({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/macke-call + Page({ + makePhoneCall() { + my.makePhoneCall({ number: '95888' }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/get-server-time + // getServerTime(){ + // my.getServerTime({ + // success: (res) => { + // my.alert({ + // title: res.time, + // }); + // }, + // }); + // }; +})(); + +(() => { + // https://docs.alipay.com/mini/api/user-capture-screen + my.onUserCaptureScreen(() => { + my.alert({ + content: '收到用户截屏事件' + }); + }); + my.offUserCaptureScreen(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/screen-brightness + my.setKeepScreenOn({ + keepScreenOn: true, + success: (res) => { + }, + fail: (res) => { + }, + }); + my.getScreenBrightness({ + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + }, + }); + my.setScreenBrightness({ + brightness: 0.5, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/show-auth-guide + my.showAuthGuide({ + authType: 'LBSSERVICE' + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/scan + Page({ + scan() { + my.scan({ + type: 'qr', + success: (res) => { + my.alert({ title: res.code }); + }, + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/bluetooth-intro + // 初始化 + my.openBluetoothAdapter({ + success: (res) => { + console.log(res); + } + }); + // 注册发现事件 + my.onBluetoothDeviceFound({ + success: (res) => { + const device = res.devices[0]; + // 连接发现的设备 + my.connectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + // 停止搜索 + my.stopBluetoothDevicesDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + } + }); + const deviceId = 'test'; + const serviceId = 'test'; + const characteristicId = 'test'; + // 注册连接事件 + my.onBLEConnectionStateChanged({ + success: (res) => { + console.log(res); + if (res.connected) { + // 开始读写notify等操作 + my.notifyBLECharacteristicValueChange({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + } + } + }); + // 注册接收read或notify的数据 + my.onBLECharacteristicValueChange({ + success: (res) => { + console.log(res); + } + }); + // 开始搜索 + my.startBluetoothDevicesDiscovery({ + services: ['fff0'], + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + // 断开连接 + my.disconnectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + // 注销事件 + my.offBluetoothDeviceFound(); + my.offBLEConnectionStateChanged(); + my.offBLECharacteristicValueChange(); + + // 退出蓝牙模块 + my.closeBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/bluetooth-api + my.openBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.closeBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBluetoothAdapterState({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.startBluetoothDevicesDiscovery({ + services: ['fff0'], + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.stopBluetoothDevicesDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBluetoothDevices({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getConnectedBluetoothDevices({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + const deviceId = 'test'; + const serviceId = 'test'; + const characteristicId = 'test'; + my.connectBLEDevice({ + // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取 + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.disconnectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.writeBLECharacteristicValue({ + deviceId, + serviceId, + characteristicId, + value: 'fffe', + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.readBLECharacteristicValue({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.notifyBLECharacteristicValueChange({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBLEDeviceServices({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBLEDeviceCharacteristics({ + deviceId, + serviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onBluetoothDeviceFound(this.callback); + }, + onUnload() { + my.offBluetoothDeviceFound(this.callback); + }, + callback(res: any) { + console.log(res); + }, + }); + my.offBluetoothDeviceFound(); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onBLECharacteristicValueChange(this.callback); + }, + onUnload() { + my.offBLECharacteristicValueChange(this.callback); + }, + callback(res: any) { + console.log(res); + }, + }); + my.offBLECharacteristicValueChange(); + my.offBLEConnectionStateChanged(); + my.offBluetoothAdapterStateChange(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/yqleyc + my.startBeaconDiscovery({ + uuids: ['uuid1', 'uuid2'], + success: (res) => { + console.log(res); + }, + fail: () => { + }, + complete: () => { + } + }); + + my.stopBeaconDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + my.getBeacons({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + my.onBeaconUpdate({ + success: (res) => { + }, + }); + + my.onBeaconServiceChange({ + success: (res) => { + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/data-safe + Page({ + data: { + inputValue: '', + outputValue: '', + }, + onInput(this: my.Page, e: any) { + this.setData({ inputValue: e.detail.value }); + }, + onEncrypt(this: my.Page) { + my.rsa({ + action: 'encrypt', + // 设置公钥 + // tslint:disable-next-line:max-line-length + key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKmi0dUSVQ04hL6GZGPMFK8+d6\nGzulagP27qSUBYxIJfE04KT+OHVeFFb6K+8nWDea5mkmZrIgp022zZVDgdWPNM62\n3ouBwHlsfm2ekey8PpQxfXaj8lhM9t8rJlC4FEc0s8Qp7Q5/uYrowQbT9m6t7BFK\n3egOO2xOKzLpYSqfbQIDAQAB', + text: this.data.inputValue, + success: (result) => { + this.setData({ outputValue: result.text }); + }, + fail(e) { + my.alert({ + content: e.errorMessage || e.error, + }); + }, + }); + }, + onDecrypt(this: my.Page) { + my.rsa({ + action: 'decrypt', + text: this.data.inputValue, + // 设置私钥 + // tslint:disable-next-line:prefer-template + key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMqaLR1RJVDTiEvo\n' + + 'ZkY8wUrz53obO6VqA/bupJQFjEgl8TTgpP44dV4UVvor7ydYN5rmaSZmsiCnTbbN\n' + + 'lUOB1Y80zrbei4HAeWx+bZ6R7Lw+lDF9dqPyWEz23ysmULgURzSzxCntDn+5iujB\n' + + 'BtP2bq3sEUrd6A47bE4rMulhKp9tAgMBAAECgYBjsfRLPdfn6v9hou1Y2KKg+F5K\n' + + 'ZsY2AnIK+6l+sTAzfIAx7e0ir7OJZObb2eyn5rAOCB1r6RL0IH+MWaN+gZANNG9g\n' + + 'pXvRgcZzFY0oqdMZDuSJjpMTj7OEUlPyoGncBfvjAg0zdt9QGAG1at9Jr3i0Xr4X\n' + + '6WrFhtfVlmQUY1VsoQJBAPK2Qj/ClkZNtrSDfoD0j083LcNICqFIIGkNQ+XeuTwl\n' + + '+Gq4USTyaTOEe68MHluiciQ+QKvRAUd4E1zeZRZ02ikCQQDVscINBPTtTJt1JfAo\n' + + 'wRfTzA0Lvgig136xLLeQXREcgq1lzgkf+tGyUGYoy9BXsV0mOuYAT9ldja4jhJeq\n' + + 'cEulAkEAuSJ5KjV9dyb0RIFAz5C8d8o5KAodwaRIxJkPv5nCZbT45j6t9qbJxDg8\n' + + 'N+vghDlHI4owvl5wwVlAO8iQBy8e8QJBAJe9CVXFV0XJR/n/XnER66FxGzJjVi0f\n' + + '185nOlFARI5CHG5VxxT2PUCo5mHBl8ctIj+rQvalvGs515VQ6YEVDCECQE3S0AU2\n' + + 'BKyFVNtTpPiTyRUWqig4EbSXwjXdr8iBBJDLsMpdWsq7DCwv/ToBoLg+cQ4Crc5/\n5DChU8P30EjOiEo=', + success: (result) => { + this.setData({ outputValue: result.text }); + }, + fail(e) { + my.alert({ + content: e.errorMessage || e.error, + }); + }, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/share_app + Page({ + onShareAppMessage() { + return { + title: '小程序示例', + desc: '小程序官方示例Demo,展示已支持的接口能力及组件。', + path: 'page/component/component-pages/view/view?param=123' + }; + }, + }); + + my.hideShareMenu(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/report + my.reportAnalytics('purchase', { + status: 200, + reason: 'ok' + }); +})(); diff --git a/types/ali-app/index.d.ts b/types/ali-app/index.d.ts new file mode 100644 index 0000000000..82f7b2bf27 --- /dev/null +++ b/types/ali-app/index.d.ts @@ -0,0 +1,3265 @@ +// Type definitions for ali-app 1.0 +// Project: https://docs.alipay.com/mini/api/overview (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// 公共部分 +declare namespace my { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: any; + /** 开发者服务器返回的 HTTP 状态码 */ + status: number; + /** 开发者服务器返回的 HTTP Response Header */ + headers: object; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + apFilePath: string; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion +} + +// 界面 +declare namespace my { + //#region 导航栏 https://docs.alipay.com/mini/api/ui-navigate + interface NavigateToOptions extends BaseOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + } + /** + * 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 + * + * 注意:为了不让用户在使用小程序时造成困扰, + * 我们规定页面路径只能是五层,请尽量避免多层级的交互方式。 + */ + function navigateTo(options: NavigateToOptions): void; + + interface RedirectToOptions extends BaseOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + } + /** + * 关闭当前页面,跳转到应用内的某个页面。 + */ + function redirectTo(options: RedirectToOptions): void; + + interface NavigateBackOptions extends BaseOptions { + /** 返回的页面数,如果 delta 大于现有打开的页面数,则返回到首页 */ + delta: number; + } + /** + * 关闭当前页面,返回上一级或多级页面。可通过 getCurrentPages 获取当前的页面栈信息,决定需要返回几层。 + */ + function navigateBack(options?: NavigateBackOptions): void; + + interface ReLaunchOptions extends BaseOptions { + /** + * 需要跳转的应用内页面路径 , 路径后可以带参数。 + * 参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔 + * 如 'path?key=value&key2=value2',如果跳转的页面路径是 tabBar 页面则不能带参数 + */ + url: string; + } + /** + * 关闭所有页面,打开到应用内的某个页面。 + */ + function reLaunch(options?: ReLaunchOptions): void; + + interface SetNavigationBarOptions extends BaseOptions { + /** 页面标题 */ + title: string; + /** 图片连接地址,必须是https,请使用3x高清图片。若设置了image则title参数失效 */ + image: string; + /** 导航栏背景色,支持十六进制颜色值 */ + backgroundColor: string; + /** 导航栏底部边框颜色,支持十六进制颜色值。若设置了 backgroundColor,则borderBottomColor 不会生效,默认会和 backgroundColor 颜色一样 */ + borderBottomColor: string; + /** 是否重置导航栏为支付宝默认配色,默认 false */ + reset: boolean; + } + /** + * 动态设置当前页面的标题。 + */ + function setNavigationBar(options: Partial): void; + + /** + * 显示导航栏 loading + */ + function showNavigationBarLoading(): void; + + /** 隐藏导航栏 loading。 */ + function hideNavigationBarLoading(): void; + //#endregion + + //#region TabBar https://docs.alipay.com/mini/api/ui-tabbar + interface SwitchTabOptions extends BaseOptions { + /** + * 需要跳转的 tabBar 页面的路径 + * (需在 app.json 的 tabBar 字段定义的页面),路径后不能带参数 + */ + url: string; + } + /** + * 跳转到指定 tabBar 页面,并关闭其他所有非 tabBar 页面 + */ + function switchTab(options: SwitchTabOptions): void; + //#endregion + + //#region 交互反馈 https://docs.alipay.com/mini/api/ui-feedback + + interface AlertOptions extends BaseOptions { + /** alert框的标题 */ + title: string; + /** alert框的内容 */ + content: string; + /** 按钮文字,默认确定 */ + buttonText: string; + } + function alert(options: Partial): void; + + interface ConfirmOptions extends BaseOptions { + /** confirm框的标题 */ + title: string; + /** confirm框的内容 */ + content: string; + /** 确认按钮文字,默认‘确定’ */ + confirmButtonText: string; + /** 确认按钮文字,默认‘取消’ */ + cancelButtonText: string; + success(result: { confirm: boolean; }): void; + } + function confirm(options: Partial): void; + + interface PromptOptions extends BaseOptions { + /** prompt框标题 */ + title?: string; + /** prompt框文本,默认‘请输入内容’ */ + message?: string; + /** 输入框内的提示文案 */ + placeholder?: string; + /** message对齐方式,可用枚举left/center/right,iOS ‘center’, android ‘left’ */ + align?: 'left' | 'center' | 'right' | string; + /** 确认按钮文字,默认‘确定’ */ + okButtonText: string; + /** 确认按钮文字,默认‘取消’ */ + cancelButtonText: string; + success(result: { ok: boolean; inputValue: string; }): void; + } + function prompt(options: PromptOptions): void; + + interface ToastOptions extends BaseOptions { + /** + * 文字内容 + */ + content: string; + /** toast 类型,展示相应图标,默认 none,支持 success / fail / exception / none’。其中 exception 类型必须传文字信息 */ + type?: 'none' | 'success' | 'fail' | 'exception' | string; + /** + * 显示时长,单位为 ms,默认 2000 + */ + duration?: number; + } + /** + * 显示消息提示框 + */ + function showToast(options: Partial): void; + function hideToast(): void; + + interface LoadingOptions extends BaseOptions { + /** + * loading的文字内容 + */ + content?: string; + /** + * 延迟显示,单位 ms,默认 0。如果在此时间之前调用了 my.hideLoading 则不会显示 + */ + delay?: number; + } + /** + * 显示加载提示 + */ + function showLoading(options?: LoadingOptions): void; + interface HideLoadingOptions { + /** + * 体指当前page实例,某些场景下,需要指明在哪个page执行hideLoading。 + */ + page: any; + } + /** + * 隐藏消息提示框 + */ + function hideLoading(options?: HideLoadingOptions): void; + + interface Badge { + /** 需要飘红的选项的索引,从0开始 */ + index: number; + /** + * 飘红类型,支持 none(无红点)/ point(纯红点) / num(数字红点)/ text(文案红点)/ more(...) + * + */ + type: 'none' | 'point' | 'num' | 'text' | 'more' | string; + + /** + * 自定义飘红文案: + * + * 1、type为none/point/more时本文案可不填 + * 2、type为num时本文案为小数或<=0均不显示, >100 显示"..." + */ + text: string; + } + interface ActionSheetOptions extends BaseOptions { + /** 菜单标题 */ + title?: string; + /** + * 菜单按钮文字数组 + */ + items: string[]; + /** + * 取消按钮文案。默认为‘取消’。注:Android平台此字段无效,不会显示取消按钮。 + */ + cancelButtonText?: string; + /** + * (iOS特殊处理)指定按钮的索引号,从0开始,使用场景:需要删除或清除数据等类似场景,默认红色 + */ + destructiveBtnIndex?: number; + /** + * 需飘红选项的数组,数组内部对象字段见下表 + */ + badges?: Array>; + /** + * 接口调用成功的回调函数 + */ + success?(res: { + /** + * 用户点击的按钮,从上到下的顺序,从0开始 + */ + index: number; + }): void; + } + /** + * 显示操作菜单 + */ + function showActionSheet(options: ActionSheetOptions): void; + //#endregion + + //#region 下拉刷新 https://docs.alipay.com/mini/api/ui-pulldown + /** + * Page 实现的接口对象 + */ + interface PageOptions { + /** + * 下拉刷新 + * 在 Page 中定义 onPullDownRefresh 处理函数,监听该页面用户下拉刷新事件。 + * 需要在页面对应的 .json 配置文件中配置 "pullRefresh": true 选项,才能开启下拉刷新事件。 + * 当处理完数据刷新后,调用 my.stopPullDownRefresh 可以停止当前页面的下拉刷新。 + */ + onPullDownRefresh?(this: Page): void; + } + /** + * 停止当前页面的下拉刷新。 + */ + function stopPullDownRefresh(): void; + //#endregion + + //#region 联系人 https://docs.alipay.com/mini/api/ui-contact + interface ChoosePhoneContactOptions extends BaseOptions { + success(result: { + name: string; // 选中的联系人姓名 + mobile: string; // 选中的联系人手机号 + }): void; + /** + * 10 没有权限 + * 11 用户取消操作(或设备未授权使用通讯录) + */ + fail?(error: 10 | 11): void; + } + /** + * 选择本地系统通信录中某个联系人的电话。 + */ + function choosePhoneContact(options: ChoosePhoneContactOptions): void; + + interface ChooseAlipayContactOptions extends BaseOptions { + /** 单次最多选择联系人个数,默认 1,最大 10 */ + count: number; + success(result: { + realName: string; // 账号的真实姓名 + mobile: string; // 账号对应的手机号码 + email: string; // 账号的邮箱 + avatar: string; // 账号的头像链接 + userId: string; // 支付宝账号唯一 userId + }): void; + /** + * 10 没有权限 + * 11 用户取消操作(或设备未授权使用通讯录) + */ + fail?(error: 10 | 11): void; + } + /** + * 唤起支付宝通讯录,选择一个或者多个支付宝联系人。 + */ + function chooseAlipayContact(options: ChooseAlipayContactOptions): void; + + interface ContactsDic { + /** + * 支付宝账号唯一 userId + */ + userId: string; + /** + * 账号的头像链接 + */ + avatar: string; + /** + * 账号对应的手机号码 + */ + mobile: string; + /** + * 账号的真实姓名 + */ + realName: string; + /** + * 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 + */ + displayName: string; // 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 + } + interface ChooseContactOptions extends BaseOptions { + /** 选择类型,值为single(单选)或者 multi(多选) */ + chooseType: 'single' | 'multi' | string; + /** 包含手机通讯录联系人的模式:默认为不包含(none)、或者仅仅包含双向通讯录联系人(known)、或者包含手机通讯录联系人(all) */ + includeMobileContactMode?: 'none' | 'known' | 'all' | string; + /** 是否包含自己 */ + includeMe?: boolean; + /** 最大选择人数,仅 chooseType 为 multi 时才有效 */ + multiChooseMax?: number; + /** 多选达到上限的文案,仅 chooseType 为 multi 时才有效 */ + multiChooseMaxTips?: string; + + success(result: { + contactsDicArray: ContactsDic[]; + }): void; + } + /** + * 唤起选人组件,默认只包含支付宝联系人,可以通过修改参数包含手机通讯录联系人或者双向通讯录联系人。 + */ + function chooseContact(options: ChooseContactOptions): void; + //#endregion + + //#region 选择城市 https://docs.alipay.com/mini/api/ui-city + interface City { + city: string; // 城市名 + adCode: string; // 行政区划代码 + spell?: string; // 城市名对应拼音拼写,方便用户搜索 + } + interface ChooseCityOptions extends BaseOptions { + showLocatedCity: boolean; // 是否显示当前定位城市,默认 false + showHotCities: boolean; // 是否显示热门城市,默认 true + cities: City[]; // 自定义城市列表,列表内对象字段见下表 + hotCities: City[]; // 自定义热门城市列表,列表内对象字段见下表 + success(result: { city: string; adCode: string; }): void; + } + /** + * 打开城市选择列表 + * + * 如果用户没有选择任何城市直接点击了返回,将不会触发回调函数。 + */ + function chooseCity(options: Partial): void; + //#endregion + + //#region 选择日期 https://docs.alipay.com/mini/api/ui-date + interface DatePickerOptions extends BaseOptions { + /** + * 返回的日期格式, + * 1. yyyy-MM-dd(默认) + * 2. HH:mm + * 3. yyyy-MM-dd HH:mm + * 4. yyyy-MM (最低基础库:1.1.1, 可用 canIUse('datePicker.object.format.yyyy-MM') 判断) + * 5. yyyy (最低基础库:1.1.1,可用 canIUse('datePicker.object.format.yyyy') 判断) + */ + format: 'yyyy-MM-dd' | 'HH:mm' | 'yyyy-MM-dd HH:mm' | 'yyyy-MM' | 'yyyy'; + /** 初始选择的日期时间,默认当前时间 */ + currentDate: string; + /** 最小日期时间 */ + startDate: string; + /** 最大日期时间 */ + endDate: string; + success(result: { date: string; }): void; + /** 11 用户取消操作 */ + fail(error: 11): void; + } + /** + * 打开日期选择列表 + */ + function datePicker(optiosn: Partial): void; + //#endregion + + //#region 动画 https://docs.alipay.com/mini/api/ui-animation + type TimingFunction = + | "linear" + | "ease" + | "ease-in" + | "ease-in-out" + | "ease-out" + | "step-start" + | "step-end"; + interface CreateAnimationOptions { + /** 动画持续时间,单位ms,默认值 400 */ + duration: number; + /** 定义动画的效果,默认值"linear",有效值:"linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" */ + timeFunction: TimingFunction; + /** 动画持续时间,单位 ms,默认值 0 */ + delay: number; + /** 设置transform-origin,默认为"50% 50% 0" */ + transformOrigin: string; + } + interface Animator { + actions: AnimationAction[]; + } + interface AnimationAction { + animates: Animate[]; + option: AnimationActionOption; + } + interface AnimationActionOption { + transformOrigin: string; + transition: AnimationTransition; + } + interface AnimationTransition { + delay: number; + duration: number; + timingFunction: TimingFunction; + } + interface Animate { + type: string; + args: any[]; + } + /** + * 创建动画实例 animation。调用实例的方法来描述动画,最后通过动画实例的export方法将动画数据导出并传递给组件的animation属性。 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + function createAnimation(options: Partial): Animation; + /** 动画实例可以调用以下方法来描述动画,调用结束后会返回自身,支持链式调用的写法。 */ + interface Animation { + /** + * 调用动画操作方法后要调用 step() 来表示一组动画完成, + * 可以在一组动画中调用任意多个动画方法, + * 一组动画中的所有动画会同时开始, + * 一组动画完成后才会进行下一组动画。 + * @param options 指定当前组动画的配置 + */ + step(options?: CreateAnimationOptions): void; + /** + * 导出动画操作 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + export(): Animator; + /** 透明度,参数范围 0~1 */ + opacity(value: number): Animation; + /** 颜色值 */ + backgroundColor(color: string): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + width(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + height(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + top(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + left(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + bottom(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + right(length: number): Animation; + /** deg的范围-180~180,从原点顺时针旋转一个deg角度 */ + rotate(deg: number): Animation; + /** deg的范围-180~180,在X轴旋转一个deg角度 */ + rotateX(deg: number): Animation; + /** deg的范围-180~180,在Y轴旋转一个deg角度 */ + rotateY(deg: number): Animation; + /** deg的范围-180~180,在Z轴旋转一个deg角度 */ + rotateZ(deg: number): Animation; + /** 同transform-function rotate3d */ + rotate3d(x: number, y: number, z: number, deg: number): Animation; + /** + * 一个参数时,表示在X轴、Y轴同时缩放sx倍数; + * 两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数 + */ + scale(sx: number, sy?: number): Animation; + /** 在X轴缩放sx倍数 */ + scaleX(sx: number): Animation; + /** 在Y轴缩放sy倍数 */ + scaleY(sy: number): Animation; + /** 在Z轴缩放sy倍数 */ + scaleZ(sz: number): Animation; + /** 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 */ + scale3d(sx: number, sy: number, sz: number): Animation; + /** + * 一个参数时,表示在X轴偏移tx,单位px; + * 两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。 + */ + translate(tx: number, ty?: number): Animation; + /** + * 在X轴偏移tx,单位px + */ + translateX(tx: number): Animation; + /** + * 在Y轴偏移tx,单位px + */ + translateY(ty: number): Animation; + /** + * 在Z轴偏移tx,单位px + */ + translateZ(tz: number): Animation; + /** + * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px + */ + translate3d(tx: number, ty: number, tz: number): Animation; + /** + * 参数范围-180~180; + * 一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度; + * 两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度 + */ + skew(ax: number, ay?: number): Animation; + /** 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度 */ + skewX(ax: number): Animation; + /** 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度 */ + skewY(ay: number): Animation; + /** + * 同transform-function matrix + */ + matrix( + a: number, + b: number, + c: number, + d: number, + tx: number, + ty: number + ): Animation; + /** 同transform-function matrix3d */ + matrix3d( + a1: number, + b1: number, + c1: number, + d1: number, + a2: number, + b2: number, + c2: number, + d2: number, + a3: number, + b3: number, + c3: number, + d3: number, + a4: number, + b4: number, + c4: number, + d4: number + ): Animation; + } + //#endregion + + //#region 画布 https://docs.alipay.com/mini/api/ui-canvas + interface ToTempFilePathOptions extends BaseOptions { + x: number; // 画布 x 轴起点,默认为 0 + y: number; // 画布 y 轴起点,默认为 0 + width: number; // 画布宽度,默认为 canvas 宽度 - x + height: number; // 画布高度,默认为 canvas 高度 - y + destWidth: number; // 输出的图片宽度,默认为 width + destHeight: number; // 输出的图片高度,默认为 height + } + type Color = string | number[] | number | CanvasAction; + + interface CanvasAction { + /** + * 创建一个颜色的渐变点。 + * 小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染。 + * + * @param stop 渐变点位置,值必须在 [0,1] 范围内 + * @param color 颜色值 + */ + addColorStop(stop: number, color: Color): void; + } + + interface TextMetrics { + width: number; + } + + interface ConvasContext { + font: string; + /** + * 把当前画布的内容导出生成图片,并返回文件路径。 + */ + toTempFilePath(options?: Partial): void; + /** + * textAlign 是 Canvas 2D API 描述绘制文本时,文本的对齐方式的属性。注意,该对齐是基于 + * CanvasRenderingContext2D.fillText 方法的x的值。所以如果 textAlign="center",那么该文本将画在 x-50%*width + */ + setTextAlign(textAlign: 'left' | 'right' | 'center' | 'start' | 'end'): void; + /** + * textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。 + */ + setTextBaseline(textBaseline: 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'): void; + /** + * 设置填充色。 + * + * 如果没有设置 fillStyle,则默认颜色为 black。 + */ + setFillStyle(color: Color): void; + /** + * 设置边框颜色。 + * + * 如果没有设置 strokeStyle,则默认颜色为 black。 + */ + setStrokeStyle(color: Color): void; + /** + * 设置阴影样式。 + * 如果没有设置,offsetX 的默认值为 0, offsetY 的默认值为 0, blur 的默认值为 0,color 的默认值为 black。 + * @param offsetX 阴影相对于形状水平方向的偏移 + * @param offsetY 阴影相对于形状竖直方向的偏移 + * @param blur 0~100 阴影的模糊级别,值越大越模糊 + * @param color 阴影颜色 + */ + setShadow(offsetX: number, offsetY: number, blur: number, color: Color): void; + + /** + * 创建一个线性的渐变色。 + * + * @param x0 起点 x 坐标 + * @param y0 起点 y 坐标 + * @param x1 终点 x 坐标 + * @param y1 终点 y 坐标 + */ + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasAction; + + /** + * 创建一个圆形的渐变色。 + * 起点在圆心,终点在圆环。 + * 需要使用 addColorStop() 来指定渐变点,至少需要两个。 + * @param x 圆心 x 坐标 + * @param y 圆心 y 坐标 + * @param r 圆半径 + * @returns + */ + createCircularGradient(x: number, y: number, r: number): CanvasAction; + + /** + * 设置线条的宽度。 + * @param lineWidth 线条宽度,单位为 px + */ + setLineWidth(lineWidth: number): void; + + /** + * 设置线条的端点样式。 + * + * @param lineCap 线条的结束端点样式 + */ + setLineCap(lineCap: 'round' | 'butt' | 'square'): void; + + /** + * 设置线条的交点样式。 + * + * @param lineJoin 线条的结束交点样式 + */ + setLineJoin(lineJoin: 'round' | 'bevel' | 'miter'): void; + + /** + * 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 当 setLineJoin() 为 miter 时才有效。超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 + * + * @param miterLimit 最大斜接长度 + */ + setMiterLimit(miterLimit: number): void; + + /** + * 创建一个矩形。 + * + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + rect(x: number, y: number, width: number, height: number): void; + + /** + * 填充矩形。 + * 用 setFillStyle() 设置矩形的填充色,如果没设置则默认是 black。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + fillRect(x: number, y: number, width: number, height: number): void; + + /** + * 画一个矩形(非填充)。 + * 用 setFillStroke() 设置矩形线条的颜色,如果没设置默认是 black。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + strokeRect(x: number, y: number, width: number, height: number): void; + + /** + * 清除画布上在该矩形区域内的内容。 + * clearRect 并非画一个白色的矩形在地址区域,而是清空,为了有直观感受,可以对 canvas 加了一层背景色。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + clearRect(x: number, y: number, width: number, height: number): void; + + /** + * 对当前路径中的内容进行填充。默认的填充色为黑色。 + * + */ + fill(): void; + + /** + * 画出当前路径的边框。默认 black。 + * stroke() 描绘的的路径是从 beginPath() 开始计算,但是不会将 strokeRect() 包含进去 + */ + stroke(): void; + + /** + * 关闭一个路径 + * 关闭路径会连接起点和终点。 + * 如果关闭路径后没有调用 fill() 或者 stroke() 并开启了新的路径,那之前的路径将不会被渲染。 + */ + beginPath(): void; + + /** + * 关闭一个路径 + * 关闭路径会连接起点和终点。 + * + */ + closePath(): void; + + /** + * 把路径移动到画布中的指定点,不创建线条。 + * 用 stroke() 方法来画线条 + * @param x 目标位置 x 坐标 + * @param y 目标位置 y 坐标 + */ + moveTo(x: number, y: number): void; + + /** + * lineTo 方法增加一个新点,然后创建一条从上次指定点到目标点的线。 + * 用 stroke() 方法来画线条 + * + * @param x 目标位置 x 坐标 + * @param y 目标位置 y 坐标 + */ + lineTo(x: number, y: number): void; + + /** + * 画一条弧线。 + * 创建一个圆可以用 arc() 方法指定其实弧度为0,终止弧度为 2 * Math.PI。 + * + * @param x + * @param y + * @param r + * @param sAngle + * @param eAngle + */ + arc(x: number, y: number, r: number, sAngle: number, eAngle: number): void; + + /** + * 创建三次方贝塞尔曲线路径。 + * 曲线的起始点为路径中前一个点。 + * @param cp1x + * @param cp1y + * @param cp2x + * @param cp2y + * @param x + * @param y + */ + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + + /** + * 将当前创建的路径设置为当前剪切路径。 + * + */ + clip(): void; + + /** + * 创建二次贝塞尔曲线路径。 + * 曲线的起始点为路径中前一个点。 + * @param cpx 贝塞尔控制点 x 坐标 + * @param cpy 贝塞尔控制点 y 坐标 + * @param x 结束点 x 坐标 + * @param y 结束点 y 坐标 + */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + + /** + * 在调用scale方法后,之后创建的路径其横纵坐标会被缩放。多次调用scale,倍数会相乘。 + * + * @param scaleWidth 横坐标缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) + * @param scaleHeight 纵坐标轴缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) + */ + scale(scaleWidth: number, scaleHeight: number): void; + + /** + * 以原点为中心,原点可以用 translate方法修改。顺时针旋转当前坐标轴。多次调用rotate,旋转的角度会叠加。 + * + * @param rotate 旋转角度,以弧度计(degrees * Math.PI/180;degrees 范围为0~360) + */ + rotate(rotate: number): void; + + /** + * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 + * + * @param x 水平坐标平移量 + * @param y 竖直坐标平移量 + */ + translate(x: number, y: number): void; + + /** + * 设置字体大小。 + * + * @param fontSize 字号 + */ + setFontSize(fontSize: number): void; + + /** + * 在画布上绘制被填充的文本。 + * + * @param text 文本 + * @param x 绘制文本的左上角 x 坐标 + * @param y 绘制文本的左上角 y 坐标 + */ + fillText(text: string, x: number, y: number): void; + + /** + * 绘制图像,图像保持原始尺寸。 + * + * @param imageResource 图片资源, 只支持线上 cdn 地址或离线包地址,线上 cdn 需返回头 Access-Control-Allow-Origin: * + * @param x 图像左上角 x 坐标 + * @param y 图像左上角 y 坐标 + * @param width 图像宽度 + * @param height 图像高度 + */ + drawImage(imageResource: string, x: number, y: number, width: number, height: number): void; + + /** + * 设置全局画笔透明度。 + * + * @param alpha 透明度,0 表示完全透明,1 表示不透明 范围 [0, 1] + */ + setGlobalAlpha(alpha: number): void; + + /** + * 设置虚线的样式 + * + * @param segments 一组描述交替绘制线段和间距(坐标空间单位)长度的数字。 如果数组元素的数量是奇数, 数组的元素会被复制并重复。例如, [5, 15, 25] 会变成 [5, 15, 25, 5, 15, 25]。 + */ + setLineDash(segments: number[]): void; + + /** + * 使用矩阵多次叠加当前变换的方法,矩阵由方法的参数进行描述。你可以缩放、旋转、移动和倾斜上下文。 + * + * @param scaleX 水平缩放 + * @param skewX 水平倾斜 + * @param skewY 垂直倾斜 + * @param scaleY 垂直缩放 + * @param translateX 水平移动 + * @param translateY 垂直移动 + */ + transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; + + /** + * 使用单位矩阵重新设置(覆盖)当前的变换并调用变换的方法,此变换由方法的变量进行描述。 + * + * @param scaleX 水平缩放 + * @param skewX 水平倾斜 + * @param skewY 垂直倾斜 + * @param scaleY 垂直缩放 + * @param translateX 水平移动 + * @param translateY 垂直移动 + */ + setTransform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; + + /** + * 保存当前的绘图上下文。 + * + */ + save(): void; + + /** + * 恢复之前保存的绘图上下文。 + */ + restore(): void; + + /** + * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。 + * 绘图上下文需要由 my.createCanvasContext(canvasId) 来创建。 + * @param [reserve] 本次绘制是否接着上一次绘制,即 reserve 参数为 false 时则在本次调用 drawCanvas绘制之前 native 层应先清空画布再继续绘制;若 reserver 参数为true 时,则保留当前画布上的内容,本次调用drawCanvas绘制的内容覆盖在上面,默认 false + */ + draw(reserve?: boolean): void; + + measureText(text: string): TextMetrics; + } + /** + * 创建 canvas 绘图上下文 + * + * 该绘图上下文只作用于对应 canvasId 的 + */ + function createCanvasContext(canvasId: string): ConvasContext; + //#endregion + + //#region 地图 https://docs.alipay.com/mini/api/ui-map + interface GetCenterLocationOptions extends BaseOptions { + success?(res: { longitude: string; latitude: string; }): void; + } + + interface MapContext extends BaseOptions { + /** + * 获取当前地图中心的经纬度,返回 gcj02 坐标系的值,可以用于 my.openLocation + * + * @param options + */ + getCenterLocation(options: GetCenterLocationOptions): void; + /** + * 将地图中心移动到当前定位点,需要配合 map 组件的 show-location 使用 + */ + moveToLocation(): void; + } + + /** + * 创建并返回一个 map 上下文对象 mapContext。 + * + * @param mapId + * @returns + */ + function createMapContext(mapId: string): MapContext; + + //#endregion + + //#region 键盘 https://docs.alipay.com/mini/api/ui-hidekeyboard + /** + * 隐藏键盘 + * + */ + function hideKeyboard(): void; + //#endregion + + //#region 滚动 https://docs.alipay.com/mini/api/scroll + interface PageScrollToOptions { + scrollTop: number; // 滚动到页面的目标位置,单位 px + } + + /** + * 滚动到页面的目标位置 + * + * @param options + */ + function pageScrollTo(options: PageScrollToOptions): void; + //#endregion + + //#region 节点查询 https://docs.alipay.com/mini/api/selector-query + interface RectArea { + /** 节点的左边界坐标 */ + left: number; + /** 节点的右边界坐标 */ + right: number; + /** 节点的上边界坐标 */ + top: number; + /** 节点的下边界坐标 */ + bottom: number; + /** 节点的宽度 */ + width: number; + /** 节点的高度 */ + height: number; + } + interface NodesRefRect extends RectArea { + /** 节点的ID */ + id: string; + /** 节点的dataset */ + dataset: any; + } + interface NodeRefOffset { + /** 节点的ID */ + id: string; + /** 节点的dataset */ + dataset: any; + /** 节点的水平滚动位置 */ + scrollLeft: number; + /** 节点的竖直滚动位置 */ + scrollTop: number; + } + interface NodesRef { + /** + * 添加节点的布局位置的查询请求,相对于显示区域,以像素为单位。 + * 其功能类似于DOM的getBoundingClientRect。 + * 返回值是nodesRef对应的selectorQuery。 + * 返回的节点信息中,每个节点的位置用 + * left、right、top、bottom、width、height字段描述。 + * 如果提供了callback回调函数,在执行selectQuery的exec方法后 + * 节点信息会在callback中返回。 + */ + boundingClientRect( + callback?: (rect: T) => void + ): SelectorQuery; + /** + * 添加节点的滚动位置查询请求,以像素为单位。 + * 节点必须是scroll-view或者viewport。 + * 返回值是nodesRef对应的selectorQuery。 + * 返回的节点信息中,每个节点的滚动位置用scrollLeft、scrollHeight字段描述。 + * 如果提供了callback回调函数,在执行selectQuery的exec方法后,节点信息会在callback中返回。 + */ + scrollOffset(callback?: (rect: NodeRefOffset) => void): SelectorQuery; + // /** + // * 获取节点的相关信息,需要获取的字段在fields中指定。 + // * 返回值是nodesRef对应的selectorQuery。 + // */ + // fields( + // fields: NodeRefFieldsOptions, + // callback?: (result: any) => void + // ): SelectorQuery; + } + /** + * SelectorQuery对象实例 + */ + interface SelectorQuery { + // /** + // * 将选择器的选取范围更改为自定义组件component内 + // * (初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点 + // * @version 1.6.0 + // */ + // in(component: Component): SelectorQuery; + /** + * 在当前页面下选择第一个匹配选择器selector的节点,返回一个NodesRef对象实例,可以用于获取节点信息。 + * selector类似于CSS的选择器,但仅支持下列语法。 + * + ID选择器:#the-id + * + class选择器(可以连续指定多个):.a-class.another-class + * + 子元素选择器:.the-parent > .the-child + * + 后代选择器:.the-ancestor .the-descendant + * + 跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant + * + 多选择器的并集:#a-node, .some-other-nodes + */ + select(selector: string): NodesRef; + /** + * 在当前页面下选择匹配选择器selector的节点,返回一个NodesRef对象实例。 + * 与selectorQuery.selectNode(selector)不同的是,它选择所有匹配选择器的节点。 + */ + selectAll(selector: string): NodesRef; + /** + * 选择显示区域,可用于获取显示区域的尺寸、滚动位置等信息 + * 返回一个NodesRef对象实例。 + */ + selectViewport(): NodesRef; + /** + * 执行所有的请求 + * 请求结果按请求次序构成数组,在callback的第一个参数中返回。 + */ + exec(callback?: (result: any[]) => void): void; + } + /** + * 获取一个节点查询对象 SelectorQuery。 + * + * @param page 可以指定 page 属性,默认为当前页面 + * @returns + */ + function createSelectorQuery(page?: any): SelectorQuery; + //#endregion + + //#region 级联选择 https://docs.alipay.com/mini/api/ewdxl3 + interface MultiLevelSelectItem { + name: string; + subList?: MultiLevelSelectItem[]; + } + interface MultiLevelSelectOptions extends BaseOptions { + title?: string; // 标题 + list?: MultiLevelSelectItem[]; // 选择数据列表 + name?: string; // 条目名称 + subList?: MultiLevelSelectItem[]; // 子条目列表 + success?(res: { + success: boolean; // 是否选择完成,取消返回false + result: MultiLevelSelectItem[]; // 选择的结果,如[{“name”:”杭州市”},{“name”:”上城区”},{“name”:”古翠街道”}] + }): void; + } + + function multiLevelSelect(options?: MultiLevelSelectOptions): void; + //#endregion +} + +// 开放接口 +declare namespace my { + //#region 用户授权 https://docs.alipay.com/mini/api/openapi-authorize + interface GetAuthCodeOptions extends BaseOptions { + scopes?: string | string[]; // 授权类型,默认 auth_base。支持 auth_base(静默授权)/ auth_user(主动授权) / auth_zhima(芝麻信用) + success?(res: { + authCode: string; // 授权码 + authErrorScope: { + [scope: string]: number; + }; // 失败的授权类型,key是授权失败的 scope,value 是对应的错误码 + authSucessScope: string[]; // 成功的授权 scope + }): void; + } + /** + * 获取授权码。 + * 详细用户授权接入参考 [指引](https://docs.alipay.com/mini/introduce/auth)。 + */ + function getAuthCode(options: GetAuthCodeOptions): void; + //#endregion + + //#region 客户端获取会员信息 https://docs.alipay.com/mini/api/userinfo + interface GetAuthUserInfoOptions extends BaseOptions { + success?(res: { + nickName: string; // 用户昵称 + avatar: string; // 用户头像链接 + }): void; + } + /** + * 客户端获取会员信息 + * 获取会员信息首先需要获取用户授权,详细会员信息获取参考[指引](https://docs.alipay.com/mini/introduce/auth),采用 jsapi 调用的方式。 + */ + function getAuthUserInfo(options: GetAuthUserInfoOptions): void; + //#endregion + + //#region 小程序唤起支付 https://docs.alipay.com/mini/api/openapi-pay + interface TradePayOptions extends BaseOptions { + tradeNO?: string; // 接入小程序支付时传入此参数。此参数为支付宝交易号 + success?(res: { + // resultCode | 描述 + // -----------|------ + // 9000 | 订单支付成功 + // 8000 | 正在处理中 + // 4000 | 订单支付失败 + // 6001 | 用户中途取消 + // 6002 | 网络连接出错 + // 6004 | 支付结果未知(有可能已经支付成功),请查询商户订单列表中订单的支付状态 + // 99 | 用户点击忘记密码导致快捷界面退出(only iOS) + resultCode: string; + }): void; + } + /** + * 发起支付。 + * 详细接入支付方式参考[指引](https://docs.alipay.com/mini/introduce/pay)。 + * @param options + */ + function tradePay(options: TradePayOptions): void; + //#endregion + + //#region 支付代扣签约 https://docs.alipay.com/mini/api/pay-sign + interface PaySignCenterOptions extends BaseOptions { + signStr: string; // 签约字符串 + } + + /** + * 签约中心 + * + * 返回码 | 含义 + * ------|------ + * 7000 | 协议签约成功 + * 7001 | 签约结果未知(有可能已经签约成功),请根据外部签约号查询签约状态 + * 7002 | 协议签约失败 + * 6001 | 用户中途取消 + * 6002 | 网络连接错误 * @param options + */ + function paySignCenter(options: PaySignCenterOptions): void; + //#endregion + + //#region 小程序二维码 https://docs.alipay.com/mini/api/openapi-qrcode + // @see https://docs.alipay.com/mini/api/openapi-qrcode + // @see https://docs.alipay.com/mini/introduce/qrcode + //#endregion + + //#region 跳转支付宝卡包 https://docs.alipay.com/mini/api/card-voucher-ticket + /** + * 打开支付宝卡列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openCardList(): void; + interface OpenMerchantCardList extends BaseOptions { + partnerId: string; // 商户编号 + } + + /** + * 打开支付宝卡列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * @param options + */ + function openMerchantCardList(options: OpenMerchantCardList): void; + + interface OpenCardDetailOptions extends BaseOptions { + passId: string; // 卡实例Id + } + /** + * 打开当前用户的某张卡的详情页 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * + * passId获取方式: + * 1)通过alipass创建的卡 + * 调用alipay.pass.instance.add(支付宝pass新建卡券实例接口)接口,在出参“result”中可获取 + * 2)通过会员卡创建的卡 + * 调用alipay.marketing.card.query(会员卡查询)接口,在schema_url中可获取,具体参数为“p=xxx”,xxx即为passId。 + */ + function openCardDetail(options: OpenCardDetailOptions): void; + + /** + * 打开支付宝券列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * + * @param options + */ + function openVoucherList(): void; + + interface OpenMerchantVoucherListOptions extends BaseOptions { + partnerId: string; // 商户编号 + } + /** + * 打开当前用户的某个商户的券列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openMerchantVoucherList(options: OpenMerchantVoucherListOptions): void; + + interface OpenVoucherDetailOptions1 extends BaseOptions { + passId: string; // 券实例Id,调用券发放接口可以获取该参数(如果传入了partnerId和serialNumber则不需传入) + } + interface OpenVoucherDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号,以 2088 为开头(如果传入了passId则不需传入) + serialNumber: string; // 序列号,调用新建卡券模板可以获取该参数(如果传入了passId则不需传入) + } + /** + * 打开当前用户的某张券的详情页(非口碑) + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openVoucherDetail(options: OpenVoucherDetailOptions1 | OpenVoucherDetailOptions2): void; + + interface OpenKBVoucherDetailOptions1 extends BaseOptions { + passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需传入) + } + interface OpenKBVoucherDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号(如果传入了passId则不需传入) + serialNumber: string; // 序列号(如果传入了passId则不需传入) + } + /** + * 打开当前用户的某张券的详情页(口碑) + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openKBVoucherDetail(options: OpenKBVoucherDetailOptions1 | OpenKBVoucherDetailOptions2): void; + + /** + * 打开支付宝票列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openTicketList(): void; + + interface OpenMerchantTicketListOptions extends BaseOptions { + partnerId: string; // 商户编号 + } + /** + * 打开某个商户的票列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openMerchantTicketList(options: OpenMerchantTicketListOptions): void; + + interface OpenTicketDetailOptions1 extends BaseOptions { + passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需要传入passId) + } + interface OpenTicketDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号(如果传入了passId则不需要传入partnerId) + serialNumber: string; // 序列号(如果传入了passId则不需要传入serialNumber) + } + /** + * 打开当前用户的某张票的详情页 + * + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openTicketDetail(options: OpenTicketDetailOptions1 | OpenTicketDetailOptions2): void; + //#endregion + + //#region 会员开卡授权 https://docs.alipay.com/mini/api/add-card-auth + interface AddCardAuthResult { + success: true | boolean; // true 表示领卡成功 + resultStatus: string; // 9000 表示成功 + result: { + app_id: string; // 应用id + auth_code: string; // 授权码,用于换取authtoken + state: string; // 授权的state + scope: string; // 授权scope + template_id: string; // 会员卡模板Id + request_id: string; // 会员卡表单信息请求Id + out_string: string; // 会员卡领卡链接透传参数 + }; + } + interface AddCardAuthResult { + success: false | boolean; // false 表示领卡失败 + /** + * 失败的错误码 + * 领卡失败 code 说明 + * 名称 | 类型 | 说明 + * -----|-----|----- + * JSAPI_SERVICE_TERMINATED | String | 用户取消 + * JSAPI_PARAM_INVALID | String | url 为空或非法参数 + * JSAPI_SYSTEM_ERROR | String | 系统错误 + */ + code: string; + } + interface AddCardAuthOptions extends BaseOptions { + /** + * 开卡授权的页面地址,从alipay.marketing.card.activateurl.apply接口获取 + */ + url: string; + success?(res: AddCardAuthResult): void; + } + /** + * 小程序唤起会员开卡授权页面,小程序接入会员卡[点此查看](https://docs.alipay.com/mini/introduce/card) + */ + function addCardAuth(options: AddCardAuthOptions): void; + //#endregion + + //#region 芝麻认证 https://docs.alipay.com/mini/api/zm-service + interface StartZMVerifyOptions extends BaseOptions { + bizNo: string; // 认证标识 + success?(res: { + token: string; // 认证标识 + passed: string; // 认证是否通过 + reason?: string; // 认证不通过原因 + }): void; + } + /** + * 芝麻认证接口,调用此接口可以唤起芝麻认证页面并进行人脸身份验证。 + * 有关芝麻认证的产品和接入介绍,详见 [芝麻认证](https://docs.alipay.com/mini/introduce/zm-verify)。 + * 需要通过蚂蚁开发平台,调用certification.initialize接口进行[认证初始化](https://docs.alipay.com/zmxy/271/105914)。获得biz_no 后,方能通过以下接口激活芝麻认证小程序。 + */ + function startZMVerify(options: StartZMVerifyOptions): void; + //#endregion + + //#region 信用借还 https://docs.alipay.com/mini/api/zmcreditborrow + interface ZMCreditBorrowOptions extends BaseOptions { + /** + * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+随机数 + * + */ + out_order_no: string; + /** + * 信用借还的产品码,传入固定值:w1010100000000002858 + */ + product_code: string; + /** + * 物品名称,最长不能超过14个汉字 + */ + goods_name: string; + /** + * 租金单位,租金+租金单位组合才具备实际的租金意义。 + * 取值定义如下: + * DAY_YUAN: 元 / 天 + * HOUR_YUAN: 元 / 小时 + * YUAN: 元 + * YUAN_ONCE: 元 / 次 + */ + rent_unit: string; + /** + * 租金,租金 + 租金单位组合才具备实际的租金意义。 + * > 0.00元,代表有租金 + * = 0.00元,代表无租金,免费借用 + * 注:参数传值必须 >= 0,传入其他值会报错参数非法 + */ + rent_amount: string; + /** + * 押金,金额单位:元。 + * 注:不允许免押金的用户按此金额支付押金;当物品丢失时,赔偿金额不得高于该金额。 + */ + deposit_amount: string; + /** + * 该字段目前默认传Y; + * 是否支持当借用用户信用不够(不准入)时,可让用户支付押金借用: + * Y: 支持 + * N: 不支持 + * 注:支付押金的金额等同于deposit_amount。 + */ + deposit_state?: string; // 该字段目前默认传Y; + /** + * 回调到商户的小程序schema地址。说明:商户的回调地址可以在商户后台里进行配置,服务端回调时,首先根据参数:invoke_type 查询是否有对应的配置地址,如果有,则使用已定义的地址,否则,使用该字段定义的地址执行回调; + * 参考表格下方的说明一; + * 小程序回调地址参考表格下方的说明三; + * 说明一: + * 支付宝商户账号登录我的商家服务打开入口链接; + * 商家服务中选择“您可能需要->信用借还”或者点击链接; + * 场景ID配置->配置新ID,选择对应的业务类型、服务类目和联盟,将生成的场景ID作为credit_biz的值传入即可; + * 回调地址配置->设置小程序回调地址,注意:若设置了该回调地址,则接口my.zmCreditBorrow中的入参invoke_return_url将会失效,以该处设置为准; + * 说明三: + * 小程序回调地址示例一:alipays://platformapi/startapp?appId=1999; + * 小程序回调地址示例二:alipays://platformapi/startapp?appId=1999&page=pages/map; + */ + invoke_return_url?: string; + /** + * 商户访问蚂蚁的对接模式,默认传TINYAPP: + * TINYAPP:回跳至小程序地址; + * WINDOWS:支付宝服务窗,默认值; + */ + invoke_type?: 'TINYAPP' | 'TINYAPP' | 'WINDOWS' | string; + /** + * 信用业务服务,注意:该字段不能为空,且必须根据说明的指引配置商户专属的场景ID,商户自助接入时,登录后台可配置场景ID,将后台配置的场景ID作为该字段的输入; + * 参考说明一自助进行配置; + */ + credit_biz: string; + /** + * 商户订单创建的起始借用时间,格式:YYYY - MM - DD HH: MM: SS。如果不传入或者为空,则认为订单创建起始时间为调用此接口时的时间。 + */ + borrow_time?: string; + /** + * 到期时间,不允许为空,请根据实际业务合理设置该值,格式:YYYY - MM - DD HH: MM: SS,是指最晚归还时间,表示借用用户如果超过此时间还未完结订单(未归还物品或者未支付租金)将会进入逾期状态,芝麻会给借用用户发送催收提醒;需要晚于borrow_time。 + */ + expiry_time: string; + /** + * 借用用户的手机号码,可选字段。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 + */ + mobile_no?: string; + /** + * 物品借用地点的描述,便于用户知道物品是在哪里借的。可为空 + * + */ + borrow_shop_name?: string; + /** + * 租金的结算方式,非必填字段,默认是支付宝租金结算支付 merchant:表示商户自行结算,信用借还不提供租金支付能力; alipay:表示使用支付宝支付功能,给用户提供租金代扣及赔偿金支付能力; + * + */ + rent_settle_type?: 'merchant' | 'alipay' | string; + /** + * 商户请求状态上下文。商户发起借用服务时,需要在借用结束后返回给商户的参数,格式:json; + * 如果json的某一项值包含中文,请使用encodeURIComponent对该值进行编码; + * @example + * var ext = { + * name: encodeURIComponent('名字') + * }; + * var obj = { + * invoke_state: JSON.stringify(ext) + * } + */ + invoke_state?: string; + /** + * 租金信息描述, 长度不超过14个汉字,只用于页面展示给C端用户,除此之外无其他意义。 + */ + rent_info?: string; + /** + * 借用用户的真实姓名,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 + */ + name?: string; + /** + * 借用用户的真实身份证号,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 + */ + cert_no?: string; + /** + * 借用用户的收货地址,可选字段,最大长度128。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 + */ + address?: string; + success?(res: { + /** + * 6001 用户取消了业务流程 + * 6002 网络异常 + * 9000 成功 + * 4000 系统异常 + */ + resultStatus: '6001' | '6002' | '9000' | '4000' | string; + result: { + /** + * 商户发起借用服务时传入的参数,需要在借用结束后返回给商户的参数 + * @example + * {"user_name":"john"} + */ + invoke_state: string; + /** + * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+4位随机数 + * @example + * 201610010000283627 + */ + out_order_no: string; + /** + * 芝麻信用借还订单号 + * @example + * 10020027631 + */ + order_no: string; + /** + * 是否准入:Y:准入;N:不准入(该字段目前无实际意义) + */ + admit_state: 'Y' | 'N' | string; + /** + * 物品借用/租赁者的用户id + * @example + * 2088202924240029 + */ + user_id: string; + callbackData: any; // todo only in example + } + }): void; + } + function zmCreditBorrow(options: ZMCreditBorrowOptions): void; + //#endregion + + //#region 文本风险识别 https://docs.alipay.com/mini/api/text-identification + type TextRiskIdentificationType = 'keyword' | '0' | '1' | '2' | '3' | string; + interface TextRiskIdentificationOptions extends BaseOptions { + /** + * 需要进行风险识别的文本内容 + */ + content: string; + /** + * 识别类型:keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 + */ + type: TextRiskIdentificationType[]; + success?(res: { + result: { + /** + * 目标内容文本识别到的类型,keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 + */ + type: TextRiskIdentificationType; + /** + * 仅当识别命中了 type 为 keyword 时,才会返回该字段 + */ + hitKeywords?: string[]; + /** + * 识别命中得分,最高分100分。仅当识别没有命中 keyword ,但入参中包含了广告或涉政或涉黄时,才会返回该字段 + */ + score?: string; + }; + fail?(res: { + /** + * 识别错误码 + */ + error: string; + /** + * 识别错误消息 + */ + errorMessage: string; + }): void; + }): void; + } + /** + * 文本风险识别, **支付宝客户端10.1.10及以上版本支持。**详细接入参考[指引](https://docs.alipay.com/mini/introduce/text-identification) + */ + function textRiskIdentification(options: TextRiskIdentificationOptions): void; + //#endregion + + //#region 小程序跳转 https://docs.alipay.com/mini/api/open-miniprogram + interface NavigateToMiniProgramOptions extends BaseOptions { + /** + * 要跳转的目标小程序appId + */ + appId: string; + /** + * 打开的页面路径,如果为空则打开首页 + */ + path?: string; + /** + * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch() ,App.onShow() 中获取到这份数据 + */ + extraData?: any; + /** + * 要打开的小程序版本,有效值 develop(开发版),trial(体验版),release(正式版) ,仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是正式版,则打开的小程序必定是正式版。默认值 release + */ + envVersion?: 'develop' | 'trial' | 'release' | string; + } + /** + * 跳转到其他小程序。详细接入参考[指引](https://docs.alipay.com/mini/introduce/open-miniprogram) + * @param options + */ + function navigateToMiniProgram(options: NavigateToMiniProgramOptions): void; + interface NavigateBackMiniProgramOptions extends BaseOptions { + /** + * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch(),App.onShow() 中获取到这份数据 + */ + extraData?: any; + } + /** + * 跳转回上一个小程序,只有当另一个小程序跳转到当前小程序时才会能调用成功 + */ + function navigateBackMiniProgram(options: NavigateBackMiniProgramOptions): void; + //#endregion + + //#region webview组件控制 https://docs.alipay.com/mini/api/webview-context + interface WebViewContext { + postMessage(param: any): void; + } + /** + * 创建并返回 web-view 上下文 webViewContext 对象。 + * + * @param webviewId 要创建的web-view所对应的id属性 + */ + function createWebViewContext(webviewId: string): WebViewContext; + //#endregion +} + +// 多媒体 +declare namespace my { + //#region 图片 https://docs.alipay.com/mini/api/media-image + type ImageSourceType = "album" | "camera"; + interface ChooseImageOptions extends BaseOptions { + /** 最大可选照片数,默认1张 */ + count: number; + /** 相册选取或者拍照,默认 [‘camera’,‘album’] */ + sourceType: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: { + /** + * 图片文件描述 + */ + apFilePaths: string[]; + }): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: Partial): void; + + interface PreviewImageOptions extends BaseOptions { + /** 当当前显示图片索引,默认 0 */ + current?: number; + /** 要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + + interface SaveImageOptions extends BaseOptions { + /** + * 要保存的图片链接 + */ + url: string; + success?(res: { errMsg: string }): void; + } + /** + * 保存在线图片到手机相册。 + */ + function saveImage(options: SaveImageOptions): void; + + interface CompressImageOptions extends BaseOptions { + /** + * 要压缩的图片地址数组 + */ + apFilePaths: string[]; + /** + * 压缩级别,支持 0 ~ 4 的整数,默认 4。详见「compressLevel表 说明表」 + * compressLevel表 + * compressLevel | 说明 + * --------------|----- + * 0 | 低质量 + * 1 | 中等质量 + * 2 | 高质量 + * 3 | 不压缩 + * 4 | 根据网络适应 + */ + compressLevel?: 0 | 1 | 2 | 3 | 4; + success?(res: { + /** + * 压缩后的路径数组 + */ + apFilePaths: string[]; + }): void; + } + /** + * 压缩图片。扫码体验: + */ + function compressImage(options: CompressImageOptions): void; + + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片路径,目前支持: + * - 网络图片路径 + * - apFilePath路径 + * - 相对路径 + */ + src: string; + success?(res: { + width: number; // 图片宽度(单位px) + height: number; // 图片高度(单位px) + path: string; // 图片本地路径 + }): void; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + //#endregion +} + +// 缓存 +declare namespace my { + //#region 缓存 https://docs.alipay.com/mini/api/storage + interface SetStorageOptions extends BaseOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 需要存储的内容 */ + data: any; + } + /** + * 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的数据。 + * 这是异步接口。 + */ + function setStorage(options: SetStorageOptions): void; + + /** + * 同步将数据存储在本地缓存中指定的 key 中。 + * 这是同步接口。 + * + * @param key 本地缓存中的指定的 key + * @param data 需要存储的内容 + */ + function setStorageSync(options: { key: string; data: any; }): void; + + interface GetStorageOptions extends BaseOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 接口调用的回调函数,res = {data: key对应的内容} */ + success(res: DataResponse): void; + } + /** + * 获取缓存数据。 + * 这是异步接口。 + */ + function getStorage(options: GetStorageOptions): void; + + /** + * 同步获取缓存数据。 + * 这是同步接口 + */ + function getStorageSync(options: { key: string; }): any; + + interface RemoveStorageOptions extends BaseOptions { + key: string; + } + /** + * 删除缓存数据。 + * 这是异步接口。 + */ + function removeStorage(options: RemoveStorageOptions): void; + + /** + * 同步删除缓存数据。 + * 这是同步接口。 + * @param key 缓存数据的key + */ + function removeStorageSync(options: { key: string; }): void; + + /** + * 清除本地数据缓存。 + * 这是异步接口。 + */ + function clearStorage(): void; + + /** + * 同步清除本地数据缓存。 + * 这是同步接口。 + */ + function clearStorageSync(): void; + + interface StorageInfo { + /** + * 当前storage中所有的key + */ + keys: string[]; + /** + * 当前占用的空间大小, 单位kb + */ + currentSize: number; + /** + * 限制的空间大小,单位kb + */ + limitSize: number; + } + interface GetStorageInfoOptions extends BaseOptions { + success(res: StorageInfo): void; + } + /** + * 异步获取当前storage的相关信息 + */ + function getStorageInfo(options: GetStorageInfoOptions): void; + + function getStorageInfoSync(): StorageInfo; + //#endregion +} + +// 文件 +declare namespace my { + //#region 文件 https://docs.alipay.com/mini/api/file + interface SavedFileData { + /** 文件保存路径 */ + apFilePath: string; + } + interface SaveFileOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + success?(res: SavedFileData): void; + } + /** + * 保存文件到本地(本地文件大小总容量限制:10M) + */ + function saveFile(options: SaveFileOptions): void; + + interface GetFileInfoSuccess { + /** 文件大小,单位:B */ + size: number; + /** 摘要结果 */ + digest: string; + } + interface GetFileInfoOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + /** 摘要算法,支持md5和sha1,默认为md5 */ + digestAlgorithm?: 'md5' | 'sha1'; + success?(options: GetFileInfoSuccess): void; + } + /** + * 获取文件信息 + * 基础库版本 1.4.0 开始支持,低版本需做兼容处理 + */ + function getFileInfo(options: GetFileInfoOptions): void; + + interface SavedFileInfoData { + /** + * 文件大小,单位B + */ + size: number; + /** + * 创建时间 + */ + createTime: number; + } + interface GetSavedFileInfoOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + /** 接口调用成功的回调函数 */ + success?(res: SavedFileInfoData): void; + } + /** + * 获取保存的文件信息 + */ + function getSavedFileInfo(options: GetSavedFileInfoOptions): void; + + interface GetSavedFileListOptions extends BaseOptions { + success?(res: { + fileList: Array<{ + /** 文件大小 */ + size: number; + /** 创建时间 */ + createTime: number; + /** 文件路径 */ + apFilePath: string; + }> + }): void; + } + function getSavedFileList(options: GetSavedFileListOptions): void; + + type RemoveSavedFileOptions = GetSavedFileInfoOptions; + /** + * 删除某个保存的文件 + */ + function removeSavedFile(options: RemoveSavedFileOptions): void; + //#endregion +} + +// 位置 +declare namespace my { + //#region 位置 https://docs.alipay.com/mini/api/location + interface LocationData { + /** 经度 */ + longitude: string; + /** 纬度 */ + latitude: string; + /** 精确度,单位m */ + accuracy: string; + /** + * 水平精确度,单位m + */ + horizontalAccuracy: string; + /** + * 国家(type>0生效) + */ + country?: string; + /** + * 国家编号 (type>0生效) + */ + countryCode?: string; + /** + * 省份(type>0生效) + */ + province?: string; + /** + * 城市(type>0生效) + */ + city?: string; + /** + * 城市级别的地区代码(type>0生效) + */ + cityAdcode?: string; + /** + * 区县(type>0生效) + */ + district?: string; + /** + * 区县级别的地区代码(type>0生效) + */ + districtAdcode?: string; + /** + * 需要街道级别逆地理的才会有的字段,街道门牌信息,结构是:{ street, number } (type > 1生效) + */ + streetNumber?: { + street: string; + number: string; + }; + /** + * 需要POI级别逆地理的才会有的字段, 定位点附近的 POI 信息,结构是:{ name, address } (type > 2生效) + */ + pois?: Array<{ + name: string; + address: string; + }>; + } + interface GetLocationOptions extends BaseOptions { + /** + * 支付宝客户端经纬度定位缓存过期时间,单位秒。默认 30s。使用缓存会加快定位速度,缓存过期会重新定位 + */ + cacheTimeout: number; + /** + * 0:默认,获取经纬度 + * 1:获取经纬度和详细到区县级别的逆地理编码数据 + * 2:获取经纬度和详细到街道级别的逆地理编码数据,不推荐使用 + * 3:获取经纬度和详细到POI级别的逆地理编码数据,不推荐使用 + */ + type: 0 | 1 | 2 | 3; + /** 接口调用成功的回调函数,返回内容详见返回参数说明。 */ + success(res: LocationData): void; + } + /** + * 获取用户当前的地理位置信息 + */ + function getLocation(options: Partial): void; + + interface OpenLocationOptions extends BaseOptions { + /** 经度 */ + longitude: number | string; + /** 纬度 */ + latitude: number | string; + /** 位置名称 */ + name: string; + /** 地址的详细说明 */ + address: string; + /** 缩放比例,范围 3~19,默认为 15 */ + scale?: number; + } + /** + * 使用微信内置地图查看位置 + */ + function openLocation(options: OpenLocationOptions): void; + + interface ChooseLocationData { + /** + * 位置名称 + */ + name: string; + /** + * 详细地址 + */ + address: string; + /** + * 纬度,浮点数,范围为-90~90,负数表示南纬 + */ + latitude: number; + /** + * 经度,浮点数,范围为-180~180,负数表示西经 + */ + longitude: number; + } + interface ChooseLocationOptions extends BaseOptions { + success(res: ChooseLocationData): void; + } + /** + * 使用支付宝内置地图选择地理位置。 + */ + function chooseLocation(options: ChooseLocationOptions): void; + //#endregion +} + +// 网络 +declare namespace my { + //#region 网络 https://docs.alipay.com/mini/api/network + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 目标服务器url */ + url: string; + /** 设置请求的 HTTP 头,默认 {'Content-Type': 'application/x-www-form-urlencoded'} */ + header?: RequestHeader; + /** 默认GET,目前支持GET,POST */ + method?: "GET" | "POST"; + /** 请求的参数 */ + data?: any; + /** + * 超时时间,单位ms,默认30000 + */ + timeout?: number; + /** 期望返回的数据格式,默认json,支持json,text,base64 */ + dataType?: 'json' | 'text' | 'base64'; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + } + function httpRequest(options: RequestOptions): void; + + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器地址 */ + url: string; + /** 要上传文件资源的本地定位符 */ + filePath: string; + /** 文件名,即对应的 key, 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + fileName: string; + /** + * 文件类型 + */ + fileType: 'image' | 'video' | 'audio'; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form 数据 */ + formData?: any; + success?(res: { + /** 服务器返回的数据 */ + data: string; + /** HTTP 状态码 */ + statusCode: string; + header: any; + }): void; + } + /** + * 上传本地资源到开发者服务器。 + */ + function uploadFile(options: UploadFileOptions): void; + + interface DownloadFileOptions extends BaseOptions { + /** 下载文件地址 */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。 + */ + function downloadFile(options: DownloadFileOptions): void; + + interface ConnectSocketOptions extends BaseOptions { + /** 目标服务器url */ + url: string; + /** 请求的参数 */ + data?: any; + /** 设置请求的头部 */ + header?: RequestHeader; + method?: 'GET' | 'POST'; // todo missing in api + } + /** + * 创建一个 WebSocket 的连接; + * 一个支付宝小程序同时只能保留一个 WebSocket 连接,如果当前已存在 WebSocket 连接,会自动关闭该连接,并重新创建一个新的 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + + /** + * 监听WebSocket连接打开事件。 + */ + function onSocketOpen(callback: () => void): void; + + /** + * 监听WebSocket关闭。 + */ + function onSocketClose(callback: () => void): void; + + /** + * 取消监听WebSocket连接打开事件。 + */ + function offSocketOpen(callback: () => void): void; + + /** + * 监听WebSocket错误。 + */ + function onSocketError(callback: (error: any) => void): void; + + /** + * 取消监听WebSocket错误。 + */ + function offSocketError(callback: (error: any) => void): void; + + interface SendSocketMessageOptions extends BaseOptions { + /** + * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String + */ + data: string | ArrayBuffer; + /** + * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 + */ + isBuffer?: boolean; + } + /** + * 通过 WebSocket 连接发送数据,需要先使用 my.connectSocket 发起建连,并在 my.onSocketOpen 回调之后再发送数据。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: { + /** + * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String + */ + data: string | ArrayBuffer; + /** + * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 + */ + isBuffer?: boolean; + }) => void): void; + function offSocketMessage(callback: (error: any) => void): void; + + interface CloseSocketOptions extends BaseOptions { + success?(res: any): void; + } + /** + * 监听WebSocket关闭。 + */ + function closeSocket(options?: CloseSocketOptions): void; + + /** + * 取消监听WebSocket关闭。 + */ + function offSocketClose(callback: (error: any) => void): void; + //#endregion +} + +// 设备 +declare namespace my { + //#region canIUse https://docs.alipay.com/mini/api/can-i-use + /** + * 判断当前小程序的 API、入参或返回值、组件、属性等在当前版本是否支持。 + * 参数使用 ${API}.${type}.${param}.${option} 或者 ${component}.${attribute}.${option} 方式来调用 + * - API 表示 api 名字 + * - type 取值 object/return/callback 表示 api 的判断类型 + * - param 表示参数的某一个属性名 + * - option 表示参数属性的具体属性值 + * - component 表示组件名称 + * - attribute 表示组件属性名 + * - option 表示组件属性值 + */ + function canIUse(api: string): boolean; + //#endregion + + //#region 获取基础库版本号 https://docs.alipay.com/mini/api/sdk-version + const SDKVersion: string; + //#endregion + //#region 系统信息 https://docs.alipay.com/mini/api/system-info + interface SystemInfo { + /** + * 手机型号 + */ + model: string; + /** + * 设备像素比 + */ + pixelRatio: number; + /** + * 窗口宽度 + */ + windowWidth: number; + /** + * 窗口高度 + */ + windowHeight: number; + /** + * 支付宝设置的语言 + */ + language: string; + /** + * 支付宝版本号 + */ + version: string; + /** + * 设备磁盘容量 + */ + storage: string; + /** + * 当前电量百分比 + */ + currentBattery: string; + /** + * 系统版本 + */ + system: string; + /** + * 系统名:Android,iOS + */ + platform: 'Android' | 'iOS' | string; + /** + * 屏幕宽度 + */ + screenWidth: number; + /** + * 屏幕高度 + */ + screenHeight: number; + /** + * 手机品牌 + */ + brand: string; + /** + * 用户设置字体大小 + */ + fontSizeSetting: number; + /** + * 当前运行的客户端,当前是支付宝则有效值是"alipay" + */ + app: 'alipay' | string; + } + interface GetSystemInfoOptions extends BaseOptions { + success?(res: SystemInfo): void; + } + function getSystemInfo(options: GetSystemInfoOptions): void; + function getSystemInfoSync(): SystemInfo; + //#endregion + + //#region 网络状态 https://docs.alipay.com/mini/api/network-status + interface GetNetworkTypeOptions extends BaseOptions { + success?(res: { + /** 网络是否可用 */ + networkAvailable: boolean; + /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ + networkType: NetworkType; + }): void; + } + type NetworkType = 'UNKNOWN' | 'NOTREACHABLE' | 'WIFI' | '3G' | '2G' | '4G' | 'WWAN'; + function getNetworkType(options: GetNetworkTypeOptions): void; + + /** + * 开始网络状态变化的监听 + */ + function onNetworkStatusChange(callback: (res: { + /** 网络是否可用 */ + isConnected: boolean; + /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ + networkType: NetworkType; + }) => void): void; + + /** + * 取消网络状态变化的监听 + */ + function offNetworkStatusChange(): void; + //#endregion + + //#region 剪贴板 https://docs.alipay.com/mini/api/clipboard + interface GetClipboardOptions extends BaseOptions { + success?(res: { + text: string; + }): void; + } + function getClipboard(options: GetClipboardOptions): void; + + interface SetClipboardOptions extends BaseOptions { + /** 剪贴板数据 */ + text: string; + } + function setClipboard(options: SetClipboardOptions): void; + //#endregion + + //#region 摇一摇 https://docs.alipay.com/mini/api/shake + function watchShake(options: BaseOptions): void; + //#endregion + + //#region 震动 https://docs.alipay.com/mini/api/vibrate + /** + * 调用震动功能。 + */ + function vibrate(options?: BaseOptions): void; + + /** + * 调用震动功能。 + */ + function vibrateLong(options?: BaseOptions): void; + + /** + * 调用震动功能。 + */ + function vibrateShort(options?: BaseOptions): void; + //#endregion + + //#region 拨打电话 https://docs.alipay.com/mini/api/macke-call + interface MakePhoneCallOptions extends BaseOptions { + /** + * 需要拨打的电话号码 + */ + number: string; + } + /** + * 拨打电话 + */ + function makePhoneCall(options: MakePhoneCallOptions): void; + //#endregion + + //#region 获取服务器时间 https://docs.alipay.com/mini/api/get-server-time + interface GetServerTimeOptions extends BaseOptions { + success?(res: { + /** 服务器时间的毫秒数 */ + time: number; + }): void; + } + function getServerTime(options: GetServerTimeOptions): void; + //#endregion + + //#region 用户截屏事件 https://docs.alipay.com/mini/api/user-capture-screen + /** + * 监听用户主动截屏事件,用户使用系统截屏按键截屏时触发此事件 + */ + function onUserCaptureScreen(callback?: (res: any) => void): void; + + /** + * 取消监听截屏事件。一般需要与 my.onUserCaptureScreen 成对出现。 + */ + function offUserCaptureScreen(): void; + //#endregion + + //#region 屏幕亮度 https://docs.alipay.com/mini/api/screen-brightness + interface SetKeepScreenOnOptions extends BaseOptions { + /** 是否保持屏幕常亮 */ + keepScreenOn: boolean; + success?(res: { errMsg: string }): void; + } + /** + * 设置是否保持常亮状态。 + * 仅在当前小程序生效,离开小程序后设置失效。 + */ + function setKeepScreenOn(options?: SetKeepScreenOnOptions): void; + + interface GetScreenBrightnessOptions extends BaseOptions { + /** 屏幕亮度值,范围 0~1,0 最暗,1 最亮 */ + success(value: number): void; + } + /** + * 获取屏幕亮度 + */ + function getScreenBrightness(options?: GetScreenBrightnessOptions): void; + + interface SetScreenBrightnessOptions extends BaseOptions { + /** 需要设置的屏幕亮度,取值范围0-1 */ + brightness: number; + } + /** + * 设置屏幕亮度 + */ + function setScreenBrightness(options: SetScreenBrightnessOptions): void; + //#endregion + + //#region 权限引导 https://docs.alipay.com/mini/api/show-auth-guide + interface showAuthGuideOptions extends BaseOptions { + /** + * 引导的权限标识,用于标识该权限类型(如 LBS) + * 支持的 authType 如下: + * + * 权限名称 权限码 支持平台 + * 后台保活权限 BACKGROUNDER Android + * 桌面快捷权限 SHORTCUT Android + * 麦克风权限 MICROPHONE iOS + * 通讯录权限 ADDRESSBOOK iOS + * 相机权限 CAMERA iOS + * 照片权限 PHOTO iOS + * push通知栏权限 NOTIFICATION iOS + * 自启动权限 SELFSTARTING Android + * lbs总开关 LBSSERVICE iOS + * lbs开关(app) LBS iOS + */ + authType: 'BACKGROUNDER' | 'SHORTCUT' | 'MICROPHONE' | 'ADDRESSBOOK' | 'CAMERA' | 'PHOTO' | 'NOTIFICATION' | 'SELFSTARTING' | 'LBSSERVICE' | 'LBS'; + } + function showAuthGuide(options: showAuthGuideOptions): void; + //#endregion +} + +// 扫码 +declare namespace my { + //#region 扫码 https://docs.alipay.com/mini/api/scan + type scanType = "qr" | "bar"; + interface ScanCodeData { + /** + * 扫描二维码时返回二维码数据 + */ + code: string; + /** + * 所扫码的类型 + */ + qrCode: string; + /** + * 扫描条形码时返回条形码数据 + */ + barCode: string; + } + interface ScanOptions extends BaseOptions { + /** + * 扫码样式(默认 qr): + * 1. qr,扫码框样式为二维码扫码框 + * 1. bar,扫码样式为条形码扫码框 + */ + type?: scanType; + /** + * 是否隐藏相册(不允许从相册选择图片),只能从相机扫码 + */ + hideAlbum?: boolean; + success?(res: ScanCodeData): void; + } + /** + * 调起客户端扫码界面,扫码成功后返回对应的结果 + */ + function scan(options: ScanOptions): void; + //#endregion +} + +// 蓝牙 +declare namespace my { + //#region 快速接入 https://docs.alipay.com/mini/api/bluetooth-intro + //#endregion + + //#region API https://docs.alipay.com/mini/api/bluetooth-api + interface OpenBluetoothAdapterOptions extends BaseOptions { + /** 不传的话默认是true,表示是否在离开当前页面时自动断开蓝牙(仅对android有效) */ + autoClose: boolean; + success(res: { + /** + * 是否支持 BLE + */ + isSupportBLE: boolean; + }): void; + } + /** + * 初始化小程序蓝牙模块,生效周期为调用 my.openBluetoothAdapter 至调用 my.closeBluetoothAdapter 或小程序被销毁为止。 在小程序蓝牙适配器模块生效期间,开发者可以正常调用下面的小程序API,并会收到蓝牙模块相关的 on 事件回调。 + */ + function openBluetoothAdapter(options: Partial): void; + + interface CloseBluetoothAdapterOptions extends BaseOptions { + success(res: any): void; + } + /** + * 关闭本机蓝牙模块 + */ + function closeBluetoothAdapter(options: CloseBluetoothAdapterOptions): void; + + interface BluetoothAdapterStateData extends ErrMsgResponse { + /** + * 是否正在搜索设备 + */ + discovering: boolean; + /** + * 蓝牙模块是否可用(需支持 BLE 并且蓝牙是打开状态) + */ + available: boolean; + } + interface GetBluetoothAdapterStateOptions extends BaseOptions { + success(res: BluetoothAdapterStateData): void; + } + /** + * 获取本机蓝牙适配器状态 + */ + function getBluetoothAdapterState(options: GetBluetoothAdapterStateOptions): void; + + interface StartBluetoothDevicesDiscoveryOptions extends BaseOptions { + /** + * 蓝牙设备主 service 的 uuid 列表 + * 某些蓝牙设备会广播自己的主 service 的 uuid。如果这里传入该数组,那么根据该 uuid 列表,只搜索有这个主服务的设备。 + */ + services?: string[]; + /** + * 否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同 + */ + allowDuplicatesKey?: boolean; + /** + * 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报 + */ + interval?: number; + } + /** + * 开始搜寻附近的蓝牙外围设备。搜索结果将在 my.onBluetoothDeviceFound 事件中返回。 + */ + function startBluetoothDevicesDiscovery(options: StartBluetoothDevicesDiscoveryOptions): void; + + interface StopBluetoothDevicesDiscoveryOptions extends BaseOptions { + success(res: ErrMsgResponse): void; + } + /** + * 停止搜寻附近的蓝牙外围设备。请在确保找到需要连接的设备后调用该方法停止搜索。 + */ + function stopBluetoothDevicesDiscovery(options: StopBluetoothDevicesDiscoveryOptions): void; + + /** + * 蓝牙设备信息 + */ + interface BluetoothDevice { + /** + * 蓝牙设备名称,某些设备可能没有 + */ + name: string; + /** + * (兼容旧版本) 值与 name 一致 + */ + deviceName: string; + /** + * 广播设备名称 + */ + localName: string; + /** + * 设备的 id + */ + deviceId: string; + /** + * 设备信号强度 + */ + RSSI: number; + /** + * 设备的广播内容 + */ + advertisData: ArrayBuffer; + /** + * 设备的manufacturerData + */ + manufacturerData: ArrayBuffer; + } + interface GetBluetoothDevicesOptions extends BaseOptions { + success( + res: { + devices: BluetoothDevice[]; + } & ErrMsgResponse + ): void; + } + /** + * 获取所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。 + */ + function getBluetoothDevices(options: GetBluetoothDevicesOptions): void; + + interface GetConnectedBluetoothDevicesOptions extends BaseOptions { + services?: string[]; + success( + res: { + devices: BluetoothDevice[]; + } & ErrMsgResponse + ): void; + } + /** + * 获取处于已连接状态的设备。 + */ + function getConnectedBluetoothDevices(options: GetConnectedBluetoothDevicesOptions): void; + + interface BLEDeviceOptions extends BaseOptions { + /** + * 蓝牙设备id + */ + deviceId: string; + } + /** + * 连接低功耗蓝牙设备。 + */ + function connectBLEDevice(options: BLEDeviceOptions): void; + + /** + * 断开与低功耗蓝牙设备的连接。 + */ + function disconnectBLEDevice(options: BLEDeviceOptions): void; + + interface WriteBLECharacteristicValueOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应的值,16进制字符串,限制在20字节内 + */ + value: string; + } + /** + * 向低功耗蓝牙设备特征值中写入数据。 + */ + function writeBLECharacteristicValue( + options: WriteBLECharacteristicValueOptions + ): void; + + interface ReadBLECharacteristicValueOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + success( + res: { + characteristic: { + /** + * 蓝牙设备特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙设备特征值对应的二进制值 + */ + value: ArrayBuffer; + }; + } & ErrMsgResponse + ): void; + } + + /** + * 读取低功耗蓝牙设备特征值中的数据。调用后在 my.onBLECharacteristicValueChange() 事件中接收数据返回。 + */ + function readBLECharacteristicValue(options: ReadBLECharacteristicValueOptions): void; + + interface NotifyBLECharacteristicValueChangeOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应 service 的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) + */ + descriptorId?: string; + /** + * 是否启用notify或indicate + */ + state?: boolean; + } + function notifyBLECharacteristicValueChange(optons: NotifyBLECharacteristicValueChangeOptions): void; + + interface NotifyBLECharacteristicValueChangedOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) + */ + descriptorId?: string; + /** + * true: 启用 notify; false: 停用 notify + */ + state: boolean; + success(res: ErrMsgResponse): void; + } + /** + * 启用低功耗蓝牙设备特征值变化时的 notify 功能。注意:设备的特征值必须支持 notify/indicate 才可以成功调用,具体参照 characteristic 的 properties 属性 另外,必须先启用 notify 才能监听到设备 characteristicValueChange 事件。 + */ + function notifyBLECharacteristicValueChanged(options: NotifyBLECharacteristicValueChangedOptions): void; + + interface GetBLEDeviceServicesOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success(res: { + services: Array<{ + /** + * 蓝牙设备服务的 uuid + */ + serviceId: string; + /** + * 该服务是否为主服务 + */ + isPrimary: boolean; + }>; + } & ErrMsgResponse): void; + } + /** + * 获取蓝牙设备所有 service(服务) + */ + function getBLEDeviceServices(options: GetBLEDeviceServicesOptions): void; + + interface GetBLEDeviceCharacteristicsOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙服务 uuid + */ + serviceId: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success(res: { + characteristics: Array<{ + /** + * 蓝牙设备特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙设备特征值对应的16进制值 + */ + value: ArrayBuffer; + /** + * 该特征值支持的操作类型 + */ + properties: Array<{ + /** + * 该特征值是否支持 read 操作 + */ + read: boolean; + /** + * 该特征值是否支持 write 操作 + */ + write: boolean; + /** + * 该特征值是否支持 notify 操作 + */ + notify: boolean; + /** + * 该特征值是否支持 indicate 操作 + */ + indicate: boolean; + }>; + }>; + } & ErrMsgResponse): void; + } + /** + * 获取蓝牙设备所有 characteristic(特征值) + */ + function getBLEDeviceCharacteristics(options: GetBLEDeviceCharacteristicsOptions): void; + + interface OnBluetoothDeviceFoundOptions extends BaseOptions { + success?(res: { + devices: BluetoothDevice[]; + }): void; + } + /** + * 搜索到新的蓝牙设备时触发此事件。 + */ + function onBluetoothDeviceFound(options: OnBluetoothDeviceFoundOptions): void; + + /** + * 移除寻找到新的蓝牙设备事件的监听。 + */ + function offBluetoothDeviceFound(callback?: any): void; + + interface OnBLECharacteristicValueChangeOptions extends BaseOptions { + success?(res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应 service 的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * 特征值最新的16进制值 + */ + value: ArrayBuffer; + }): void; + } + /** + * 监听低功耗蓝牙设备的特征值变化的事件。 + */ + function onBLECharacteristicValueChange(options: OnBLECharacteristicValueChangeOptions): void; + + interface OnBLEConnectionStateChangedOptions extends BaseOptions { + success?(res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 连接目前的状态 + */ + connected: boolean; + }): void; + } + /** + * 移除低功耗蓝牙设备的特征值变化事件的监听。 + */ + function offBLECharacteristicValueChange(callback?: any): void; + + /** + * 监听低功耗蓝牙连接的错误事件,包括设备丢失,连接异常断开等。 + */ + function onBLEConnectionStateChanged(options: OnBLEConnectionStateChangedOptions): void; + + /** + * 移除低功耗蓝牙连接状态变化事件的监听。 + */ + function offBLEConnectionStateChanged(): void; + + interface BluetoothAdapterState { + /** + * 蓝牙适配器是否可用 + */ + available: boolean; + /** + * 蓝牙适配器是否处于搜索状态 + */ + discovering: boolean; + } + /** + * 监听本机蓝牙状态变化的事件。 + */ + function onBluetoothAdapterStateChange(callback: (res: BluetoothAdapterState) => void): void; + + /** + * 移除本机蓝牙状态变化的事件的监听。 + */ + function offBluetoothAdapterStateChange(): void; + //#endregion +} + +// iBeacon +declare namespace my { + //#region iBeacon https://docs.alipay.com/mini/api/yqleyc + interface StartBeaconDiscoveryOptions extends BaseOptions { + /** + * iBeacon设备广播的 uuids + */ + uuids: string[]; + success?(res: ErrMsgResponse): void; + } + /** + * 开始搜索附近的iBeacon设备 + */ + function startBeaconDiscovery(options: StartBeaconDiscoveryOptions): void; + + interface StopBeaconDiscoveryOptions extends BaseOptions { + success?(res: ErrMsgResponse): void; + } + /** + * 停止搜索附近的iBeacon设备 + */ + function stopBeaconDiscovery(options: StopBeaconDiscoveryOptions): void; + + interface Beacon { + /** iBeacon 设备广播的 uuid */ + uuid: string; + /** iBeacon 设备的主 id */ + major: string; + /** iBeacon 设备的次 id */ + minor: string; + /** 表示设备距离的枚举值(0-3分别代表:未知、极近、近、远) */ + proximity: 0 | 1 | 2 | 3; + /** iBeacon 设备的距离 */ + accuracy: number; + /** iBeacon 信号强度 */ + rssi: number; + } + interface GetBeaconsSuccess { + beacons: Beacon[]; + /** + * errorCode=0 ,接口调用成功 + */ + errCode: string; + /** + * ok + */ + errMsg: string; + } + interface GetBeaconsOptions extends BaseOptions { + success?(options: GetBeaconsSuccess): void; + } + /** + * 获取所有已搜索到的iBeacon设备 + */ + function getBeacons(options: GetBeaconsOptions): void; + + interface BeaconUpdateOptions extends BaseOptions { + success?(res: { + beacons: Beacon[]; + }): void; + } + /** + * 监听 iBeacon 设备的更新事件 + */ + function onBeaconUpdate(options: BeaconUpdateOptions): void; + + interface BeaconServiceChangeOptions extends BaseOptions { + success?(res: { + /** + * 服务目前是否可用 + */ + available: boolean; + /** + * 目前是否处于搜索状态 + */ + discovering: boolean; + }): void; + } + /** + * 监听 iBeacon 服务的状态变化 + */ + function onBeaconServiceChange(options: BeaconServiceChangeOptions): void; + //#endregion +} + +// 数据安全 +declare namespace my { + //#region 数据安全 https://docs.alipay.com/mini/api/data-safe + interface RsaOptions extends BaseOptions { + /** + * 使用rsa加密还是rsa解密,encrypt加密,decrypt解密 + */ + action: string; + /** + * 要处理的文本,加密为原始文本,解密为Base64编码格式文本 + */ + text: string; + /** + * rsa秘钥,加密使用公钥,解密使用私钥 + */ + key: string; + success?(res: { + /** + * 经过处理过后得到的文本,加密为Base64编码文本,解密为原始文本 + */ + text: string; + }): void; + } + /** + * 非对称加密。 + */ + function rsa(options: RsaOptions): void; + //#endregion +} + +// 分享 +declare namespace my { + //#region 分享 https://docs.alipay.com/mini/api/share_app + //#endregion +} + +// 自定义分析 +declare namespace my { + //#region 自定义分析 https://docs.alipay.com/mini/api/report + /** + * 自定义分析数据的上报接口。使用前需要在小程序管理后台的事件管理中新建事件,并配置好事件名和字段。 + * + * @param eventName 自定义事件名,需申请 + * @param data 上报的数据 + */ + function reportAnalytics(eventName: string, data: any): void; + + /** + * 隐藏分享按钮。 + */ + function hideShareMenu(options?: BaseOptions): void; + //#endregion +} + +declare namespace my { + interface LaunchOptions { + /** + * 打开小程序的路径 + */ + path: string; + /** + * 打开小程序的query + */ + query: object; + /** + * 打开小程序的[场景值] + */ + scene: number; + /** + * shareTicket,详见 获取更多[转发信息] + */ + shareTicket: string; + /** + * 当场景为由从另一个小程序或公众号或App打开时,返回此字段 + */ + referrerInfo: object; + /** + * 来源小程序或公众号或App的 appId,详见下方说明 + */ + "referrerInfo.appId": string; + /** + * 来源小程序传过来的数据,scene=1037或1038时支持 + */ + "referrerInfo.extraData": object; + // #endregion + } + interface AppOptions { + /** + * 监听小程序初始化。 + * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) + * 生命周期函数 + */ + onLaunch?: (this: App, option: LaunchOptions) => void; + /** + * 监听小程序显示。 + * 当小程序启动,或从后台进入前台显示,会触发 onShow + * 生命周期函数 + */ + onShow?: (this: App, option: LaunchOptions) => void; + /** + * 监听小程序隐藏。 + * 当小程序从前台进入后台,会触发 onHide + * 生命周期函数 + */ + onHide?: (this: App) => void; + /** + * 错误监听函数 + * 当小程序发生脚本错误或者 api 调用失败时 + * 会触发 onError 并带上错误信息 + */ + onError?: (this: App, msg: string) => void; + /** + * 小程序退出时触发 + */ + onUnlaunch?: (this: App) => void; + /** + * 全局Data + */ + globalData?: object; + [key: string]: any; + } + interface CreateIntersectionObserverOption { + thresholds?: [number, number]; + initialRatio?: number; + selectAll?: boolean; + } + + interface Margins { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + interface ObserveResponse { + id: string; + dataset: any; + time: number; + intersectionRatio: number; // 相交区域占目标节点的布局区域的比例 + boundingClientRect: RectArea; + intersectionRect: RectArea; + relativeRect: RectArea; + } + interface IntersectionObserver { + relativeTo(selector?: string, margins?: Margins): IntersectionObserver; + relativeToViewport(margins?: Margins): IntersectionObserver; + observe( + selector?: string, + callback?: (response: ObserveResponse) => void + ): IntersectionObserver; + disconnect(): void; + } + interface ComponentRelation { + /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ + type: "parent" | "child" | "ancestor" | "descendant"; + /** 如果这一项被设置,则它表示关联的目标节点所应具有的behavior,所有拥有这一behavior的组件节点都会被关联 */ + target?: string; + /** 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件attached生命周期之后 */ + linked?: (target: Component) => void; + /** 关系生命周期函数,当关系在页面节点树中发生改变时触发,触发时机在组件moved生命周期之后 */ + linkChanged?: (target: Component) => void; + /** 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件detached生命周期之后 */ + unlinked?: (target: Component) => void; + } + interface Component { + /** + * 组件的文件路径 + */ + is: string; + /** + * 节点id + */ + id: string; + /** + * 节点dataset + */ + dataset: string; + /** + * 组件数据,包括内部数据和属性值 + */ + data: any; + + /** + * 组件数据,包括内部数据和属性值(与 data 一致) + */ + properties: any; + /** + * 将数据从逻辑层发送到视图层,同时改变对应的 this.data 的值 + * 1. 直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致。 + * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 + * 3. 请不要把 data 中任何一项的 value 设为 undefined ,否则这一项将不被设置并可能遗留一些潜在问题 + * @param data object 以 key,value 的形式表示将 this.data 中的 key 对应的值改变成 value + * @param [callback] callback 是一个回调函数,在这次setData对界面渲染完毕后调用 + */ + setData( + data: any, + callback?: () => void + ): void; + hasBehavior(behavior: any): boolean; + triggerEvent( + name: string, + details?: any, + options?: Partial<{ + bubbles: boolean; + composed: boolean; + capturePhase: boolean; + }> + ): void; + createSelectorQuery(): SelectorQuery; + createIntersectionObserver( + options?: CreateIntersectionObserverOption + ): IntersectionObserver; + /** + * 使用选择器选择组件实例节点 + * 返回匹配到的第一个组件实例对象 + */ + selectComponent(selector: string): Component; + /** + * selector 使用选择器选择组件实例节点,返回匹配到的全部组件实例对象组成的数组 + */ + selectAllComponents(selector: string): Component[]; + getRelationNodes(relationKey: string): ComponentRelation[]; + } + interface Page extends Component { + /** + * data + */ + data: any; + /** + * 强制更新 + */ + forceUpdate(): void; + /** + * 字段可以获取到当前页面的路径。 + */ + route(): void; + /** + * 更新 + */ + update(): void; + /** + * 将页面滚动到目标位置。 + * + * scrollTop 滚动到页面的目标位置(单位px) + * [duration] 滚动动画的时长,默认300ms,单位 ms + */ + pageScrollTo(option?: PageScrollToOptions): void; + [key: string]: any; + } + interface App { + data: any; + /** + * 获取当前页面 + */ + getCurrentPage(): Page; + [key: string]: any; + } + interface EventTarget { + id: string; + tagName: string; + dataset: { [name: string]: string }; + } + type TouchEventType = + | "tap" + | "touchstart" + | "touchmove" + | "touchcancel" + | "touchend" + | "touchforcechange"; + + type TransitionEventType = + | "transitionend" + | "animationstart" + | "animationiteration" + | "animationend"; + + type EventType = + | "input" + | "form" + | "submit" + | "scroll" + | TouchEventType + | TransitionEventType + | "tap" + | "longpress"; + interface BaseEvent { + type: T; + timeStamp: number; + currentTarget: EventTarget; + target: EventTarget; + detail: Detail; + } + interface Options { + query: any; // 当前小程序的 query + path: string; // 当前小程序的页面地址 + } + interface PageOptions { + data: any; + onLaunch(this: Page, options: Options): void; + onShow(this: Page, options: Options): void; + onHide(this: Page): void; + onError(this: Page): void; + [key: string]: any; + } + function postMessage(param: any): void; + type onMessageFun = (p: any) => void; + let onMessage: onMessageFun; +} + +declare function App(app: Partial): void; + +declare function getApp(): my.App; + +declare function Behavior(options?: any): my.Component; + +declare function Component(options?: any): my.Component; + +declare function Page(options: Partial): void; + +declare function getCurrentPages(): my.Page[]; diff --git a/types/ali-app/tsconfig.json b/types/ali-app/tsconfig.json new file mode 100644 index 0000000000..a2402fac2c --- /dev/null +++ b/types/ali-app/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "esnext", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "ali-app-tests.ts" + ], + "exclude": [ + ".prettierrc" + ] +} \ No newline at end of file diff --git a/types/ali-app/tslint.json b/types/ali-app/tslint.json new file mode 100644 index 0000000000..f491d1bed9 --- /dev/null +++ b/types/ali-app/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-mergeable-namespace": false, + "no-unnecessary-generics": false + } +} \ No newline at end of file diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 9ad6d9ceda..2ea088f841 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -8,7 +8,7 @@ import * as Promise from 'bluebird'; import * as events from 'events'; -import { Replies, Options, Message } from './properties'; +import { Replies, Options, Message, GetMessage, ConsumeMessage } from './properties'; export * from './properties'; export interface Connection extends events.EventEmitter { @@ -40,10 +40,10 @@ export interface Channel extends events.EventEmitter { publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - consume(queue: string, onMessage: (msg: Message | null) => any, options?: Options.Consume): Promise; + consume(queue: string, onMessage: (msg: ConsumeMessage | null) => any, options?: Options.Consume): Promise; cancel(consumerTag: string): Promise; - get(queue: string, options?: Options.Get): Promise; + get(queue: string, options?: Options.Get): Promise; ack(message: Message, allUpTo?: boolean): void; ackAll(): void; diff --git a/types/amqplib/properties.d.ts b/types/amqplib/properties.d.ts index 9f96b14f5c..97dc8ac393 100644 --- a/types/amqplib/properties.d.ts +++ b/types/amqplib/properties.d.ts @@ -145,12 +145,32 @@ export interface Message { properties: MessageProperties; } -export interface MessageFields { +export interface GetMessage extends Message { + fields: GetMessageFields; +} + +export interface ConsumeMessage extends Message { + fields: ConsumeMessageFields; +} + +export interface CommonMessageFields { deliveryTag: number; redelivered: boolean; exchange: string; routingKey: string; - messageCount: string; +} + +export interface MessageFields extends CommonMessageFields { + messageCount?: number; + consumerTag?: string; +} + +export interface GetMessageFields extends CommonMessageFields { + messageCount: number; +} + +export interface ConsumeMessageFields extends CommonMessageFields { + deliveryTag: number; } export interface MessageProperties { diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 6885916e8a..e488bd6b49 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -340,6 +340,7 @@ declare module 'angular' { interface IMenuService { hide(response?: any, options?: any): IPromise; + open(event?: MouseEvent): void; } interface IColorPalette { diff --git a/types/angular-ui-sortable/angular-ui-sortable-tests.ts b/types/angular-ui-sortable/angular-ui-sortable-tests.ts index 9ecde2f92a..9418b5741c 100644 --- a/types/angular-ui-sortable/angular-ui-sortable-tests.ts +++ b/types/angular-ui-sortable/angular-ui-sortable-tests.ts @@ -16,6 +16,9 @@ interface SortLogInfo { Text: string; } +// Ensure that the jQuery-ui defined `sortable()` method is not overwritten +jQuery().sortable(); // $ExpectType JQuery + myApp.controller('sortableController', function ($scope: MySortableControllerScope) { $scope.sortableOptions = { activate: function(e, ui) { @@ -84,6 +87,7 @@ myApp.controller('sortableController', function ($scope: MySortableControllerSco update: function(e, ui) { var jQueryEventObject: JQueryEventObject = e; var uiSortableUIParams: ng.ui.UISortableUIParams = ui; + ui.item.sortable; // $ExpectType UISortableProperties var voidcanceled: void = ui.item.sortable.cancel(); var isCanceled: Boolean = ui.item.sortable.isCanceled(); var isCustomHelperUsed: Boolean =ui.item.sortable.isCustomHelperUsed(); diff --git a/types/angular-ui-sortable/index.d.ts b/types/angular-ui-sortable/index.d.ts index aa81038346..9ecf06e112 100644 --- a/types/angular-ui-sortable/index.d.ts +++ b/types/angular-ui-sortable/index.d.ts @@ -2,12 +2,16 @@ // Project: https://github.com/angular-ui/ui-sortable // Definitions by: Thodoris Greasidis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// +/// import * as ng from 'angular'; +// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 +type Omit = Pick; + declare module 'angular' { export namespace ui { @@ -79,11 +83,11 @@ declare module 'angular' { isCustomHelperUsed(): Boolean; } - interface UISortableUIItem extends ng.IAugmentedJQuery { + interface UISortableUIItem extends Omit { sortable: UISortableProperties; } - interface UISortableUIParams extends SortableUIParams { + interface UISortableUIParams extends Omit { item: UISortableUIItem; } diff --git a/types/animejs/index.d.ts b/types/animejs/index.d.ts index a975f59513..069187b15e 100644 --- a/types/animejs/index.d.ts +++ b/types/animejs/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -type FunctionBasedParamter = (element: HTMLElement, index: number, length: number) => number; +type FunctionBasedParameter = (element: HTMLElement, index: number, length: number) => number; type AnimeCallbackFunction = (anim: anime.AnimeInstance) => void; // Allowing null is necessary because DOM queries may not return anything. type AnimeTarget = string | object | HTMLElement | SVGElement | NodeList | null; @@ -55,10 +55,10 @@ declare namespace anime { interface AnimeAnimParams { targets: AnimeTarget | ReadonlyArray; - duration?: number | FunctionBasedParamter; - delay?: number | FunctionBasedParamter; - elasticity?: number | FunctionBasedParamter; - round?: number | boolean | FunctionBasedParamter; + duration?: number | FunctionBasedParameter; + delay?: number | FunctionBasedParameter; + elasticity?: number | FunctionBasedParameter; + round?: number | boolean | FunctionBasedParameter; easing?: EasingOptions | string | ReadonlyArray; @@ -106,7 +106,7 @@ declare namespace anime { } interface AnimeTimelineAnimParams extends AnimeAnimParams { - offset: number | string | FunctionBasedParamter; + offset: number | string | FunctionBasedParameter; } interface AnimeTimelineInstance extends AnimeInstance { diff --git a/types/ansi/ansi-tests.ts b/types/ansi/ansi-tests.ts new file mode 100644 index 0000000000..5d8e73e8ec --- /dev/null +++ b/types/ansi/ansi-tests.ts @@ -0,0 +1,24 @@ +import ansi = require('ansi'); +const cursor = ansi(process.stdout); + +Object.keys({ + white: 37 + , black: 30 + , blue: 34 + , cyan: 36 + , green: 32 + , magenta: 35 + , red: 31 + , yellow: 33 + , grey: 90 + , brightBlack: 90 + , brightRed: 91 + , brightGreen: 92 + , brightYellow: 93 + , brightBlue: 94 + , brightMagenta: 95 + , brightCyan: 96 + , brightWhite: 97 +}).forEach((color) => { + cursor[color]().bold().write(`Hello, bold ${color.replace(/([a-z])([A-Z])/g, (_: string, l: string, u: string): string => `${l} ${u.toLowerCase()}`)} world!\n`).reset(); +}); diff --git a/types/ansi/index.d.ts b/types/ansi/index.d.ts new file mode 100644 index 0000000000..976268a29a --- /dev/null +++ b/types/ansi/index.d.ts @@ -0,0 +1,168 @@ +// Type definitions for ansi 0.3 +// Project: https://www.npmjs.com/package/ansi +// Definitions by: Gustavo6046 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * References: + * + * - http://en.wikipedia.org/wiki/ANSI_escape_code + * - http://www.termsys.demon.co.uk/vtansi.htm + * + */ + +/// +import { Stream } from "stream"; + +declare function ansi(stream: Stream, options?: any): ansi.Cursor; + +declare namespace ansi { + class Cursor { + constructor(stream: Stream, options?: any); + + /** + * Helper function that calls `write()` on the underlying Stream. + * Returns `this` instead of the write() return value to keep + * the chaining going. + */ + write(data: string): Cursor; + + /** + * Buffer `write()` calls into memory. + * + * @api public + */ + buffer(): Cursor; + + /** + * Write out the in-memory buffer. + * + * @api public + */ + flush(): Cursor; + + /** + * Makes a beep sound! + */ + beep(): Cursor; + + /** + * Moves cursor to specific position + */ + goto(x?: number, y?: number): Cursor; + + /** + * Resets all ANSI formatting on the stream. + */ + reset(): Cursor; + + /** + * Sets the foreground color with the given RGB values. + * The closest match out of the 216 colors is picked. + */ + rgb(r: number, g: number, b: number): Cursor; + + /** + * Accepts CSS color codes for use with ANSI escape codes. + * For example: `#FF000` would be bright red. + */ + hex(color: string): Cursor; + + up(): Cursor; + down(): Cursor; + forward(): Cursor; + back(): Cursor; + nextLine(): Cursor; + previousLine(): Cursor; + horizontalAbsolute(): Cursor; + eraseData(): Cursor; + eraseLine(): Cursor; + scrollUp(): Cursor; + scrollDown(): Cursor; + savePosition(): Cursor; + restorePosition(): Cursor; + queryPosition(): Cursor; + hide(): Cursor; + show(): Cursor; + + bold(): Cursor; + italic(): Cursor; + underline(): Cursor; + inverse(): Cursor; + resetbold(): Cursor; + resetitalic(): Cursor; + resetunderline(): Cursor; + resetinverse(): Cursor; + + white(): Cursor; + black(): Cursor; + blue(): Cursor; + cyan(): Cursor; + green(): Cursor; + magenta(): Cursor; + red(): Cursor; + yellow(): Cursor; + grey(): Cursor; + brightBlack(): Cursor; + brightRed(): Cursor; + brightGreen(): Cursor; + brightYellow(): Cursor; + brightBlue(): Cursor; + brightMagenta(): Cursor; + brightCyan(): Cursor; + brightWhite(): Cursor; + } + + /** + * The `Colorer` class manages both the background and foreground colors. + */ + class Colorer { + constructor(cursor: Cursor, base: string); + + /** + * Write an ANSI color code, ensuring that the same code doesn't get rewritten. + */ + _setColorCode(code: string): Colorer; + + /** + * Resets the color. + */ + reset(): Cursor; + + /** + * Sets the foreground color with the given RGB values. + * The closest match out of the 216 colors is picked. + */ + rgb(r: number, g: number, b: number): Cursor; + + /** + * Accepts CSS color codes for use with ANSI escape codes. + * For example: `#FF000` would be bright red. + */ + hex(color: string): Cursor; + + white(): Cursor; + black(): Cursor; + blue(): Cursor; + cyan(): Cursor; + green(): Cursor; + magenta(): Cursor; + red(): Cursor; + yellow(): Cursor; + grey(): Cursor; + brightBlack(): Cursor; + brightRed(): Cursor; + brightGreen(): Cursor; + brightYellow(): Cursor; + brightBlue(): Cursor; + brightMagenta(): Cursor; + brightCyan(): Cursor; + brightWhite(): Cursor; + } + + interface Cursor { + [key: string]: (...anything: any[]) => Cursor; + } +} + +export = ansi; diff --git a/types/ansi/tsconfig.json b/types/ansi/tsconfig.json new file mode 100644 index 0000000000..8c698148e6 --- /dev/null +++ b/types/ansi/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts", + "ansi-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "noEmit": true, + "types": [], + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/types/ansi/tslint.json b/types/ansi/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/ansi/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/aphrodite/index.d.ts b/types/aphrodite/index.d.ts index 3e7807b6b6..f41aadec46 100644 --- a/types/aphrodite/index.d.ts +++ b/types/aphrodite/index.d.ts @@ -12,7 +12,7 @@ type FontFamily = | BaseCSSProperties['fontFamily'] | CSS.FontFace; -type Omit = Pick; +type Omit = Pick>; type CSSProperties = Omit & { fontFamily?: FontFamily | FontFamily[]; diff --git a/types/apostrophe/index.d.ts b/types/apostrophe/index.d.ts index 5201453542..9c415a3931 100644 --- a/types/apostrophe/index.d.ts +++ b/types/apostrophe/index.d.ts @@ -145,6 +145,9 @@ declare namespace apostrophe { required?: boolean; options?: AposObject; choices?: SelectChoice[]; + widgetType?: string; + titleField?: string; + schema?: Field[]; } interface SelectChoice { diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 76641f5270..5babc4a961 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -1698,7 +1698,7 @@ declare module "@arangodb/crypto" { key: string | null, token: string, noVerify?: boolean - ): string | null; + ): object | null; function md5(message: string): string; function sha1(message: string): string; function sha224(message: string): string; diff --git a/types/ascii-art/ascii-art-tests.ts b/types/ascii-art/ascii-art-tests.ts new file mode 100644 index 0000000000..d5a2d567f8 --- /dev/null +++ b/types/ascii-art/ascii-art-tests.ts @@ -0,0 +1,193 @@ +import art from 'ascii-art'; + +art.font('test', 'doom').toPromise(); + +art.font('my text', 'Doom', (rendered: string) => { + rendered.big(); +}); + +art.font('my text', 'Doom', '', (rendered) => { + rendered.big(); +}); + +art.artwork({ + artwork: 'textfiles.com/art/st-char.asc' +}).lines(31, 45, (rendered: string) => { + // cleanup non-unix terminators + rendered = rendered.replace(/\r/g, ''); + art.image({ + filepath : '~/Images/earth_in_space.jpg', + alphabet : 'ultra-wide' + }).overlay(rendered, { + x: 0, + y: -1, + style: 'red+blink', + transparent: '&' + }, (_final: any) => {}); +}); + +art.font('Ghost Wire BBS', 'Doom', (logo) => { + art.font('No place like home', 'rusted', (subtext) => { + art.table({ + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ', + data: [ + {name: art.style('current users', 'red'), value: '203'}, + {name: 'operator', value: 'vince.vega'}, + {name: 'dial-in', value: '(917)555-4202'}, + ] + }).lines(2, (table: any) => { + art.image({ + filepath : '~/Images/starburst_red.jpg', + alphabet : 'ultra-wide' + }).lines(2, 30).overlay(logo, { + x: 0, + y: 0, + style: 'blue', + }).overlay(subtext, { + x: 19, + y: 8, + style: 'yellow', + }).overlay(table, { + x: -1, + y: -1, + style: 'green', + }, (_final: any) => { + }); + }); + }); +}); + +art.image({ + width : 40, + filepath : '/Images/initech.png', + alphabet : 'wide' +}).font('INITECH', 'Doom', 'cyan', (_ascii) => { +}); + +art.table({ + data: [ + {text: ' .\'ANDRE. '}, + {text: ' ..THE.GIANT\'. '}, + {text: '.With.Bobby."The.Brain"'}, + {text: '.Heenan.'} + ], + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ' +}).lines(2, (table: any) => { + art.strings([ + 'ANDRE', + 'the', + 'GIANT', + 'POSSE', + '7\'4"', + '520 LB' + ], 'rusted', (andre: any, the: any, giant: any, posse: any, height: any, weight: any) => { + art.strings([ 'has', 'a'], 'twopoint', (has: any, a: any) => { + art.image({ + filepath : '/Images/andre_has_a_posse.jpeg', + alphabet : 'ultra-wide' + }).overlay(andre, { + x: 8, y: 4, + style: 'white' + }).overlay(the, { + x: 10, y: 7, + style: 'white', + transparent : true + }).overlay(giant, { + x: 8, y: 10, + style: 'white', + transparent : true + }).overlay(has, { + x: 10, y: 14, + style: 'white' + }).overlay(a, { + x: 13, y: 17, + style: 'white' + }).overlay(posse, { + x: 5, y: 20, + style: 'bright_black', + transparent: true + }).overlay(height, { + x: 59, y: 3, + style: 'bright_black', + transparent: true + }).overlay(weight, { + x: 59, y: 8, + style: 'bright_black', + transparent: true + }).overlay(table, { + x: 6, y: -6, + style: 'bright_black', + transparent: true + }, (_final: any) => { + }); + }); + }); +}); + +art.Figlet.fontPath = 'Fonts'; + +const image = new art.Image({ + filepath: '~/Images/metropolis.jpg', + alphabet: 'variant4' +}); +image.write((_err: any, _rendered: string) => { +}); + +art.font('Prompt', 'Basic', 'red').font('v1', 'Doom', 'magenta', (_rendered) => { +}); + +art.image({ + width : 40, + filepath : '/Images/initech.png', + alphabet : 'wide' +}).font('INITECH', 'Doom', 'cyan', (_ascii) => { +}); + +art.style('my text', 'red+underline'); + +art.table({ + width : 80, + data : [ /* ... */ ], + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ', + columns : [ + { + value : 'Product', + style : 'black+gray_bg' + }, { + value : 'Maker', + style : 'white' + }, { + value : 'Location', + style : 'white' + } + ] +}, (_rendered) => { + // use rendered text +}); + +art.table({ + width : 80, + data : [ /* ... */ ], + bars : { + ul_corner: '┏', + ur_corner: '┓', + lr_corner: '┛', + ll_corner: '┗', + bottom_t: '┻', + top_t: '┳', + right_t: '┫', + left_t: '┣', + intersection: '╋', + vertical: '┃', + horizontal: '━', + }, + borderColor : 'bright_white', +}, (_rendered) => { + // use rendered text +}); diff --git a/types/ascii-art/index.d.ts b/types/ascii-art/index.d.ts new file mode 100644 index 0000000000..3a753a183b --- /dev/null +++ b/types/ascii-art/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for ascii-art 1.4 +// Project: https://github.com/khrome/ascii-art +// Definitions by: Lukas Elmer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export type StyleType = (text: string, style?: string, close?: boolean) => Art; +export type FontType = ((text: string, font?: string, styleOrCallback?: string | Cb, callback?: Cb) => Art); +export type ImageType = (options: object, callback?: Cb) => Art; +export type TableType = (options: object, callback?: Cb) => Art; +export type ArtworkType = (options: object, callback?: Cb) => Art; +export type LinesType = (...options: any[]) => Art; +export type OverlayType = (...options: any[]) => Art; +export type JoinType = (...options: any[]) => Art; +export type StringsType = (...options: any[]) => Art; + +export const style: StyleType; +export const font: FontType; +export const image: ImageType; +export const table: TableType; +export const artwork: ArtworkType; +export const lines: LinesType; +export const overlay: OverlayType; +export const join: JoinType; +export const strings: StringsType; +export const Figlet: any; +export const Image: any; + +export interface Art { + style: StyleType; + font: FontType; + image: ImageType; + table: TableType; + artwork: ArtworkType; + lines: LinesType; + overlay: OverlayType; + join: JoinType; + working: boolean; + + toPromise: (() => Promise); +} + +export type Cb = (result: string) => void; diff --git a/types/ascii-art/tsconfig.json b/types/ascii-art/tsconfig.json new file mode 100644 index 0000000000..1f9759cc1f --- /dev/null +++ b/types/ascii-art/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ascii-art-tests.ts" + ] +} diff --git a/types/ascii-art/tslint.json b/types/ascii-art/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/ascii-art/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 3daca57647..7ca266e6ce 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -4,6 +4,7 @@ // Matt Durrant // Peter Blazejewicz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace auth0; @@ -172,7 +173,7 @@ export class WebAuth { * * @param callback: any(err, token_payload) */ - parseHash(callback: Auth0Callback): void; + parseHash(callback: Auth0Callback): void; /** * Parse the url hash and extract the returned tokens depending on the transaction. @@ -183,7 +184,7 @@ export class WebAuth { * * @param callback: any(err, token_payload) */ - parseHash(options: ParseHashOptions, callback: Auth0Callback): void; + parseHash(options: ParseHashOptions, callback: Auth0Callback): void; /** * Decodes the id_token and verifies the nonce. @@ -482,7 +483,7 @@ export class CrossOriginAuthentication { callback(): void; } -export type Auth0Callback = (error: null | Auth0Error, result: T) => void; +export type Auth0Callback = (error: null | E, result: T) => void; export interface TokenProvider { enableCache?: boolean; @@ -522,18 +523,51 @@ export interface PasswordlessAuthOptions { email: string; } +/** + * These are error codes defined by the auth0-js lib. + */ +export type LibErrorCodes = 'timeout' | 'request_error' | 'invalid_token'; + +/** + * The user was not logged in at Auth0, so silent authentication is not possible. + */ +export type LoginRequiredErrorCode = 'login_required'; + +/** + * The user was logged in at Auth0 and has authorized the application, but needs to + * be redirected elsewhere before authentication can be completed; for example, when + * using a redirect rule. + */ +export type InteractionRequiredErrorCode = 'interaction_required'; + +/** + * The user was logged in at Auth0, but needs to give consent to authorize the application. + */ +export type ConsentRequiredErrorCode = 'consent_required'; + +/** + * These are error codes defined by the OpenID Connect specification. + */ +export type SpecErrorCodes = + LoginRequiredErrorCode | + InteractionRequiredErrorCode | + ConsentRequiredErrorCode | + 'account_selection_required' | + 'invalid_request_uri' | + 'invalid_request_object' | + 'request_not_supported' | + 'request_uri_not_supported' | + 'registration_not_supported'; + export interface Auth0Error { - error?: any; - errorDescription?: string; - code?: string; - description?: string; - name?: string; - policy?: string; - original?: any; - statusCode?: number; - statusText?: string; + error: LibErrorCodes | SpecErrorCodes | string; + errorDescription: string; } +export type Auth0ParseHashError = Auth0Error & { + state?: string; +}; + /** * The contents of the authResult object returned by {@link WebAuth#parseHash } */ diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 8c3a7da850..2916ec58c8 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -5,6 +5,7 @@ // Larry Faudree // Will Caulfield // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 /// diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index f4251364d2..60bbf86823 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -203,3 +203,26 @@ management.linkUsers('primaryId', { user_id: 'secondaryId' }) management.linkUsers('primaryId', { user_id: 'secondaryId' }, (err: Error, result: any) => {}); +// Get all clients (with promise) +management.getClients() + .then((clients: auth0.Client[]) => { + console.log(clients); + }) + .catch((err) => { + // Handle the error + }); + +//Get all clients (with callback) +management.getClients((err: Error, clients: auth0.Client[]) => {}); + +// Get all clients with params (with promise) +management.getClients({fields:['name','client_metadata'], include_fields:true}) + .then((clients: auth0.Client[]) => { + console.log(clients); + }) + .catch((err) => { + // Handle the error + }); + +// Get all cients with params (with callback) +management.getClients({fields:['name','client_metadata'], include_fields:true}, (err:Error, clients:auth0.Client[]) => {}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index e03ad5aa06..ed0e9d1f3f 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for auth0 2.9.2 // Project: https://github.com/auth0/node-auth0 -// Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach +// Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -588,7 +588,19 @@ export interface ImpersonateSettingOptions { clientId?: string; } - +export type ClientAppType = 'native' | 'spa' | 'regular_web' | 'non_interactive' | 'rms' | 'box' | + 'cloudbees' | 'concur' | 'dropbox' | 'mscrm' | 'echosign' | 'egnyte' | 'newrelic' | 'office365' | + 'salesforce' | 'sentry' | 'sharepoint' | 'slack' | 'springcm' | 'zendesk' | 'zoom'; +export interface GetClientsOptions { + fields?: string[]; + include_fields?: boolean; + page?: number; + per_page?: number; + include_totals?: boolean; + is_global?: boolean; + is_first_party?: boolean; + app_type?: ClientAppType[]; +} export class AuthenticationClient { @@ -661,8 +673,9 @@ export class ManagementClient { // Clients - getClients(): Promise; - getClients(cb: (err: Error, clients: Client[]) => void): void; + getClients(params?: GetClientsOptions): Promise; + getClients(cb: (err: Error, clients: Client[]) => void ): void; + getClients(params: GetClientsOptions, cb: (err: Error, clients: Client[]) => void ): void; getClient(params: ClientParams): Promise; getClient(params: ClientParams, cb: (err: Error, client: Client) => void): void; diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 59bb2c404d..c62f6115af 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -190,6 +190,8 @@ declare namespace autobahn { export class Connection { constructor(options?: IConnectionOptions); + isOpen: boolean; + open(): void; close(reason?: string, message?: string): void; diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 5fa225eafd..00b71132e9 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -8,6 +8,7 @@ declare let error: Error; declare let bool: boolean; declare let boolOrUndefined: boolean | undefined; declare let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; +declare let apiGwEvtReqCtxOpt: AWSLambda.APIGatewayEventRequestContext | null | undefined; declare let apiGwEvt: AWSLambda.APIGatewayEvent; declare let customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; declare let clientCtx: AWSLambda.ClientContext; @@ -102,11 +103,13 @@ str = apiGwEvtReqCtx.resourcePath; /* API Gateway Event */ strOrNull = apiGwEvt.body; str = apiGwEvt.headers["example"]; +str = apiGwEvt.multiValueHeaders["example"][0]; str = apiGwEvt.httpMethod; bool = apiGwEvt.isBase64Encoded; str = apiGwEvt.path; str = apiGwEvt.pathParameters!["example"]; str = apiGwEvt.queryStringParameters!["example"]; +str = apiGwEvt.multiValueQueryStringParameters!["example"][0]; str = apiGwEvt.stageVariables!["example"]; apiGwEvtReqCtx = apiGwEvt.requestContext; str = apiGwEvt.resource; @@ -115,10 +118,12 @@ str = apiGwEvt.resource; str = customAuthorizerEvt.type; str = customAuthorizerEvt.methodArn; strOrUndefined = customAuthorizerEvt.authorizationToken; -str = apiGwEvt.pathParameters!["example"]; -str = apiGwEvt.queryStringParameters!["example"]; -str = apiGwEvt.stageVariables!["example"]; -apiGwEvtReqCtx = apiGwEvt.requestContext; +str = customAuthorizerEvt.headers!["example"]; +str = customAuthorizerEvt.multiValueHeaders!["example"][0]; +str = customAuthorizerEvt.pathParameters!["example"]; +str = customAuthorizerEvt.queryStringParameters!["example"]; +str = customAuthorizerEvt.multiValueQueryStringParameters!["example"][0]; +apiGwEvtReqCtxOpt = customAuthorizerEvt.requestContext; /* DynamoDB Stream Event */ const dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { @@ -245,6 +250,9 @@ num = proxyResult.statusCode; proxyResult.headers!["example"] = str; proxyResult.headers!["example"] = bool; proxyResult.headers!["example"] = num; +proxyResult.multiValueHeaders!["example"][0] = str; +proxyResult.multiValueHeaders!["example"][0] = bool; +proxyResult.multiValueHeaders!["example"][0] = num; boolOrUndefined = proxyResult.isBase64Encoded; str = proxyResult.body; @@ -383,6 +391,8 @@ cognitoUserPoolEvent.triggerSource === "TokenGeneration_Authentication"; cognitoUserPoolEvent.triggerSource === "TokenGeneration_NewPasswordChallenge"; cognitoUserPoolEvent.triggerSource === "TokenGeneration_AuthenticateDevice"; cognitoUserPoolEvent.triggerSource === "TokenGeneration_RefreshTokens"; +cognitoUserPoolEvent.triggerSource === "UserMigration_Authentication"; +cognitoUserPoolEvent.triggerSource === "UserMigration_ForgotPassword"; str = cognitoUserPoolEvent.region; str = cognitoUserPoolEvent.userPoolId; strOrUndefined = cognitoUserPoolEvent.userName; @@ -404,6 +414,7 @@ strOrUndefined = cognitoUserPoolEvent.request.session![0].challengeMetadata; strOrUndefined = cognitoUserPoolEvent.request.challengeName; str = cognitoUserPoolEvent.request.privateChallengeParameters!["answer"]; str = cognitoUserPoolEvent.request.challengeAnswer!; +strOrUndefined = cognitoUserPoolEvent.request.password; boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; strOrUndefined = cognitoUserPoolEvent.response.smsMessage; strOrUndefined = cognitoUserPoolEvent.response.emailMessage; @@ -415,6 +426,14 @@ str = cognitoUserPoolEvent.response.publicChallengeParameters!["captchaUrl"]; str = cognitoUserPoolEvent.response.privateChallengeParameters!["answer"]; strOrUndefined = cognitoUserPoolEvent.response.challengeMetadata; boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; +str = cognitoUserPoolEvent.response.userAttributes!["username"]; +cognitoUserPoolEvent.response.finalUserStatus === "CONFIRMED"; +cognitoUserPoolEvent.response.finalUserStatus === "RESET_REQUIRED"; +cognitoUserPoolEvent.response.messageAction === "SUPPRESS"; +cognitoUserPoolEvent.response.desiredDeliveryMediums === ["EMAIL"]; +cognitoUserPoolEvent.response.desiredDeliveryMediums === ["SMS"]; +cognitoUserPoolEvent.response.desiredDeliveryMediums === ["SMS", "EMAIL"]; +boolOrUndefined = cognitoUserPoolEvent.response.forceAliasCreation; // CloudFormation Custom Resource switch (cloudformationCustomResourceEvent.RequestType) { diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index cce721e68c..d9d22f8c65 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -22,6 +22,8 @@ // Louis Larry // Daniel Papukchiev // Oliver Hookins +// Trevor Leach +// James Gregory // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -58,11 +60,13 @@ export interface APIGatewayEventRequestContext { export interface APIGatewayProxyEvent { body: string | null; headers: { [name: string]: string }; + multiValueHeaders: { [name: string]: string[] }; httpMethod: string; isBase64Encoded: boolean; path: string; pathParameters: { [name: string]: string } | null; queryStringParameters: { [name: string]: string } | null; + multiValueQueryStringParameters: { [name: string]: string[] } | null; stageVariables: { [name: string]: string } | null; requestContext: APIGatewayEventRequestContext; resource: string; @@ -75,8 +79,10 @@ export interface CustomAuthorizerEvent { methodArn: string; authorizationToken?: string; headers?: { [name: string]: string }; + multiValueHeaders?: { [name: string]: string[] }; pathParameters?: { [name: string]: string } | null; queryStringParameters?: { [name: string]: string } | null; + multiValueQueryStringParameters?: { [name: string]: string[] } | null; requestContext?: APIGatewayEventRequestContext; } @@ -234,7 +240,9 @@ export interface CognitoUserPoolTriggerEvent { | "TokenGeneration_Authentication" | "TokenGeneration_NewPasswordChallenge" | "TokenGeneration_AuthenticateDevice" - | "TokenGeneration_RefreshTokens"; + | "TokenGeneration_RefreshTokens" + | "UserMigration_Authentication" + | "UserMigration_ForgotPassword"; region: string; userPoolId: string; userName?: string; @@ -256,6 +264,7 @@ export interface CognitoUserPoolTriggerEvent { challengeName?: string; privateChallengeParameters?: { [key: string]: string }; challengeAnswer?: string; + password?: string; }; response: { autoConfirmUser?: boolean; @@ -269,6 +278,11 @@ export interface CognitoUserPoolTriggerEvent { privateChallengeParameters?: { [key: string]: string }; challengeMetadata?: string; answerCorrect?: boolean; + userAttributes?: { [key: string]: string }; + finalUserStatus?: "CONFIRMED" | "RESET_REQUIRED"; + messageAction?: "SUPPRESS"; + desiredDeliveryMediums?: Array<"EMAIL" | "SMS">; + forceAliasCreation?: boolean; }; } export type CognitoUserPoolEvent = CognitoUserPoolTriggerEvent; @@ -433,6 +447,9 @@ export interface APIGatewayProxyResult { headers?: { [header: string]: boolean | number | string; }; + multiValueHeaders?: { + [header: string]: Array; + }; body: string; isBase64Encoded?: boolean; } diff --git a/types/better-scroll/index.d.ts b/types/better-scroll/index.d.ts index 326dd2c3a0..91e5710805 100644 --- a/types/better-scroll/index.d.ts +++ b/types/better-scroll/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for better-scroll 1.12 // Project: https://github.com/ustbhuangyi/better-scroll // Definitions by: cloudstone +// jack // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -42,6 +43,24 @@ export interface PullUpOption { threshold: number; } +export interface MouseWheelOption { + speed: number; + invert: boolean; + easeTime: number; +} + +export interface ZoomOption { + start: number; + min: number; + max: number; +} + +export interface InfinityOption { + fetch: (count: number) => void; + render: (item: any, div: Element) => Element; + createTombstone: () => Element; +} + export interface BounceObjectOption { top?: boolean; bottom?: boolean; @@ -49,6 +68,10 @@ export interface BounceObjectOption { right?: boolean; } +export interface DoubleClick { + delay: number; +} + export interface EaseOption { swipe?: { style: string; @@ -73,6 +96,7 @@ export interface BsOption { directionLockThreshold: number; eventPassthrough: string | boolean; click: boolean; + dblclick: boolean | DoubleClick; tap: boolean; bounce: boolean | BounceObjectOption; bounceTime: number; @@ -140,6 +164,23 @@ export interface BsOption { * } */ pullUpLoad: Partial | boolean; + + // mouseWheel: { + // speed: 20, + // invert: false, + // easeTime: 300 + // } + mouseWheel: Partial | boolean; + + // zoom: { + // start: 1, + // min: 1, + // max: 4 + // } + zoom: Partial | boolean; + + // https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/options-advanced.html + infinity: Partial | boolean; } export interface Position { diff --git a/types/bn.js/index.d.ts b/types/bn.js/index.d.ts index 8c0bc8dd5f..db4c9f8b9e 100644 --- a/types/bn.js/index.d.ts +++ b/types/bn.js/index.d.ts @@ -45,7 +45,7 @@ interface ReductionContext { declare class BN { constructor( number: number | string | number[] | Buffer | BN, - base?: number, + base?: number | 'hex', endian?: Endianness ); constructor( diff --git a/types/bootstrap-toggle/bootstrap-toggle-tests.ts b/types/bootstrap-toggle/bootstrap-toggle-tests.ts new file mode 100644 index 0000000000..764415a048 --- /dev/null +++ b/types/bootstrap-toggle/bootstrap-toggle-tests.ts @@ -0,0 +1,38 @@ +import 'bootstrap-toggle'; + +const $elem = $("#toggle"); + +// Test Initialise Cases +$elem.bootstrapToggle(); + +$elem.bootstrapToggle({}); + +$elem.bootstrapToggle({ + // Defaults from source project + on: 'On', + off: 'Off', + onstyle: 'primary', + offstyle: 'default', + size: 'normal', + style: '', + width: null, + height: null +}); + +$elem.bootstrapToggle({ + width: 100, + height: 100 +}); + +$elem.bootstrapToggle({ + width: "100%", + height: "100%" +}); + +// Methods +$elem.bootstrapToggle("destroy"); +$elem.bootstrapToggle("on"); +$elem.bootstrapToggle("off"); +$elem.bootstrapToggle("toggle"); +$elem.bootstrapToggle("enable"); +$elem.bootstrapToggle("disable"); diff --git a/types/bootstrap-toggle/index.d.ts b/types/bootstrap-toggle/index.d.ts new file mode 100644 index 0000000000..51dcec9446 --- /dev/null +++ b/types/bootstrap-toggle/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for bootstrap-toggle 2.2 +// Project: https://github.com/minhur/bootstrap-toggle +// Definitions by: Mitchell Grice +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +interface BootstrapToggleOptions { + on?: string; + off?: string; + size?: string; + onstyle?: string; + offstyle?: string; + style?: string; + width?: number | string | null; + height?: number | string | null; +} + +interface JQuery { + bootstrapToggle(options?: BootstrapToggleOptions): JQuery; + bootstrapToggle(command: "destroy" | "on" | "off" | "toggle" | "enable" | "disable"): JQuery; +} diff --git a/types/bootstrap-toggle/tsconfig.json b/types/bootstrap-toggle/tsconfig.json new file mode 100644 index 0000000000..b3d28afbde --- /dev/null +++ b/types/bootstrap-toggle/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", + "bootstrap-toggle-tests.ts" + ] +} diff --git a/types/react-i18next/v4/tslint.json b/types/bootstrap-toggle/tslint.json similarity index 100% rename from types/react-i18next/v4/tslint.json rename to types/bootstrap-toggle/tslint.json diff --git a/types/caniuse-api/caniuse-api-tests.ts b/types/caniuse-api/caniuse-api-tests.ts new file mode 100644 index 0000000000..46b6a1eec4 --- /dev/null +++ b/types/caniuse-api/caniuse-api-tests.ts @@ -0,0 +1,17 @@ +import * as caniuse from "caniuse-api"; + +caniuse.features; // $ExpectType string[] + +caniuse.getSupport(""); // $ExpectType BrowserSupport + +caniuse.isSupported("", ""); // $ExpectType boolean +caniuse.isSupported("", [""]); // $ExpectType boolean + +caniuse.find(""); // $ExpectType string[] + +caniuse.getLatestStableBrowsers(); // $ExpectType string[] + +caniuse.setBrowserScope(""); // $ExpectType void +caniuse.setBrowserScope([""]); // $ExpectType void + +caniuse.getBrowserScope(); // $ExpectType string[] diff --git a/types/caniuse-api/index.d.ts b/types/caniuse-api/index.d.ts new file mode 100644 index 0000000000..ce6dac23ec --- /dev/null +++ b/types/caniuse-api/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for caniuse-api 3.0 +// Project: https://github.com/nyalab/caniuse-api#readme +// Definitions by: Dave Cardwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const features: string[]; + +export interface BrowserSupport { + [browser: string]: { + y?: number; + n?: number; + a?: number; + x?: number; + }; +} + +export function getSupport(feature: string): BrowserSupport; + +export function isSupported( + feature: string, + browsers: string | ReadonlyArray +): boolean; + +export function find(query: string): string[]; + +export function getLatestStableBrowsers(): string[]; + +export function setBrowserScope( + browserscope: string | ReadonlyArray +): void; + +export function getBrowserScope(): string[]; diff --git a/types/caniuse-api/tsconfig.json b/types/caniuse-api/tsconfig.json new file mode 100644 index 0000000000..2e43754f9e --- /dev/null +++ b/types/caniuse-api/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "caniuse-api-tests.ts"] +} diff --git a/types/caniuse-api/tslint.json b/types/caniuse-api/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/caniuse-api/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index ae8a71766e..36002d9bfa 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -808,6 +808,24 @@ function frozen() { expect(Object.freeze({})).to.be.frozen; ({}).should.be.not.frozen; Object.freeze({}).should.be.frozen; + + expect([1, 2, 3]).to.have.all.members([1, 2, 3]); + expect([1, 2, 3]).to.have.all.members(Object.freeze([1, 2, 3])); + + expect({1: "", 2: "", 3: ""}).to.have.all.keys([1, 2, 3]); + expect({1: "", 2: "", 3: ""}).to.have.all.keys(Object.freeze([1, 2, 3])); + + assert.notDeepInclude([1, 2, 3], 1); + assert.notDeepInclude(Object.freeze([1, 2, 3]), 1); + + assert.include([1, 2, 3], 1); + assert.include(Object.freeze([1, 2, 3]), 1); + + assert.notInclude([1, 2, 3], 1); + assert.notInclude(Object.freeze([1, 2, 3]), 1); + + expect([1, 2, 3]).to.have.oneOf([1, 2, 3]); + expect([1, 2, 3]).to.have.oneOf(Object.freeze([1, 2, 3])); } class PoorlyConstructedError { diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index 72ebc0191d..5f73803757 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -118,7 +118,7 @@ declare namespace Chai { extensible: Assertion; sealed: Assertion; frozen: Assertion; - oneOf(list: any[], message?: string): Assertion; + oneOf(list: ReadonlyArray, message?: string): Assertion; } interface LanguageChains { @@ -235,7 +235,7 @@ declare namespace Chai { interface Keys { (...keys: string[]): Assertion; - (keys: any[]|Object): Assertion; + (keys: ReadonlyArray|Object): Assertion; } interface Throw { @@ -252,7 +252,7 @@ declare namespace Chai { } interface Members { - (set: any[], message?: string): Assertion; + (set: ReadonlyArray, message?: string): Assertion; } interface PropertyChange { @@ -696,7 +696,7 @@ declare namespace Chai { * @param needle Potential value contained in haystack. * @param message Message to display on error. */ - include(haystack: T[], needle: T, message?: string): void; + include(haystack: ReadonlyArray, needle: T, message?: string): void; /** * Asserts that haystack does not include needle. @@ -705,7 +705,7 @@ declare namespace Chai { * @param needle Potential expected substring of haystack. * @param message Message to display on error. */ - notInclude(haystack: string | any[], needle: any, message?: string): void; + notInclude(haystack: string | ReadonlyArray, needle: any, message?: string): void; /** * Asserts that haystack includes needle. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used. @@ -732,7 +732,7 @@ declare namespace Chai { * @param needle Potential expected substring of haystack. * @param message Message to display on error. */ - notDeepInclude(haystack: string | any[], needle: any, message?: string): void; + notDeepInclude(haystack: string | ReadonlyArray, needle: any, message?: string): void; /** * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. diff --git a/types/chordsheetjs/chordsheetjs-tests.ts b/types/chordsheetjs/chordsheetjs-tests.ts new file mode 100644 index 0000000000..7f01828e7f --- /dev/null +++ b/types/chordsheetjs/chordsheetjs-tests.ts @@ -0,0 +1,5 @@ +import { Song, HtmlTableFormatter } from 'chordsheetjs'; + +const song = new Song({ key: 'value' }); +const formatter = new HtmlTableFormatter(); +formatter.format(song); diff --git a/types/chordsheetjs/index.d.ts b/types/chordsheetjs/index.d.ts new file mode 100644 index 0000000000..ee2e69593f --- /dev/null +++ b/types/chordsheetjs/index.d.ts @@ -0,0 +1,372 @@ +// Type definitions for chordsheetjs 2.8 +// Project: https://github.com/martijnversluis/ChordSheetJS +// Definitions by: Adam Bloom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Represents a chord with the corresponding (partial) lyrics + */ +export class ChordLyricsPair { + /** + * Initialises a ChordLyricsPair + * @param chords The chords + * @param lyrics The lyrics + */ + constructor(chords: string, lyrics: string); + + chords: string; + lyrics: string; + + /** + * Indicates whether a ChordLyricsPair should be visible in a formatted chord sheet (except for ChordPro sheets) + */ + isRenderable: () => boolean; + + /** + * Returns a deep copy of the ChordLyricsPair, useful when programmatically transforming a song + */ + clone: () => ChordLyricsPair; + + toString: () => string; +} + +/** + * Represents a tag/directive. See https://www.chordpro.org/chordpro/ChordPro-Directives.html + */ +export class Tag { + constructor(name: string, value: string | null); + + /** + * The tag full name. When the original tag used the short name, `name` will return the full name. + */ + name: string; + + /** + * The tag value + */ + value: string | null; + + static parse(tag: string): Tag | null; + static parseWithRegex(tag: string, regex: string): Tag | null; + + /** + * The original tag name that was used to construct the tag. + */ + originalName: string; + + /** + * Checks whether the tag value is a non-empty string. + */ + hasValue(): boolean; + + /** + * Checks whether the tag is usually rendered inline. It currently only applies to comment tags. + */ + isRenderable(): boolean; + + /** + * Checks whether the tag is either a standard meta tag or a custom meta directive (`{x_some_name}`) + */ + isMetaTag(): boolean; + + /** + * Returns a clone of the tag. + */ + clone(): Tag; + + toString(): string; +} + +/** + * Represents a line in a chord sheet, consisting of items of type ChordLyricsPair or Tag + */ +export class Line { + constructor(); + + /** + * The items (ChordLyricsPair or Tag) of which the line consists + */ + items: Array; + + /** + * The line type, This is set by the ChordProParser when it read tags like {start_of_chorus} or {start_of_verse} + * Values can be 'verse', 'chorus' or 'none' + */ + type: 'verse' | 'chorus' | 'none'; + + /** + * Indicates whether the line contains any items + */ + isEmpty(): boolean; + + /** + * Adds an item to the line + * @param item The item to be added + */ + addItem(item: ChordLyricsPair | Tag): void; + + /** + * Indicates whether the line contains items that are renderable + */ + hasRenderableItems(): boolean; + + /** + * Returns a deep copy of the line and all of its items + */ + clone(): Line; + + /** + * Indicates whether the line type is 'verse' + */ + isVerse(): boolean; + + /** + * Indicates whether the line type is 'chorus' + */ + isChorus(): boolean; + + /** + * Indicates whether the line contains items that are renderable. Please use hasRenderableItems + * @deprecated + */ + hasContent(): boolean; + + addChordLyricsPair( + chords: ChordLyricsPair | string, + lyrics: string + ): ChordLyricsPair; + ensureChordLyricsPair(): void; + chords(chr: string): void; + lyrics(chr: string): void; + addTag(name: Tag | string, value: string | null): Tag; +} + +/** + * Represents a paragraph of lines in a chord sheet + */ +export class Paragraph { + constructor(); + + /** + * The Line items of which the paragraph consists + */ + lines: Line[]; + + addLine(line: Line): void; + + /** + * Tries to determine the common type for all lines. If the types for all lines are equal, it returns that type. + * If not, it returns 'indeterminate'. + */ + type: string; +} + +/** + * Represents a song in a chord sheet. Currently a chord sheet can only have one song. + */ +export class Song { + constructor(metadata: object); + + /** + * The Line items of which the song consists + */ + lines: Line[]; + + /** + * The Paragraph items of which the song consists + */ + paragraphs: Paragraph[]; + + currentLine: Line; + currentParagraph: Paragraph; + assignMetaData(metadata: object): void; + + /** + * Returns the song lines, skipping the leading empty lines (empty as in not rendering any content). This is useful + * if you want to skip the "header lines": the lines that only contain meta data. + */ + bodyLines: Line[]; + + chords(chr: string): void; + lyrics(chr: string): void; + addLine(): Line; + setCurrentLineType(type: string): void; + flushLine(): void; + finish(): void; + addChordLyricsPair(): ChordLyricsPair; + ensureLine(): void; + addParagraph(): Paragraph; + ensureParagraph(): void; + addTag(tagContents: string): Tag; + + /** + * Returns a deep clone of the song + */ + clone(): Song; + + setMetaData(name: string, value: string): void; + metaData: object; + optimizedMetaData: object; + getOptimizedMetaData(): object; + optimizeMetaDataValue( + valueSet: string[] | undefined + ): string | string[] | null; + getMetaData(name: string): string | null; +} + +/** + * Represents a parser warning, currently only used by ChordProParser. + */ +export class ParserWarning { + /** + * The warning message + */ + message: string; + + /** + * The line number on which the warning occurred + */ + lineNumber: string; + + toString(): string; +} + +/** + * Parses a ChordPro chord sheet + */ +export class ChordProParser { + /** + * Parses a ChordPro chord sheet into a song + * @param chordProChordSheet The ChordPro chord sheet + */ + parse(chordProChordSheet: string): Song; + + song: Song; + lineNumber: number; + sectionType: string; + warnings: ParserWarning[]; + + parseDocument(document: string): void; + readLyrics(chr: string): void; + readChords(chr: string): void; + readTag(chr: string): void; + readComment(chr: string): void; + finishTag(): void; + resetTag(): void; + applyTag(tag: Tag): void; + startSection(sectionType: string, tag: Tag): void; + endSection(sectionType: string, tag: Tag): void; + checkCurrentSectionType(sectionType: string, tag: Tag): void; + addWarning(message: string): void; +} + +export interface ChordSheetParserProps { + preserveWhitespace: boolean; +} + +/** + * Formats a song into a plain text chord sheet + */ +export class ChordSheetParser { + constructor(props: ChordSheetParserProps); + + song: Song; + lines: Line[]; + songLine: Line; + chordLyricsPair: ChordLyricsPair; + currentLine: number; + lineCount: number; + processingText: string; + preserveWhitespace: boolean; + + /** + * Parses a chord sheet into a song + * @param chordSheet The ChordPro chord sheet + */ + parse(chordSheet: string): Song; + + parseLine(line: string): void; + parseNonEmptyLine(line: string): void; + initialize(document: string): void; + readLine(): Line; + hasNextLine(): boolean; + parseLyricsWithChords(chordsLine: string, lyricsLine: string): void; + processCharacters(chordsLine: string, lyricsLine: string): void; + addCharacter(chr: string, nextChar: string): void; + shouldAddCharacterToChords(nextChar: string): boolean; + ensureChordLyricsPairInitialized(): void; +} + +export interface SongHeader { + title: string; + subtitle: string; +} + +export class TextFormatter { + constructor(); + /** + * Formats a song into a plain text chord sheet + * @param song The song to be formatted + */ + format(song: Song): string; + formatHeader(header: SongHeader): string; + formatParagraphs(song: Song): string; + formatParagraph(paragraph: Paragraph): string; + formatLine(line: Line): string; + formatTitle(title: string): string; + formatSubtitle(subtitle: string): string; + formatTopLine(line: Line): string | null; + chordLyricsPairLength(chordLyricsPair: ChordLyricsPair): number; + formatItemTop(item: Tag | ChordLyricsPair | Line): string; + formatLineBottom(line: Line): string; + formatLineWithFormatter( + line: Line, + formatter: (x: string) => string + ): string; + formatItemBottom(item: Tag | ChordLyricsPair | Line): string; +} + +/** + * Formats a song into HTML. It uses TABLEs to align lyrics with chords, which makes the HTML for things like + * PDF conversion. + */ +export class HtmlTableFormatter { + constructor(); + /** + * Formats a song into HTML. + * @param song The song to be formatted + */ + format(song: Song): string; +} + +/** + * Formats a song into HTML. It uses DIVs to align lyrics with chords, which makes it useful for responsive web pages. + */ +export class HtmlDivFormatter { + constructor(); + /** + * Formats a song into HTML. + * @param song The song to be formatted + */ + format(song: Song): string; +} + +/** + * Formats a song into a ChordPro chord sheet + */ +export class ChordProFormatter { + constructor(); + /** + * Formats a song into a ChordPro chord sheet. + * @param song The song to be formatted + */ + format(song: Song): string; + + formatLine(line: Line): string; + formatItem(item: Tag | ChordLyricsPair | Line): string; + formatTag(tag: Tag): string; + formatChordLyricsPair(chordLyricsPair: ChordLyricsPair): string; + formatChordLyricsPairChords(chordLyricsPair: ChordLyricsPair): string; + formatChordLyricsPairLyrics(chordLyricsPair: ChordLyricsPair): string; +} diff --git a/types/chordsheetjs/tsconfig.json b/types/chordsheetjs/tsconfig.json new file mode 100644 index 0000000000..0b2e8140ca --- /dev/null +++ b/types/chordsheetjs/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "chordsheetjs-tests.ts"] +} diff --git a/types/chordsheetjs/tslint.json b/types/chordsheetjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chordsheetjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 33b760ce82..567b73f2bb 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -612,7 +612,10 @@ declare namespace chrome { * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ maxHeight?: integer; - /** Type of window to create */ + /** + * @deprecated Deprecated since Chrome 69. All app windows use the 'shell' window type. + * @description Type of window to create + **/ type?: 'shell'; /** * If true, the window will have its own shelf icon. @@ -919,7 +922,8 @@ declare namespace chrome { level?: integer; } /** - * Device properties by which to filter the list of returned audio devices. If the filter is not set or set to {}, returned device list will contain all available audio devices. + * Device properties by which to filter the list of returned audio devices. + * If the filter is not set or set to {}, returned device list will contain all available audio devices. */ interface Filter { /** @@ -1083,8 +1087,9 @@ declare namespace chrome { function getDevices(callback: (devices: Device[]) => void): void; /** - * Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. - * @param filter Since Chrome 67. Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. + * @since Chrome 67. + * @description Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. + * @param filter Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. * @param callback Called when the search is completed. */ function getDevices(filter: DeviceFilter, callback: (devices: Device[]) => void): void; @@ -2082,12 +2087,12 @@ declare namespace chrome { /** * **Dev channel only.** * Sets image data to clipboard - * @param imageData The encoded image data. *Since Chrome 70. Warning: this is the current Beta channel.* - * @param type The type of image being passed. *Since Chrome 70. Warning: this is the current Beta channel.* + * @param imageData The encoded image data. *Since Chrome 71. Warning: this is the current Dev channel.* + * @param type The type of image being passed. *Since Chrome 71. Warning: this is the current Dev channel.* * @param [additionalItems] Additional data items for describing image data. * The callback is called with chrome.runtime.lastError set to error code if there is an error. * Requires clipboard and clipboardWrite permissions. - * *Since Chrome 70. Warning: this is the current Beta channel.* + * *Since Chrome 71. Warning: this is the current Dev channel.* * @param [callback] */ function setImageData(imageData: ArrayBuffer, type: ImageType, additionalItems?: AdditionalItems, callback?: () => void): void; @@ -3078,7 +3083,8 @@ declare namespace chrome { 'document_end' | 'document_idle'; /** - * The origin of injected CSS. + * @since Chrome 66. + * @description The origin of injected CSS. **/ type CSSOrigin = 'author' | @@ -5968,6 +5974,11 @@ declare namespace chrome { SSID?: S; /** The network signal strength. */ SignalStrength?: integer; + /** + * @since Chrome 70 + * @description The tethering state associated with the connection. + */ + TetheringState?: string; } interface WiFiProperties void>; /** - * The user clicked on a link for the app's notification settings. - * @since Chrome 32. + * @deprecated Deprecated since Chrome 65. Custom notification settings button is no longer supported. + * @description The user clicked on a link for the app's notification settings. + * As of Chrome 47, only ChromeOS has UI that dispatches this event. + * As of Chrome 65, that UI has been removed from ChromeOS, too. */ const onShowSettings: chrome.events.Event<() => void>; @@ -9319,7 +9339,10 @@ declare namespace chrome { /** The display mode height in native pixels. */ heightInNativePixels: integer; - /** The display mode UI scale factor. */ + /** + * @deprecated Deprecated since Chrome 70. Use `displayZoomFactor` + * @description The display mode UI scale factor. + **/ uiScale: integer; /** The display mode device scale factor. */ @@ -9380,15 +9403,16 @@ declare namespace chrome { * If set to true, changes the display mode to unified desktop. * If set to false, unified desktop mode will be disabled. * This is only valid for the primary display. - * If provided, mirroringSourceId must not be provided and other properties may not apply. This is has no effect if not provided. - * @see(See enableUnifiedDesktop for details). + * If provided, mirroringSourceId must not be provided and other properties may not apply. + * This is has no effect if not provided. + * @see(See `enableUnifiedDesktop` for details). * @since Chrome 59 * */ isUnified?: boolean; /** * @requires(CrOS) Chrome OS only. - * @deprecated Deprecated since Chrome 68. Use *setMirrorMode* + * @deprecated Deprecated since Chrome 68. Use ´setMirrorMode´ * @see setMirrorMode * @description * If set and not empty, enables mirroring for this display. @@ -9416,7 +9440,7 @@ declare namespace chrome { * If set, updates the display's rotation. * Legal values are [0, 90, 180, 270]. * The rotation is set clockwise, relative to the display's vertical position. - * It's applied after overscan paramter. + * It's applied after overscan parameter. */ rotation?: 0 | 90 | 180 | 270; @@ -9912,10 +9936,10 @@ declare namespace chrome { /** The language that this voice supports, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ lang?: string; /** - * This voice's gender. - * One of: 'male', or 'female' + * @deprecated Deprecated since Chrome 70. Gender is deprecated and will be ignored. + * @description This voice's gender. */ - gender?: string; + gender?: 'male' | 'female'; /** The name of the voice. */ voiceName?: string; /** The ID of the extension providing this voice. */ @@ -9959,10 +9983,10 @@ declare namespace chrome { /** The extension ID of the speech engine to use, if known. */ extensionId?: string; /** - * Gender of voice for synthesized speech. - * One of: 'male', or 'female' + * @deprecated Deprecated since Chrome 70. Gender is deprecated and will be ignored. + * @description Gender of voice for synthesized speech. */ - gender?: string; + gender?: 'male' | 'female'; /** The TTS event types the voice must support. */ requiredEventTypes?: string[]; /** The TTS event types that you are interested in listening to. If missing, all event types may be sent. */ @@ -10983,7 +11007,7 @@ declare namespace chrome { */ class RequestMatcher { protected readonly typeGuard: 'RequestMatcher'; - constructor (parameters?: RequestMatcherFields); + constructor(parameters?: RequestMatcherFields); public readonly instanceType: string; } @@ -11001,7 +11025,7 @@ declare namespace chrome { /** Declarative event action that redirects a network request. */ class RedirectRequest { protected readonly typeGuard: 'RedirectRequest'; - constructor (parameters: RedirectRequestParams); + constructor(parameters: RedirectRequestParams); public readonly instanceType: string; } @@ -11036,7 +11060,7 @@ declare namespace chrome { */ class RedirectByRegEx { protected readonly typeGuard: 'RedirectByRegEx'; - constructor (parameters: RedirectByRegExParams); + constructor(parameters: RedirectByRegExParams); public readonly instanceType: string; } @@ -11055,7 +11079,7 @@ declare namespace chrome { */ class SetRequestHeader { protected readonly typeGuard: 'SetRequestHeader'; - constructor (parameters: SetRequestHeaderParams); + constructor(parameters: SetRequestHeaderParams); public readonly instanceType: string; } @@ -11072,7 +11096,7 @@ declare namespace chrome { */ class RemoveRequestHeader { protected readonly typeGuard: 'RemoveRequestHeader'; - constructor (parameters: RemoveRequestHeaderParams); + constructor(parameters: RemoveRequestHeaderParams); public readonly instanceType: string; } @@ -11091,7 +11115,7 @@ declare namespace chrome { */ class AddResponseHeader { protected readonly typeGuard: 'AddResponseHeader'; - constructor (parameters: AddResponseHeaderParams); + constructor(parameters: AddResponseHeaderParams); public readonly instanceType: string; } @@ -11107,7 +11131,7 @@ declare namespace chrome { */ class RemoveResponseHeader { protected readonly typeGuard: 'RemoveResponseHeader'; - constructor (parameters: RemoveResponseHeaderParams); + constructor(parameters: RemoveResponseHeaderParams); public readonly instanceType: string; } @@ -11133,7 +11157,7 @@ declare namespace chrome { */ class IgnoreRules { protected readonly typeGuard: 'IgnoreRules'; - constructor (parameters: IgnoreRulesParams); + constructor(parameters: IgnoreRulesParams); public readonly instanceType: string; } @@ -11150,7 +11174,7 @@ declare namespace chrome { */ class SendMessageToExtension { protected readonly typeGuard: 'SendMessageToExtension'; - constructor (parameters: SendMessageParams); + constructor(parameters: SendMessageParams); public readonly instanceType: string; } @@ -11248,7 +11272,7 @@ declare namespace chrome { */ class AddRequestCookie { protected readonly typeGuard: 'AddRequestCookie'; - constructor (parameters: AddCookie); + constructor(parameters: AddCookie); public readonly instanceType: string; } @@ -11259,7 +11283,7 @@ declare namespace chrome { */ class AddResponseCookie { protected readonly typeGuard: 'AddResponseCookie'; - constructor (parameters: AddCookie); + constructor(parameters: AddCookie); public readonly instanceType: string; } @@ -11292,7 +11316,7 @@ declare namespace chrome { * @param modification Attributes that shall be overridden in cookies that machted the filter. * Attributes that are set to an empty string are removed. */ - constructor (parameters: EditCookieParams); + constructor(parameters: EditCookieParams); public readonly instanceType: string; } @@ -11306,7 +11330,7 @@ declare namespace chrome { * @param filter Filter for cookies that will be modified.All empty entries are ignored. * @param modification */ - constructor (parameter: EditCookieParams); + constructor(parameter: EditCookieParams); public readonly instanceType: string; } @@ -11316,7 +11340,7 @@ declare namespace chrome { */ class RemoveRequestCookie { protected readonly typeGuard: 'RemoveRequestCookie'; - constructor (parameters: RemoveCookieParams); + constructor(parameters: RemoveCookieParams); public readonly instanceType: string; } @@ -11340,7 +11364,7 @@ declare namespace chrome { */ class RemoveResponseCookie { protected readonly typeGuard: 'RemoveResponseCookie'; - constructor (parameters: RemoveCookieParams); + constructor(parameters: RemoveCookieParams); public readonly instanceType: string; } @@ -11518,7 +11542,7 @@ declare namespace chrome { */ declare class HTMLAppViewElement extends HTMLElement { /** Create a new AppView tag */ - constructor (); + constructor(); /** * Requests another app to be embedded. * @param app The extension id of the app to be embedded. @@ -11626,7 +11650,7 @@ declare class HTMLWebViewElement extends HTMLElement { src: string; /** Create a new element */ - constructor (); + constructor(); /** * Queries audio state. @@ -11908,6 +11932,21 @@ declare class HTMLWebViewElement extends HTMLElement { */ loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; + /** + * @since Chrome 71 + * @description Sets spatial navigation state of the webview. + * @param enabled Spatial navigation state value. + */ + setSpatialNavigationEnabled(enabled: boolean): void; + + /** + * @since Chrome 71 + * @description Queries whether spatial navigation is enabled for the webview. + * @param callback Callback that will provide the value of the spatial navigation state. + */ + isSpatialNavigationEnabled(callback: (enabled: boolean) => void): void; + + /** * Forcibly kills the guest web page's renderer process. * This may affect multiple webview tags in the current app if they share the same process, diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 93864d107b..499a34bab1 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1114,6 +1114,7 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { if (networkObj.WiFi) { // WiFi active :) console.log('Wifi BSID: ' + networkObj.WiFi.BSSID); + const state = networkObj.WiFi.TetheringState; } chrome.networking.onc.setProperties(networkObj.GUID || '', { WiFi: { @@ -1124,6 +1125,19 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { chrome.networking.onc.getProperties(networkObj.GUID || '', (props) => { const WiFiResult = props.WiFi; }); + chrome.networking.onc.getState(networkObj.GUID || '', (state) => { + const wifiState = state.WiFi || {}; + return wifiState.TetheringState; + }); + chrome.networking.onc.getManagedProperties(networkObj.GUID || '', (result) => { + const wifiResult = result.WiFi; + if (wifiResult !== undefined) { + const managed = wifiResult.HexSSID; + if (managed !== undefined) { + return managed.UserPolicy; + } + } + }); } }); diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 49f079e159..ba074550f8 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -4525,12 +4525,12 @@ declare namespace chrome.pageAction { * Shows the page action. The page action is shown whenever the tab is selected. * @param tabId The id of the tab for which you want to modify the page action. */ - export function hide(tabId: number): void; + export function hide(tabId: number, callback?: () => void): void; /** * Shows the page action. The page action is shown whenever the tab is selected. * @param tabId The id of the tab for which you want to modify the page action. */ - export function show(tabId: number): void; + export function show(tabId: number, callback?: () => void): void; /** Sets the title of the page action. This is displayed in a tooltip over the page action. */ export function setTitle(details: TitleDetails): void; /** Sets the html document to be opened as a popup when the user clicks on the page action's icon. */ diff --git a/types/cli-table2/cli-table2-tests.ts b/types/cli-table2/cli-table2-tests.ts index dfaed4ec33..97d8c82dbe 100644 --- a/types/cli-table2/cli-table2-tests.ts +++ b/types/cli-table2/cli-table2-tests.ts @@ -230,3 +230,24 @@ table26.push( // feel free to use colors in your content strings, column widths will be calculated correctly const table27 = new Table({ colWidths: [5], style: { head: [], border: [] } }) as Table.HorizontalTable; table27.push([/*colors.red(*/'hello'/*)*/]); + +// Header as text +const table28 = new Table({ head: ["Top Header 1", "Top Header 2"] }) as Table.HorizontalTable; +table28.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2'] +); + +// Header as Cells +const table29 = new Table({ head: [{content: "Top Header 1"}, {content: "Top Header 2"}] }) as Table.HorizontalTable; +table29.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2'] +); + +// ColSpan in header +const table30 = new Table({ head: [{content: "Top Header 1", colSpan: 2}, {content: "Top Header 3"}] }) as Table.HorizontalTable; +table30.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2', 'Value Row 1 Col 3'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2', 'Value Row 2 Col 3'] +); diff --git a/types/cli-table2/index.d.ts b/types/cli-table2/index.d.ts index b216b23832..865439f000 100644 --- a/types/cli-table2/index.d.ts +++ b/types/cli-table2/index.d.ts @@ -31,7 +31,7 @@ declare namespace CliTable2 { rowHeights: Array; colAligns: HorizontalAlignment[]; rowAligns: VerticalAlignment[]; - head: string[]; + head: Cell[]; wordWrap: boolean; } 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/commangular/commangular-mock.d.ts b/types/commangular/commangular-mock.d.ts index 134e4d0d1e..a31563bc9e 100644 --- a/types/commangular/commangular-mock.d.ts +++ b/types/commangular/commangular-mock.d.ts @@ -4,33 +4,33 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module commangular { - + /////////////////////////////////////////////////////////////////////////// // Commangular Static // see http://commangular.org/docs/#commangular-namespace /////////////////////////////////////////////////////////////////////////// interface ICommAngularStatic { - + /** * Mock dispatch function for testing commands. */ dispatch( ec: ICommandCall, callback: Function ): void; } - + interface ICommandCall { /** * Name of the command that needs to * execute */ command: string; - + /** * Data that needs to be passed to the command */ data?: any; } - - + + /** * Object type expected to be passed into the callback function * of the dispatch() function @@ -41,25 +41,25 @@ declare module commangular { * @param key The property name that is in the object that was passed */ dataPassed( key : string ) : any; - + /** * The data that was returned by the command * @param key The result key that was defined in the command. If no result * was defined use 'lastResult' as the key */ resultKey( key: string ): any; - + /** * Indicates if the command execution was cancelled. */ canceled( ): boolean; - + /** * Indicates if the command was executed???? */ commandExecuted( ): boolean; } - + } @@ -67,7 +67,6 @@ declare module commangular { * Mock dispatch function for testing commands. * @param ec an ICommandCall object * @param callback The function that will be called upon the completion of the command -* function should expecte an ICommandInfo paramter. +* function should expecte an ICommandInfo parameter. */ -declare function dispatch( ec: commangular.ICommandCall, callback: Function ): void; - +declare function dispatch( ec: commangular.ICommandCall, callback: Function ): void; diff --git a/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx new file mode 100644 index 0000000000..bceab689e7 --- /dev/null +++ b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx @@ -0,0 +1,30 @@ +import React = require('react'); +import enzyme = require('enzyme'); +import configureExtensions = require('@commercetools/enzyme-extensions'); + +configureExtensions(enzyme.ShallowWrapper); + +function App() { + return 'Hello world'} />; +} + +interface ChildProps { + cb: () => string; +} + +function Child(props: ChildProps) { + return
{props.cb()}
; +} + +enzyme.shallow() + .find(App) + .renderProp('render'); +enzyme.shallow() + .find(Child) + .renderProp('render', 1, 2); + +enzyme.shallow() + .find(Child) + .drill(props => props.cb()); + +enzyme.shallow().until(Child); diff --git a/types/commercetools__enzyme-extensions/index.d.ts b/types/commercetools__enzyme-extensions/index.d.ts new file mode 100644 index 0000000000..7c009f8e95 --- /dev/null +++ b/types/commercetools__enzyme-extensions/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for @commercetools/enzyme-extensions 3.0 +// Project: https://github.com/commercetools/enzyme-extensions +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as enzyme from 'enzyme'; + +declare module 'enzyme' { + interface UntilOptions { + maxDepth: number; + } + interface ShallowWrapper

{ + renderProp(propName: string, ...args: any[]): ShallowWrapper

; + drill(expander: (props: any) => ShallowWrapper): ShallowWrapper

; + until(selector: EnzymeSelector, options?: UntilOptions): ShallowWrapper

; + } +} + +declare function monkeyPatchShallowWrapper(s: typeof enzyme.ShallowWrapper): void; + +export = monkeyPatchShallowWrapper; diff --git a/types/react-i18next/tsconfig.json b/types/commercetools__enzyme-extensions/tsconfig.json similarity index 58% rename from types/react-i18next/tsconfig.json rename to types/commercetools__enzyme-extensions/tsconfig.json index f90b5c3ff0..9e6d70239e 100644 --- a/types/react-i18next/tsconfig.json +++ b/types/commercetools__enzyme-extensions/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, @@ -17,17 +16,12 @@ "noEmit": true, "forceConsistentCasingInFileNames": true, "jsx": "react", - "experimentalDecorators": true + "paths": { + "@commercetools/enzyme-extensions": ["commercetools__enzyme-extensions"] + } }, "files": [ "index.d.ts", - "test/react-i18next-tests.tsx", - "src/context.d.ts", - "src/I18n.d.ts", - "src/I18nextProvider.d.ts", - "src/interpolate.d.ts", - "src/loadNamespaces.d.ts", - "src/trans.d.ts", - "src/translate.d.ts" + "commercetools__enzyme-extensions-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/commercetools__enzyme-extensions/tslint.json b/types/commercetools__enzyme-extensions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/commercetools__enzyme-extensions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/consul/index.d.ts b/types/consul/index.d.ts index 3d344ae983..096a906c8b 100644 --- a/types/consul/index.d.ts +++ b/types/consul/index.d.ts @@ -625,6 +625,7 @@ declare namespace Consul { dc?: string; tag?: string; passing?: boolean; + near?: string; } interface StateOptions extends CommonOptions { diff --git a/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts new file mode 100644 index 0000000000..72925fe5ba --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts @@ -0,0 +1,63 @@ +let BluetoothClassicSerial: BluetoothClassicSerial = + window.BluetoothClassicSerial; + +BluetoothClassicSerial.connect( + "", + [""] +); +BluetoothClassicSerial.connect( + "", + [""], + results => {} +); +BluetoothClassicSerial.connect( + "", + [""], + results => {}, + error => {} +); +BluetoothClassicSerial.connectInsecure("", [""]); +BluetoothClassicSerial.connectInsecure("", [""], results => {}); +BluetoothClassicSerial.connectInsecure("", [""], results => {}, error => {}); +BluetoothClassicSerial.register(() => {}); +BluetoothClassicSerial.disconnect(results => {}); +BluetoothClassicSerial.disconnect(results => {}, error => {}); +BluetoothClassicSerial.write("", ""); +BluetoothClassicSerial.write("", "", results => {}); +BluetoothClassicSerial.write("", "", results => {}, error => {}); +BluetoothClassicSerial.available(""); +BluetoothClassicSerial.available("", results => {}); +BluetoothClassicSerial.available("", results => {}, error => {}); +BluetoothClassicSerial.read(""); +BluetoothClassicSerial.read("", results => {}); +BluetoothClassicSerial.read("", results => {}, error => {}); +BluetoothClassicSerial.readUntil("", ""); +BluetoothClassicSerial.readUntil("", "", results => {}); +BluetoothClassicSerial.readUntil("", "", results => {}, error => {}); +BluetoothClassicSerial.subscribe("", ""); +BluetoothClassicSerial.subscribe("", "", results => {}); +BluetoothClassicSerial.subscribe("", "", results => {}, error => {}); +BluetoothClassicSerial.unsubscribe(""); +BluetoothClassicSerial.unsubscribe("", results => {}); +BluetoothClassicSerial.unsubscribe("", results => {}, error => {}); +BluetoothClassicSerial.subscribeRawData(""); +BluetoothClassicSerial.subscribeRawData("", results => {}); +BluetoothClassicSerial.subscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.unsubscribeRawData(""); +BluetoothClassicSerial.unsubscribeRawData("", results => {}); +BluetoothClassicSerial.unsubscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.clear(""); +BluetoothClassicSerial.clear("", results => {}); +BluetoothClassicSerial.clear("", results => {}, error => {}); +BluetoothClassicSerial.list(results => {}); +BluetoothClassicSerial.list(results => {}, error => {}); +BluetoothClassicSerial.isConnected(results => {}); +BluetoothClassicSerial.isConnected(results => {}, error => {}); +BluetoothClassicSerial.isEnabled(results => {}); +BluetoothClassicSerial.isEnabled(results => {}, error => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}, error => {}); +BluetoothClassicSerial.enable(results => {}); +BluetoothClassicSerial.enable(results => {}, error => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}, error => {}); diff --git a/types/cordova-plugin-bluetoothclassic-serial/index.d.ts b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts new file mode 100644 index 0000000000..2dfe8c94ae --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for cordova-plugin-bluetoothClassic-serial 0.9 +// Project: https://github.com/soltius/BluetoothClassicSerial +// Definitions by: Wouter Roosendaal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Global object bluetoothClassicSerial. + */ +interface Window { + BluetoothClassicSerial: BluetoothClassicSerial; +} + +interface BluetoothClassicSerial { + connect: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + connectInsecure: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + register: (data_cb?: () => any) => void; + disconnect: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + write: ( + interfaceId: string, + data: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + available: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + read: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + readUntil: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribe: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribe: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + clear: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + list: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isConnected: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isEnabled: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + showBluetoothSettings: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + enable: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + discoverUnpaired: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; +} + +declare var bluetoothClassicSerial: BluetoothClassicSerial; diff --git a/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json b/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json new file mode 100644 index 0000000000..5cd12b710a --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/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", + "cordova-plugin-bluetoothclassic-serial-tests.ts" + ] +} diff --git a/types/cordova-plugin-bluetoothclassic-serial/tslint.json b/types/cordova-plugin-bluetoothclassic-serial/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/crpc/crpc-tests.ts b/types/crpc/crpc-tests.ts new file mode 100644 index 0000000000..ade069cbba --- /dev/null +++ b/types/crpc/crpc-tests.ts @@ -0,0 +1,3 @@ +import crpc from 'crpc'; + +const client = crpc('https://example.com/'); diff --git a/types/crpc/index.d.ts b/types/crpc/index.d.ts new file mode 100644 index 0000000000..8947443c42 --- /dev/null +++ b/types/crpc/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for crpc 0.2 +// Project: https://github.com/billinghamj/crpc +// Definitions by: Alexander Forbes-Reed +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +export type Client = (path: string, body: any, options?: {} | null) => Promise; + +export default function crpc(baseUrl: string, options?: {}): Client; diff --git a/types/crpc/tsconfig.json b/types/crpc/tsconfig.json new file mode 100644 index 0000000000..657ccc0d04 --- /dev/null +++ b/types/crpc/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "esModuleInterop": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "crpc-tests.ts" + ] +} diff --git a/types/crpc/tslint.json b/types/crpc/tslint.json new file mode 100644 index 0000000000..8f3d5d7eec --- /dev/null +++ b/types/crpc/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} 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/dd-trace/dd-trace-tests.ts b/types/dd-trace/dd-trace-tests.ts index 8169358155..9d6936875a 100644 --- a/types/dd-trace/dd-trace-tests.ts +++ b/types/dd-trace/dd-trace-tests.ts @@ -9,6 +9,7 @@ tracer.init({ debug: msg => {}, error: err => {}, }, + tags: { tracerEnv: 'dev'} }); function useWebFrameworkPlugin(plugin: "express" | "hapi" | "koa" | "restify") { diff --git a/types/dd-trace/index.d.ts b/types/dd-trace/index.d.ts index 90aa9afc66..311fa7675e 100644 --- a/types/dd-trace/index.d.ts +++ b/types/dd-trace/index.d.ts @@ -110,6 +110,11 @@ interface TracerOptions { debug: (message: string) => void; error: (err: Error) => void; }; + + /** + * Global tags that should be assigned to every span. + */ + tags?: { [key: string]: any }; } interface ExperimentalOptions {} diff --git a/types/deep-diff/deep-diff-tests.ts b/types/deep-diff/deep-diff-tests.ts index 42abf98ee1..6192dad9e5 100644 --- a/types/deep-diff/deep-diff-tests.ts +++ b/types/deep-diff/deep-diff-tests.ts @@ -1,9 +1,6 @@ +import { diff, observableDiff, applyChange, Diff } from 'deep-diff'; - -import _deepDiff = require('deep-diff'); -var diff = _deepDiff.diff; - -var lhs = { +let lhs = { name: 'my object', description: 'it\'s an object!', details: { @@ -13,7 +10,7 @@ var lhs = { } }; -var rhs = { +let rhs = { name: 'updated object', description: 'it\'s an object!', details: { @@ -23,17 +20,13 @@ var rhs = { } }; -var differences: deepDiff.IDiff[] = diff(lhs, rhs); +const differences: Array> = diff(lhs, rhs); console.log(differences); - // -------------------------- -var observableDiff = _deepDiff.observableDiff; -var applyChange = _deepDiff.applyChange; - -var lhs = { +lhs = { name: 'my object', description: 'it\'s an object!', details: { @@ -43,7 +36,7 @@ var lhs = { } }; -var rhs = { +rhs = { name: 'updated object', description: 'it\'s an object!', details: { @@ -53,7 +46,7 @@ var rhs = { } }; -observableDiff(lhs, rhs, function (d: deepDiff.IDiff) { +observableDiff(lhs, rhs, d => { // Apply all changes except those to the 'name' property... if (d.path.length !== 1 || d.path.join('.') !== 'name') { applyChange(lhs, rhs, d); diff --git a/types/deep-diff/index.d.ts b/types/deep-diff/index.d.ts index de17a03bc8..ac4d50b44a 100644 --- a/types/deep-diff/index.d.ts +++ b/types/deep-diff/index.d.ts @@ -1,42 +1,60 @@ -// Type definitions for deep-diff +// Type definitions for deep-diff 1.0 // Project: https://github.com/flitbit/diff/ // Definitions by: ZauberNerd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace deepDiff { - interface IDiff { - kind: string; - path: string[]; - lhs: any; - rhs: any; - index?: number; - item?: IDiff; - } - - interface IAccumulator { - push(diff: IDiff): void; - length: number; - } - - interface IPrefilter { - (path: string[], key: string): boolean; - } - - interface IDeepDiff { - diff(lhs: Object, rhs: Object, prefilter?: IPrefilter, acc?: IAccumulator): IDiff[]; - diff(): IDiff; - observableDiff(lhs: Object, rhs: Object, changes: Function, prefilter?: IPrefilter, path?: string[], key?: string, stack?: Object[]): void; - applyDiff(target: Object, source: Object, filter: Function): void; - applyChange(target: Object, source: Object, change: IDiff): void; - revertChange(target: Object, source: Object, change: IDiff): void; - isConflict(): boolean; - noConflict(): IDeepDiff; - } +export interface DiffNew { + kind: 'N'; + path?: any[]; + rhs: RHS; } -declare var DeepDiff: deepDiff.IDeepDiff; - -declare module "deep-diff" { - var diff: deepDiff.IDeepDiff; - export = diff; +export interface DiffDeleted { + kind: 'D'; + path?: any[]; + lhs: LHS; } + +export interface DiffEdit { + kind: 'E'; + path?: any[]; + lhs: LHS; + rhs: RHS; +} + +export interface DiffArray { + kind: 'A'; + path?: any[]; + index: number; + item: Diff; +} + +export type Diff = DiffNew | DiffDeleted | DiffEdit | DiffArray; + +export type PreFilterFunction = (path: any[], key: any) => boolean; +export interface PreFilterObject { + prefilter?(path: any[], key: any): boolean; + normalize?(currentPath: any, key: any, lhs: LHS, rhs: RHS): [ LHS, RHS ] | undefined; +} +export type PreFilter = PreFilterFunction | PreFilterObject; + +export interface Accumulator { + push(diff: Diff): void; + length: number; +} + +export type Observer = (diff: Diff) => void; + +export type Filter = (target: LHS, source: RHS, change: Diff) => boolean; + +export function diff(lhs: LHS, rhs: RHS, prefilter?: PreFilter): Array> | undefined; +export function diff(lhs: LHS, rhs: RHS, prefilter?: PreFilter, acc?: Accumulator): Accumulator; +export function orderIndependentDiff(lhs: LHS, rhs: RHS, prefilter?: PreFilter): Array> | undefined; +export function orderIndependentDiff(lhs: LHS, rhs: RHS, prefilter?: PreFilter, acc?: Accumulator): Accumulator; +export function observableDiff(lhs: LHS, rhs: RHS, observer?: Observer, prefilter?: PreFilter, orderIndependent?: boolean): Array>; +export function orderIndependentDeepDiff(lhs: LHS, rhs: RHS, changes: Array>, prefilter: PreFilter, path: any[], key: any, stack: any[]): void; +export function orderIndepHash(object: any): number; +export function applyDiff(target: LHS, source: RHS, filter?: Filter): void; +export function applyChange(target: LHS, source: any, change: Diff): void; +export function revertChange(target: LHS, source: any, change: Diff): void; diff --git a/types/deep-diff/tslint.json b/types/deep-diff/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/deep-diff/tslint.json +++ b/types/deep-diff/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/detective/detective-tests.ts b/types/detective/detective-tests.ts new file mode 100644 index 0000000000..b0c176af03 --- /dev/null +++ b/types/detective/detective-tests.ts @@ -0,0 +1,16 @@ +import detective = require("detective"); + +const opts: detective.Options = { + parse: { + sourceType: "module", + allowImportExportEverywhere: true + } +}; + +detective("content", opts).filter((x) => x && x.length > 0); + +const detectiveFunc: detective.Detective = detective; + +detectiveFunc.find("str").strings.forEach((dep) => { + const b: boolean = dep[0] === '.'; +}); diff --git a/types/detective/index.d.ts b/types/detective/index.d.ts new file mode 100644 index 0000000000..771d88f40c --- /dev/null +++ b/types/detective/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for detective 5.1 +// Project: https://github.com/browserify/detective +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as acorn from "acorn"; + +/** + * Find all calls to require() by walking the AST + */ +declare namespace detective { + interface Detective { + /** + * Give some source body src, return an array of all the require() calls with string arguments. + * The options parameter opts is passed along to detective.find(). + */ + (src: string, opts?: Options): string[]; + /** + * Give some source body 'src', return 'found' DetectiveResults + */ + find(src: string, opts?: Options): DetectiveResults; + } + + interface Options { + /** + * specify a different function name instead of "require" + */ + word?: string; + /** + * when true, populate found.nodes + */ + nodes?: string; + /** + * a function returning whether an AST CallExpression node is a require call + */ + isRequire?: (node: any) => boolean; + /** + * supply options directly to acorn with some support for esprima-style options range and loc + */ + parse?: acorn.Options; + /** + * Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), + * 7 (2016), 8 (2017), 9 (2018) or 10 (2019, partial support). This influences + * support for strict mode, the set of reserved words, and support for new syntax features. + * Default is 9. + */ + ecmaVersion?: string | number; + + /** + * If false, using a reserved word will generate an error. Defaults to true for ecmaVersion 3, + * false for higher versions. When given the value "never", reserved words and keywords can + * also not be used as property names (as in Internet Explorer's old parser). + */ + allowReserved?: boolean | "never"; + /** + * By default, a return statement at the top level raises an error. Set this to true to accept such code. + */ + allowReturnOutsideFunction?: boolean; + /** + * By default, import and export declarations can only appear at a program's top level. + * Setting this option to true allows them anywhere where a statement is allowed. + */ + allowImportExportEverywhere?: boolean; + /** + * When this is enabled (off by default), if the code starts with the + * characters #! (as in a shellscript), the first line will be treated as a comment. + */ + allowHashBang?: boolean; + /** + * When true, each node has a loc object attached with start and end subobjects, each of which + * contains the one-based line and zero-based column numbers in {line, column} form. Default is false. + */ + locations?: boolean; + /** + * Nodes have their start and end characters offsets recorded in start and end properties + * (directly on the node, rather than the loc object, which holds line/column data. + * To also add a semi-standardized range property holding a [start, end] array with + * the same numbers, set the ranges option to true. + */ + ranges?: string; + /** + * Indicate the mode the code should be parsed in. Can be either "script" or "module". + * This influences global strict mode and parsing of import and export declarations. + */ + sourceType?: ("script" | "module"); + } + + interface DetectiveResults { + /** + * an array of each string found in a require() + */ + strings: string[]; + /** + * an array of each stringified expression found in a require() call + */ + expressions: string[]; + /** + * (when opts.nodes === true) - an array of AST nodes for each argument found in a require() call + */ + nodes?: any[]; + } +} + +declare var detective: detective.Detective; + +export = detective; diff --git a/types/detective/tsconfig.json b/types/detective/tsconfig.json new file mode 100644 index 0000000000..49cdedb7fd --- /dev/null +++ b/types/detective/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", + "detective-tests.ts" + ] +} \ No newline at end of file diff --git a/types/detective/tslint.json b/types/detective/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detective/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts index 0dea2a305e..2f640da490 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -16,6 +16,29 @@ diffArraysResult.forEach(result => { } }); +interface DiffObj { + value: number; +} +const a: DiffObj = {value: 0}; +const b: DiffObj = {value: 1}; +const c: DiffObj = {value: 2}; +const d: DiffObj = {value: 3}; +const arrayOptions: jsdiff.IArrayOptions = { + comparator: (left: DiffObj, right: DiffObj) => { + return left.value === right.value; + } +}; +const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); +diffResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + // -------------------------- class LineDiffWithoutWhitespace extends jsdiff.Diff { diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 33d337d1b7..760aee4e61 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kpdecker/jsdiff // Definitions by: vvakame // szdc +// moc-yuto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -18,8 +19,8 @@ declare namespace JsDiff { newlineIsToken?: boolean; } - interface IArrayOptions extends IOptions { - comparator?: (left: any, right: any) => number; + interface IArrayOptions { + comparator?: (left: any, right: any) => boolean; } interface IDiffResult { 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/dojo/dijit.d.ts b/types/dojo/dijit.d.ts index b22742b85d..4b75746aed 100644 --- a/types/dojo/dijit.d.ts +++ b/types/dojo/dijit.d.ts @@ -2855,7 +2855,7 @@ declare module dijit { get(property:"ownerDocument"): Object; watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -6801,7 +6801,7 @@ declare module dijit { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -104923,7 +104923,7 @@ declare module dijit { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. diff --git a/types/dojo/dojox.widget.d.ts b/types/dojo/dojox.widget.d.ts index 9e8ce6563e..36a58aab0d 100644 --- a/types/dojo/dojox.widget.d.ts +++ b/types/dojo/dojox.widget.d.ts @@ -17225,7 +17225,7 @@ declare namespace dojox { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -18171,7 +18171,7 @@ declare namespace dojox { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -23352,7 +23352,7 @@ declare namespace dojox { get(property:"refreshOnShow"): boolean; watch(property: "refreshOnShow", callback: { (property?: string, oldValue?: boolean, newValue?: boolean): void }): { unwatch(): void } /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -24411,7 +24411,7 @@ declare namespace dojox { get(property:"ownerDocument"): Object; watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -25307,7 +25307,7 @@ declare namespace dojox { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. diff --git a/types/dom-loaded/dom-loaded-tests.ts b/types/dom-loaded/dom-loaded-tests.ts new file mode 100644 index 0000000000..f8a3e5486d --- /dev/null +++ b/types/dom-loaded/dom-loaded-tests.ts @@ -0,0 +1,3 @@ +import domLoaded = require("dom-loaded"); + +domLoaded.then(() => console.log("DOM is loaded")); diff --git a/types/dom-loaded/index.d.ts b/types/dom-loaded/index.d.ts new file mode 100644 index 0000000000..5d4d5154c4 --- /dev/null +++ b/types/dom-loaded/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for dom-loaded 1.0 +// Project: https://github.com/sindresorhus/dom-loaded#readme +// Definitions by: Lukas Tetzlaf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const domLoaded: Promise; +export = domLoaded; diff --git a/types/dom-loaded/tsconfig.json b/types/dom-loaded/tsconfig.json new file mode 100644 index 0000000000..7d17914d86 --- /dev/null +++ b/types/dom-loaded/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", + "dom-loaded-tests.ts" + ] +} diff --git a/types/dom-loaded/tslint.json b/types/dom-loaded/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dom-loaded/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dompurify/index.d.ts b/types/dompurify/index.d.ts index b72cc9e5e9..4c3a38d8f5 100644 --- a/types/dompurify/index.d.ts +++ b/types/dompurify/index.d.ts @@ -1,10 +1,14 @@ // Type definitions for DOM Purify // Project: https://github.com/cure53/DOMPurify -// Definitions by: Dave Taylor , Samira Bazuzi +// Definitions by: Dave Taylor , Samira Bazuzi , FlowCrypt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace DOMPurify; +export declare let version: string; +export declare let removed: any[]; +export declare let isSupported: boolean; + export declare function sanitize(source: string | Node): string; export declare function sanitize(source: string | Node, config: Config & { RETURN_DOM_FRAGMENT?: false; RETURN_DOM?: false; }): string; export declare function sanitize(source: string | Node, config: Config & { RETURN_DOM_FRAGMENT: true; }): DocumentFragment; @@ -13,6 +17,12 @@ export declare function sanitize(source: string | Node, config: Config): string export declare function addHook(hook: 'uponSanitizeElement', cb: (currentNode: Element, data: SanitizeElementHookEvent, config: Config) => void): void; export declare function addHook(hook: 'uponSanitizeAttribute', cb: (currentNode: Element, data: SanitizeAttributeHookEvent, config: Config) => void): void; export declare function addHook(hook: HookName, cb: (currentNode: Element, data: HookEvent, config: Config) => void): void; +export declare function setConfig(cfg: Config): void; +export declare function clearConfig(): void; +export declare function isValidAttribute(tag: string, attr: string, value: string): boolean; +export declare function removeHook(entryPoint: HookName): void; +export declare function removeHooks(entryPoint: HookName): void; +export declare function removeAllHooks(): void; interface Config { ADD_ATTR?: string[]; @@ -30,6 +40,11 @@ interface Config { SAFE_FOR_JQUERY?: boolean; SANITIZE_DOM?: boolean; WHOLE_DOCUMENT?: boolean; + ALLOWED_URI_REGEXP?: RegExp; + SAFE_FOR_TEMPLATES?: boolean; + ALLOW_UNKNOWN_PROTOCOLS?: boolean; + USE_PROFILES?: false | {mathMl?: boolean, svg?: boolean, svgFilters?: boolean, html?: boolean}; + IN_PLACE?: boolean; } type HookName diff --git a/types/doubleclick-gpt/doubleclick-gpt-tests.ts b/types/doubleclick-gpt/doubleclick-gpt-tests.ts index 9218408268..4d29a46d91 100644 --- a/types/doubleclick-gpt/doubleclick-gpt-tests.ts +++ b/types/doubleclick-gpt/doubleclick-gpt-tests.ts @@ -41,7 +41,7 @@ googletag.openConsole(); googletag.setAdIframeTitle("title"); -googletag.cmd.push(function() { +googletag.cmd.push(() => { googletag.defineSlot("/1234567/sports", [160, 600]). addService(googletag.pubads()); }); @@ -79,8 +79,8 @@ googletag.pubads().definePassback("/1234567/sports", [468, 60]). display(); googletag.pubads().definePassback("/1234567/sports", [160, 600]). - updateTargetingFromMap({"color": "red", - "interests": ["sports", "music", "movies"]}). + updateTargetingFromMap({color: "red", + interests: ["sports", "music", "movies"]}). display(); googletag.pubads().enableLazyLoad(); @@ -262,7 +262,7 @@ googletag.pubads().updateCorrelator(); // The listener will be called only when the pubads service renders a slot. // To listen to companion ads, add a similar listener to // googletag.companionAds(). -googletag.pubads().addEventListener("slotRenderEnded", function(event: googletag.events.SlotRenderEndedEvent) { +googletag.pubads().addEventListener("slotRenderEnded", (event: googletag.events.SlotRenderEndedEvent) => { console.log("Slot has been rendered:"); console.log(event); }); @@ -273,7 +273,7 @@ googletag.pubads().addEventListener("slotRenderEnded", function(event: googletag // however, programmatically filter a listener to respond only to a certain // ad slot, using this pattern: let targetSlot = slot1; -googletag.pubads().addEventListener("slotRenderEnded", function(event: googletag.events.SlotRenderEndedEvent) { +googletag.pubads().addEventListener("slotRenderEnded", (event: googletag.events.SlotRenderEndedEvent) => { if (event.slot === targetSlot) { // Slot specific logic. } @@ -283,7 +283,7 @@ googletag.pubads().addEventListener("slotRenderEnded", function(event: googletag // The listener will be called when the impression is considered viewable. // This event also operates at service level, but, as above, you can filter // to respond only to a certain ad slot by using this pattern: -googletag.pubads().addEventListener("impressionViewable", function(event: googletag.events.ImpressionViewableEvent) { +googletag.pubads().addEventListener("impressionViewable", (event: googletag.events.ImpressionViewableEvent) => { if (event.slot === targetSlot) { // Slot specific logic. } @@ -317,7 +317,6 @@ slot.clearCategoryExclusions(); // Make an ad request. Any ad can be returned for the slot. - slot = googletag.defineSlot("/1234567/sports", [160, 600], "div-1"). setTargeting("allow_expandable", "true"). setTargeting("interests", ["sports", "music", "movies"]). diff --git a/types/doubleclick-gpt/index.d.ts b/types/doubleclick-gpt/index.d.ts index ab71cdc99a..374f410c36 100644 --- a/types/doubleclick-gpt/index.d.ts +++ b/types/doubleclick-gpt/index.d.ts @@ -1,29 +1,30 @@ -// Type definitions for Google Publisher Tag v238 +// Type definitions for Google Publisher Tag 238.0 // Project: https://developers.google.com/doubleclick-gpt/reference // Definitions by: John Wright // Steven Joyce // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 declare namespace googletag { - export type SingleSizeArray = number[]; + type SingleSizeArray = number[]; - export type NamedSize = string | string[]; + type NamedSize = string | string[]; - export type SingleSize = SingleSizeArray | NamedSize; + type SingleSize = SingleSizeArray | NamedSize; - export type MultiSize = SingleSize[]; + type MultiSize = SingleSize[]; - export type GeneralSize = SingleSize | MultiSize; + type GeneralSize = SingleSize | MultiSize; - export type SizeMapping = GeneralSize[]; + type SizeMapping = GeneralSize[]; - export type SizeMappingArray = SizeMapping[]; + type SizeMappingArray = SizeMapping[]; - export interface CommandArray { - push(f: Function): number; + interface CommandArray { + push(f: () => void): number; } - export interface Service { + interface Service { addEventListener( eventType: string, listener: (event: events.ImpressionViewableEvent | events.SlotOnloadEvent | events.SlotRenderEndedEvent | events.slotVisibilityChangedEvent) => void @@ -31,29 +32,29 @@ declare namespace googletag { getSlots(): Slot[]; } - export interface CompanionAdsService extends Service { + interface CompanionAdsService extends Service { enableSyncLoading(): void; setRefreshUnfilledSlots(value: boolean): void; } - export interface ContentService extends Service { - setContent(slot: Slot, content: String): void; + interface ContentService extends Service { + setContent(slot: Slot, content: string): void; } - export interface LazyLoadOptionsConfig { - fetchMarginPercent?: number, - renderMarginPercent?: number, - mobileScaling?: number + interface LazyLoadOptionsConfig { + fetchMarginPercent?: number; + renderMarginPercent?: number; + mobileScaling?: number; } - export interface ResponseInformation { + interface ResponseInformation { advertiserId: string; campaignId: string; creativeId?: number; lineItemId?: number; } - export interface SafeFrameConfig { + interface SafeFrameConfig { allowOverlayExpansion?: boolean; allowPushExpansion?: boolean; sandbox?: boolean; @@ -78,7 +79,7 @@ declare namespace googletag { sizeMapping(): SizeMappingBuilder; } - export interface Slot { + interface Slot { addService(service: Service): Slot; clearCategoryExclusions(): Slot; clearTargeting(opt_key?: string): Slot; @@ -100,7 +101,7 @@ declare namespace googletag { setTargeting(key: string, value: string | string[]): Slot; } - export interface PassbackSlot { + interface PassbackSlot { display(): void; get(key: string): string; set(key: string, value: string): PassbackSlot; @@ -109,10 +110,10 @@ declare namespace googletag { setTagForChildDirectedTreatment(value: number): PassbackSlot; setTagForUnderAgeOfConsent(value: number): PassbackSlot; setTargeting(key: string, value: string | string[]): PassbackSlot; - updateTargetingFromMap(map: Object): PassbackSlot; + updateTargetingFromMap(map: object): PassbackSlot; } - export interface PubAdsService extends Service { + interface PubAdsService extends Service { clear(opt_slots?: Slot[]): boolean; clearCategoryExclusions(): PubAdsService; clearTagForChildDirectedTreatment(): PubAdsService; @@ -148,23 +149,23 @@ declare namespace googletag { updateCorrelator(): PubAdsService; } - export interface SizeMappingBuilder { + interface SizeMappingBuilder { addSize(viewportSize: SingleSizeArray, slotSize: GeneralSize): SizeMappingBuilder; build(): SizeMappingArray; } - export namespace events { - export interface ImpressionViewableEvent { + namespace events { + interface ImpressionViewableEvent { serviceName: string; slot: Slot; } - export interface SlotOnloadEvent { + interface SlotOnloadEvent { serviceName: string; slot: Slot; } - export interface SlotRenderEndedEvent { + interface SlotRenderEndedEvent { advertiserId?: number; creativeId?: number; isEmpty: boolean; @@ -176,7 +177,7 @@ declare namespace googletag { sourceAgnosticLineItemId?: number; } - export interface slotVisibilityChangedEvent { + interface slotVisibilityChangedEvent { inViewPercentage: number; serviceName: string; slot: Slot; diff --git a/types/doubleclick-gpt/tsconfig.json b/types/doubleclick-gpt/tsconfig.json index d240d560ce..7fff409f80 100644 --- a/types/doubleclick-gpt/tsconfig.json +++ b/types/doubleclick-gpt/tsconfig.json @@ -1,5 +1,4 @@ { - "compileOnSave": false, "compilerOptions": { "module": "commonjs", "lib": [ @@ -22,4 +21,4 @@ "index.d.ts", "doubleclick-gpt-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/doubleclick-gpt/tslint.json b/types/doubleclick-gpt/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/doubleclick-gpt/tslint.json +++ b/types/doubleclick-gpt/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } 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/draft-js/index.d.ts b/types/draft-js/index.d.ts index aea132cb3d..4f2c34dd3a 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -989,6 +989,8 @@ import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRe import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; import DraftDragType = Draft.Model.Constants.DraftDragType; import DraftBlockType = Draft.Model.Constants.DraftBlockType; +import DraftBlockRenderConfig = Draft.Model.ImmutableData.DraftBlockRenderConfig; +import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; import DraftEntityType = Draft.Model.Constants.DraftEntityType; @@ -1039,6 +1041,8 @@ export { DraftEditorCommand, DraftDragType, DraftBlockType, + DraftBlockRenderConfig, + DraftBlockRenderMap, DraftInlineStyleType, DraftEntityType, DraftEntityMutability, diff --git a/types/dragula/dragula-tests.ts b/types/dragula/dragula-tests.ts index 5f143406c3..0e6280ae61 100644 --- a/types/dragula/dragula-tests.ts +++ b/types/dragula/dragula-tests.ts @@ -30,3 +30,14 @@ var drake = dragula({ copy: true }); drake.containers.push(document.querySelector('#container')); + +dragula([document.getElementById('left'), document.getElementById('right')]) + .on('drag', function (el: Element) { + el.className = el.className.replace('ex-moved', ''); + }).on('drop', function (el: Element) { + el.className += ' ex-moved'; + }).on('over', function (el: Element, container: Element) { + container.className += ' ex-over'; + }).on('out', function (el: Element, container: Element) { + container.className = container.className.replace('ex-over', ''); + }); diff --git a/types/dragula/index.d.ts b/types/dragula/index.d.ts index 51998fb583..925a586971 100644 --- a/types/dragula/index.d.ts +++ b/types/dragula/index.d.ts @@ -33,7 +33,7 @@ declare namespace dragula { cancel(revert:boolean): void; cancel(): void; remove(): void; - on(events: string, callback: Function): void; + on(events: string, callback: Function): Drake; destroy(): void; } diff --git a/types/duplexify/duplexify-tests.ts b/types/duplexify/duplexify-tests.ts index 11d33d7303..aeed21e8dc 100644 --- a/types/duplexify/duplexify-tests.ts +++ b/types/duplexify/duplexify-tests.ts @@ -8,9 +8,17 @@ duplexify(writable, readable); duplexify(writable); duplexify(undefined, readable); +duplexify.obj(); +duplexify.obj(writable); +duplexify.obj(writable, readable); +duplexify.obj(writable, readable, {}); + const d: duplexify.Duplexify = duplexify(); d.setReadable(readable); d.setReadable(); // $ExpectError d.setWritable(writable); d.setWritable(); // $ExpectError +d.cork(); +d.uncork(); + const f: Duplex = d; diff --git a/types/duplexify/index.d.ts b/types/duplexify/index.d.ts index 791a000f8b..7df693e93b 100644 --- a/types/duplexify/index.d.ts +++ b/types/duplexify/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for duplexify 3.5 +// Type definitions for duplexify 3.6 // Project: https://github.com/mafintosh/duplexify // Definitions by: Sami Kukkonen +// Jonathan Lui // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -11,10 +12,14 @@ export = duplexify; interface DuplexifyConstructor { (writable?: stream.Writable, readable?: stream.Readable, streamOptions?: stream.DuplexOptions): duplexify.Duplexify; new (writable?: stream.Writable, readable?: stream.Readable, streamOptions?: stream.DuplexOptions): duplexify.Duplexify; + + obj(writable?: stream.Writable, readable?: stream.Readable, streamOptions?: stream.DuplexOptions): duplexify.Duplexify; } declare var duplexify: DuplexifyConstructor; declare namespace duplexify { interface Duplexify extends stream.Duplex { + cork(): void; + uncork(): void; setWritable(writable: stream.Writable): void; setReadable(readable: stream.Readable): void; } diff --git a/types/durandal/index.d.ts b/types/durandal/index.d.ts index 85dbb86e93..77e73f2501 100644 --- a/types/durandal/index.d.ts +++ b/types/durandal/index.d.ts @@ -101,7 +101,7 @@ interface DurandalSystemModule { /** * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. - * @param {function} [action] The action to defer. You will be passed the deferred object as a paramter. + * @param {function} [action] The action to defer. You will be passed the deferred object as a parameter. * @returns {Deferred} The deferred object. */ defer(action?: (dfd: DurandalDeferred) => void): DurandalDeferred; diff --git a/types/dwt/index.d.ts b/types/dwt/index.d.ts index 12813a9b40..12e4ac0521 100644 --- a/types/dwt/index.d.ts +++ b/types/dwt/index.d.ts @@ -1372,7 +1372,7 @@ declare enum EnumDWT_UploadDataFormat { Base64 = 1 } -/** +/** * interface for a DWT container which basically defines a DIV on the page */ interface Container { @@ -1381,7 +1381,7 @@ interface Container { Height: string | number; } -/** +/** * interface for a base64 result */ interface Base64Result { @@ -2294,7 +2294,7 @@ interface WebTwain { */ Zoom: number; - /* ignored + /* ignored style _AutoCropMethod */ @@ -2490,7 +2490,7 @@ interface WebTwain { * @param {Array} indices indices specifies which images are to be converted to base64. * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. * @return {Base64Result} - + ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType): Base64Result; */ @@ -3289,7 +3289,7 @@ interface WebTwain { */ MoveImage(sSourceImageIndex: number, sTargetImageIndex: number): boolean; - /*ignored + /*ignored OnRefreshUI */ @@ -3727,7 +3727,7 @@ interface WebTwain { * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. * @param {boolean} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. * @param {boolean} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. - * @param {number} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and paramters "AllowMultiSelect" and "OverwritePrompt" will be useless. + * @param {number} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and parameters "AllowMultiSelect" and "OverwritePrompt" will be useless. * @return {boolean} */ ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; @@ -3751,7 +3751,7 @@ interface WebTwain { */ ShowImageEditorEx(x: number, y: number, cx: number, cy: number, nCmdShow: number): boolean; - /*ingored + /*ingored SourceNameItems */ diff --git a/types/dwt/v12/index.d.ts b/types/dwt/v12/index.d.ts index 423dab8824..cc0d1f8079 100644 --- a/types/dwt/v12/index.d.ts +++ b/types/dwt/v12/index.d.ts @@ -2768,7 +2768,7 @@ interface WebTwain { * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. * @param {bool} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. * @param {bool} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. - * @param {int} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and paramters "AllowMultiSelect" and "OverwritePrompt" will be useless. + * @param {int} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and parameters "AllowMultiSelect" and "OverwritePrompt" will be useless. * @return {bool} */ ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index dc8edec397..601a45faf3 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -1132,7 +1132,7 @@ export namespace DS { * This method unloads all records in the store. * It schedules unloading to happen during the next run loop. */ - unloadAll(modelName: K): void; + unloadAll(modelName?: K): void; /** * DEPRECATED: * This method has been deprecated and is an alias for store.hasRecordForId, which should diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts index d3641a6c68..9c1194c711 100644 --- a/types/ember-data/test/store.ts +++ b/types/ember-data/test/store.ts @@ -205,3 +205,6 @@ declare module 'ember-data/types/registries/serializer' { assertType(store.adapterFor('user')); assertType(store.serializerFor('user')); + +store.unloadAll(); +store.unloadAll('user'); diff --git a/types/ember-data/v2/index.d.ts b/types/ember-data/v2/index.d.ts index dccf63e890..3afd091ffe 100644 --- a/types/ember-data/v2/index.d.ts +++ b/types/ember-data/v2/index.d.ts @@ -1094,7 +1094,7 @@ export namespace DS { * This method unloads all records in the store. * It schedules unloading to happen during the next run loop. */ - unloadAll(modelName: K): void; + unloadAll(modelName?: K): void; /** * DEPRECATED: * This method has been deprecated and is an alias for store.hasRecordForId, which should diff --git a/types/ember-data/v2/test/store.ts b/types/ember-data/v2/test/store.ts index f512afd8a7..2584e7bdf3 100644 --- a/types/ember-data/v2/test/store.ts +++ b/types/ember-data/v2/test/store.ts @@ -203,3 +203,6 @@ declare module 'ember-data' { assertType(store.adapterFor('user')); assertType(store.serializerFor('user')); + +store.unloadAll(); +store.unloadAll('user'); diff --git a/types/ember__object/internals.d.ts b/types/ember__object/internals.d.ts index e920311d45..518d777a46 100644 --- a/types/ember__object/internals.d.ts +++ b/types/ember__object/internals.d.ts @@ -1,4 +1,4 @@ -import { UnwrapComputedPropertyGetter } from '@ember/object/-private/types'; +import { UnwrapComputedPropertyGetter } from "@ember/object/-private/types"; /** * Returns the cached value for a property, if one exists. @@ -13,6 +13,11 @@ export function cacheFor( /** * Creates a shallow copy of the passed object. A deep copy of the object is * returned if the optional `deep` argument is `true`. + * + * @deprecated as of Ember 3.3, to be removed in Ember 4.0. See how to migrate + * [here][deprecation]. + * + * [deprecation]: https://emberjs.com/deprecations/v3.x#toc_ember-runtime-deprecate-copy-copyable */ export function copy(obj: T, deep: true): T; export function copy(obj: any, deep?: boolean): any; diff --git a/types/es6-shim/package.json b/types/es6-shim/package.json new file mode 100644 index 0000000000..c1f0c68752 --- /dev/null +++ b/types/es6-shim/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} \ No newline at end of file diff --git a/types/es6-shim/ts3.1/es6-shim-tests.ts b/types/es6-shim/ts3.1/es6-shim-tests.ts new file mode 100644 index 0000000000..87f6fba0e5 --- /dev/null +++ b/types/es6-shim/ts3.1/es6-shim-tests.ts @@ -0,0 +1,234 @@ +declare const require: (module: string) => Object; +if (require !== null) { + require('es6-shim'); +} + +interface Point { x: number; y: number; } +interface Point3D extends Point { z: number; } + +let a: any; +let s: string = ''; +let i: number = 2; +let iOrUndef: number | undefined; +let b: boolean; +let f: () => void = () => {}; +let o: Object; +let r: RegExp = /a/; +let sym: symbol = {} as symbol; +let e: Error = new Error(); +let date: Date; +let key: PropertyKey; +let point: Point = { x: 1, y: 2 }; +let point3d: Point3D = { x: 1, y: 2, z: 3 }; +let point3dOrUndef: Point3D | undefined; +let pointOrUndef: Point | undefined; +let arrayOfPoint: Point[] = []; +let arrayOfPoint3D: Point3D[]; +let arrayOfSymbol: symbol[]; +let arrayOfPropertyKey: PropertyKey[]; +let arrayOfAny: any[]; +let arrayOfStringAny: [string, any][]; +let arrayLikeOfAny: ArrayLike = []; +let iterableOfPoint: IterableShim = []; +let iterableOfStringPoint: IterableShim<[string, Point]> = []; +let iterableOfPointPoint3D: IterableShim<[Point, Point3D]> = []; +let iterableIteratorOfPoint: IterableIteratorShim; +let iterableIteratorOfNumberPoint: IterableIteratorShim<[number, Point]>; +let iterableIteratorOfNumber: IterableIteratorShim; +let iterableIteratorOfString: IterableIteratorShim; +let iterableIteratorOfPointPoint: IterableIteratorShim<[Point, Point]>; +let iterableIteratorOfNode: IterableIteratorShim; +let iterableIteratorOfStringPoint: IterableIteratorShim<[string, Point]>; +let iterableIteratorOfAny: IterableIteratorShim; +let iterableIteratorOfPropertyKey: IterableIteratorShim; +let iterableIteratorOfPropertyKeyPoint: IterableIteratorShim<[PropertyKey, Point]>; +let nodeList: NodeList; +let pd: PropertyDescriptor = {}; +let pdm: PropertyDescriptorMap = {}; +let map: Map = new Map(); +let set: Set = new Set(); +let weakMap: WeakMap = new WeakMap(); +let weakSet: WeakSet = new WeakSet(); +let promiseLikeOfPoint: PromiseLike = Promise.resolve(point); +let promiseLikeOfPoint3D: PromiseLike = Promise.resolve(point3d); +let promiseOfPoint: Promise = Promise.resolve(point); +let promiseOfPoint3D: Promise = Promise.resolve(point3d); +let promiseOfArrayOfPoint: Promise; +let promiseOfVoid: Promise; + +point = Object.assign(point, point); +b = Object.is(point, point); +Object.setPrototypeOf(point, {}); +pointOrUndef = arrayOfPoint.find(p => b); +i = arrayOfPoint.findIndex(p => b); +arrayOfPoint = arrayOfPoint.fill(point, i, arrayOfPoint.length); +arrayOfPoint = arrayOfPoint.copyWithin(i, i, i); +arrayOfPoint = Array.from(arrayOfPoint); +arrayOfPoint = Array.from(iterableOfPoint); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d, a); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d, a); +arrayOfPoint = Array.of(point, point); +i = s.codePointAt(i); +b = s.includes(s, i); +b = s.endsWith(s, i); +s = s.repeat(i); +b = s.startsWith(s, i); +s = String.fromCodePoint(2 as number, 3 as number); +s = String.raw`abc`; +s = r.flags; +i = Number.EPSILON; +b = Number.isFinite(i); +b = Number.isInteger(i); +b = Number.isNaN(i); +b = Number.isSafeInteger(i); +i = Number.MAX_SAFE_INTEGER; +i = Number.MIN_SAFE_INTEGER; +i = Number.parseFloat(s); +i = Number.parseInt(s); +i = Number.parseInt(s, i); +i = Math.clz32(i); +i = Math.imul(i, i); +i = Math.sign(i); +i = Math.log10(i); +i = Math.log2(i); +i = Math.log1p(i); +i = Math.expm1(i); +i = Math.cosh(i); +i = Math.sinh(i); +i = Math.tanh(i); +i = Math.acosh(i); +i = Math.asinh(i); +i = Math.atanh(i); +i = Math.hypot(i, i); +i = Math.trunc(i); +i = Math.fround(i); +i = Math.cbrt(i); +map.clear(); +map.delete(s); +map.forEach((value: Point, key: string) => { }); +pointOrUndef = map.get(s); +b = map.has(s); +map = map.set(s, point); +i = map.size; +map = new Map(); +map = new Map(iterableOfStringPoint); +set.clear(); +set.delete(point); +set.forEach((value: Point, key: Point) => { }); +b = set.has(point); +set = set.add(point); +i = set.size; +set = new Set(); +set = new Set(iterableOfPoint); +weakMap.delete(point); +point3dOrUndef = weakMap.get(point); +b = weakMap.has(point); +weakMap = weakMap.set(point, point3d); +weakMap = new WeakMap(); +weakMap = new WeakMap(iterableOfPointPoint3D); +weakSet.delete(point); +weakSet = weakSet.add(point); +b = weakSet.has(point); +weakSet = new WeakSet(); +weakSet = new WeakSet(iterableOfPoint); +iterableIteratorOfNumberPoint = arrayOfPoint.entries(); +iterableIteratorOfNumber = arrayOfPoint.keys(); +iterableIteratorOfPoint = arrayOfPoint.values(); +iterableIteratorOfPointPoint = set.entries(); +iterableIteratorOfPoint = set.keys(); +iterableIteratorOfPoint = set.values(); +promiseLikeOfPoint.then((point: Point) => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint.then((point: Point) => { }); +promiseOfPoint = promiseOfPoint.then(); +promiseOfPoint = promiseOfPoint.then(p => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint = promiseOfPoint.catch(e => point); +promiseOfPoint = promiseOfPoint.catch(e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => { }); +promiseOfPoint3D = promiseOfPoint3D.catch(e => point3d); +promiseOfPoint3D = promiseOfPoint3D.catch(e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint3D.catch(e => promiseLikeOfPoint3D); +promiseOfPoint = new Promise((resolve, reject) => resolve(point)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseLikeOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => reject(e)); +// To prevent UnhandledPromiseRejectionWarning +promiseOfPoint.catch(() => {}); +promiseOfArrayOfPoint = Promise.all(arrayOfPoint); +promiseOfArrayOfPoint = Promise.all(iterableOfPoint); +promiseOfPoint = Promise.race(arrayOfPoint); +promiseOfPoint = Promise.race(iterableOfPoint); +promiseOfVoid = Promise.resolve(); +promiseOfPoint = Promise.resolve(point3d); +promiseOfPoint = Promise.resolve(promiseOfPoint); +promiseOfPoint = Promise.resolve(promiseLikeOfPoint); +promiseOfVoid = Promise.reject(e); +// To prevent UnhandledPromiseRejectionWarning +promiseOfVoid.catch(() => {}); +promiseOfPoint = Promise.reject(e); +// To prevent UnhandledPromiseRejectionWarning +promiseOfPoint.catch(() => {}); +a = Reflect.apply(f, a, arrayLikeOfAny); +a = Reflect.construct(f, arrayLikeOfAny); +b = Reflect.defineProperty(a, s, pd); +b = Reflect.defineProperty(a, i, pd); +b = Reflect.defineProperty(a, sym, pd); +b = Reflect.deleteProperty(a, s); +b = Reflect.deleteProperty(a, i); +b = Reflect.deleteProperty(a, sym); +iterableIteratorOfAny = Reflect.enumerate(a); +Reflect.get(a, s, a); +Reflect.get(a, i, a); +Reflect.get(a, sym, a); +pd = Reflect.getOwnPropertyDescriptor(a, s); +pd = Reflect.getOwnPropertyDescriptor(a, i); +pd = Reflect.getOwnPropertyDescriptor(a, sym); +a = Reflect.getPrototypeOf(a); +b = Reflect.has(a, s); +b = Reflect.has(a, i); +b = Reflect.has(a, sym); +b = Reflect.isExtensible(a); +arrayOfPropertyKey = Reflect.ownKeys(a); +b = Reflect.preventExtensions(a); +b = Reflect.set(a, s, a, a); +b = Reflect.set(a, i, a, a); +b = Reflect.set(a, sym, a, a); +b = Reflect.setPrototypeOf(a, a); diff --git a/types/es6-shim/ts3.1/index.d.ts b/types/es6-shim/ts3.1/index.d.ts new file mode 100644 index 0000000000..7ed7ef6aba --- /dev/null +++ b/types/es6-shim/ts3.1/index.d.ts @@ -0,0 +1,661 @@ +interface IteratorResult { + done: boolean; + value?: T; +} + +interface IterableShim { + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): Iterator; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface IterableIteratorShim extends IterableShim, Iterator { + /** + * Shim for an ES6 iterable iterator. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; + + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: IterableShim, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: IterableShim): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): T[]; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIteratorShim<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIteratorShim; + + /** + * Returns an list of values in the array + */ + values(): IterableIteratorShim; + + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects to copy properties from. + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + * @remarks Requires `__proto__` support. + */ + setPrototypeOf(o: any, proto: any): any; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + flags: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[]): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; +} + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used to resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: IterableShim>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: IterableShim>): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): Map; + size: number; + entries(): IterableIteratorShim<[K, V]>; + keys(): IterableIteratorShim; + values(): IterableIteratorShim; +} + +interface MapConstructor { + new (): Map; + new (iterable: IterableShim<[K, V]>): Map; + prototype: Map; +} + +declare var Map: MapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + size: number; + entries(): IterableIteratorShim<[T, T]>; + keys(): IterableIteratorShim; + values(): IterableIteratorShim; + '_es6-shim iterator_'(): IterableIteratorShim; +} + +interface SetConstructor { + new (): Set; + new (iterable: IterableShim): Set; + prototype: Set; +} + +declare var Set: SetConstructor; + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): WeakMap; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (iterable: IterableShim<[K, V]>): WeakMap; + prototype: WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface WeakSet { + add(value: T): WeakSet; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (iterable: IterableShim): WeakSet; + prototype: WeakSet; +} + +declare var WeakSet: WeakSetConstructor; + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIteratorShim; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +declare module "es6-shim" { + var String: StringConstructor; + var Array: ArrayConstructor; + var Number: NumberConstructor; + var Math: Math; + var Object: ObjectConstructor; + var Map: MapConstructor; + var Set: SetConstructor; + var WeakMap: WeakMapConstructor; + var WeakSet: WeakSetConstructor; + var Promise: PromiseConstructor; + namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): Iterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; + } +} diff --git a/types/es6-shim/ts3.1/tsconfig.json b/types/es6-shim/ts3.1/tsconfig.json new file mode 100644 index 0000000000..e652a67caa --- /dev/null +++ b/types/es6-shim/ts3.1/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "es6-shim-tests.ts" + ] +} diff --git a/types/es6-shim/ts3.1/tslint.json b/types/es6-shim/ts3.1/tslint.json new file mode 100644 index 0000000000..7f26b198d9 --- /dev/null +++ b/types/es6-shim/ts3.1/tslint.json @@ -0,0 +1,19 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "array-type": false, + "ban-types": false, + "jsdoc-format": false, + "no-inferrable-types": false, + "no-object-literal-type-assertion": false, + "no-single-declare-module": false, + "no-unnecessary-generics": false, + "no-var-keyword": false, + "no-var-requires": false, + "prefer-object-spread": false, + "radix": false, + "semicolon": false, + "unified-signatures": false + } +} diff --git a/types/eslint/eslint-tests.ts b/types/eslint/eslint-tests.ts index b0c3c1966d..c6b8b786fa 100644 --- a/types/eslint/eslint-tests.ts +++ b/types/eslint/eslint-tests.ts @@ -62,7 +62,9 @@ sourceCode.getNodeByRangeIndex(0); sourceCode.isSpaceBetweenTokens(TOKEN, TOKEN); -sourceCode.getLocFromIndex(0); +const loc = sourceCode.getLocFromIndex(0); +loc.line; // $ExpectType number +loc.column; // $ExpectType number sourceCode.getIndexFromLoc({ line: 0, column: 0 }); diff --git a/types/eslint/index.d.ts b/types/eslint/index.d.ts index 031ab984f7..451477af40 100644 --- a/types/eslint/index.d.ts +++ b/types/eslint/index.d.ts @@ -136,7 +136,7 @@ export class SourceCode { isSpaceBetweenTokens(first: AST.Token, second: AST.Token): boolean; - getLocFromIndex(index: number): ESTree.SourceLocation; + getLocFromIndex(index: number): ESTree.Position; getIndexFromLoc(location: ESTree.Position): number; diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 2ba6227012..6b04bf8f11 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -104,7 +104,7 @@ export function warn(...values: any[]): void; /////////////////////////////////////////////////////////////////////////////// // Data Object Interfaces - These intrface are not specific part of fabric, -// They are just helpful for for defining function paramters +// They are just helpful for for defining function parameters ////////////////////////////////////////////////////////////////////////////// interface IDataURLOptions { /** @@ -4682,4 +4682,3 @@ export interface WebglFilterBackend extends FilterBackend, WebglFilterBackendOpt export class WebglFilterBackend { constructor(options?: WebglFilterBackendOptions); } - diff --git a/types/facebook-js-sdk/facebook-js-sdk-tests.ts b/types/facebook-js-sdk/facebook-js-sdk-tests.ts index 6b400a10a7..46b9f331f5 100644 --- a/types/facebook-js-sdk/facebook-js-sdk-tests.ts +++ b/types/facebook-js-sdk/facebook-js-sdk-tests.ts @@ -1,11 +1,10 @@ - - FB.init({ - appId: '***********', - version: 'v2.5', - status: true, - cookie: true, - xfbml: true + appId: '***********', + version: 'v2.5', + status: true, + cookie: true, + xfbml: true, + autoLogAppEvents: false }); FB.getLoginStatus(function(response: fb.StatusResponse) { @@ -31,12 +30,18 @@ FB.login(function(response: fb.StatusResponse) { scope: 'public_profile' }); +FB.login({ + scope: 'public_profile' +}); + FB.logout(function(response: fb.StatusResponse) { console.log(response); console.log(response.status); console.log(response.authResponse.accessToken); }); +FB.logout(); + /** * Dialog samples from Facebook documentation: */ @@ -65,8 +70,8 @@ FB.ui({ method: 'pay', action: 'purchaseitem', product: 'YOUR_PRODUCT_URL' -}, data => { - console.log(data.payment_id); +}, response => { + console.log(response.payment_id); }); FB.ui({ @@ -75,43 +80,93 @@ FB.ui({ product_id: 'com.fb.friendsmash.coins.10', developer_payload: 'this_is_a_test_payload' }, response => { - console.log(response); + console.log(response.payment_id); }); FB.ui({ method: 'pagetab', redirect_uri: 'YOUR_URL' -}, response => {}); +}, response => { + console.log(response.error_code); +}); FB.ui({ method: 'send', link: 'http://www.nytimes.com/interactive/2015/04/15/travel/europe-favorite-streets.html', -}, response => {}); +}, response => { + console.log(response.error_code); +}); FB.ui({ method: 'apprequests', message: 'Take this bomb to blast your way to victory!', to: 'USER_ID, USER_ID, INVITE_TOKEN', - action_type:'send', + action_type: 'send', object_id: 'YOUR_OBJECT_ID', // e.g. '191181717736427' }, response => { - console.log(response); + console.log(response.request); }); FB.ui({ method: 'apprequests', message: 'Friend Smash Request!', filters: [ - { name:'GROUP_1_NAME', user_ids:['USER_ID','USER_ID','USER_ID'] }, - { name:'GROUP_2_NAME', user_ids: ['USER_ID','USER_ID','USER_ID'] }, + { name: 'GROUP_1_NAME', user_ids: ['USER_ID', 'USER_ID', 'USER_ID'] }, + { name: 'GROUP_2_NAME', user_ids: ['USER_ID', 'USER_ID', 'USER_ID'] }, ] }, response => { - console.log(response); + console.log(response.request); }); FB.ui({ method: 'share', mobile_iframe: true, - href: 'https://developers.facebook.com/docs/', - picture: 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/2000px-Google_2015_logo.svg.png', -}, response => {}); + href: 'https://developers.facebook.com/docs/' +}, response => { + console.log(response.post_id); +}); + +FB.ui({ + account_id: '', + display: 'popup', + method: 'create_offer', + objective: 'APP_INSTALLS', + page_id: '', +}, response => { + console.log(response.id) +}); + +FB.ui({ + account_id: '', + display: 'popup', + method: 'lead_gen', + page_id: '', +}, response => { + console.log(response.formID) +}); + +FB.ui({ + display: 'popup', + method: 'canvas_editor', + business_id: '', + page_id: '' +}, response => { + console.log(response.id) +}); + +FB.ui({ + display: 'popup', + method: 'canvas_editor', + account_id: '', + business_id: '', + page_id: '', + template_id: '' +}, response => { + console.log(response.id) +}); + +FB.ui({ + display: 'popup', + method: 'canvas_preview', + canvas_id: '' +}); diff --git a/types/facebook-js-sdk/index.d.ts b/types/facebook-js-sdk/index.d.ts index 8a635d8995..86ca521c88 100644 --- a/types/facebook-js-sdk/index.d.ts +++ b/types/facebook-js-sdk/index.d.ts @@ -1,14 +1,15 @@ -// Type definitions for the Facebook Javascript SDK 2.8 +// Type definitions for the Facebook Javascript SDK 3.1 // Project: https://developers.facebook.com/docs/javascript // Definitions by: Amrit Kahlon // Mahmoud Zohdi +// Marc Knaup // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import fb = facebook; declare var FB: fb.FacebookStatic; declare namespace facebook { - - + + interface FacebookStatic { api: any; AppEvents: any; @@ -19,24 +20,26 @@ declare namespace facebook { * The method FB.getAuthResponse() is a synchronous accessor for the current authResponse. * The synchronous nature of this method is what sets it apart from the other login methods. * - * @param callback function to handle the response. - * * This method is similar in nature to FB.getLoginStatus(), but it returns just the authResponse object. */ - getAuthResponse(): AuthResponse; + getAuthResponse(): AuthResponse | null; + /** * FB.getLoginStatus() allows you to determine if a user is * logged in to Facebook and has authenticated your app. * * @param callback function to handle the response. + * @param roundtrip force a roundtrip to Facebook - effectively refreshing the cache of the response object */ - getLoginStatus(callback: (response: StatusResponse) => void, roundtrip?: boolean ): void; + getLoginStatus(callback: (response: StatusResponse) => void, roundtrip?: boolean): void; + /** * The method FB.init() is used to initialize and setup the SDK. * * @param params params for the initialization. */ init(params: InitParams): void; + /** * Use this function to log the user in * @@ -47,44 +50,90 @@ declare namespace facebook { * @param callback function to handle the response. * @param options optional ILoginOption to add params such as scope. */ - login(callback: (response: StatusResponse) => void, options?: LoginOptions): void; + login(callback: (response: StatusResponse) => void, options: LoginOptions): void; + + /** + * Use this function to log the user in + * + * Calling FB.login() results in the JS SDK attempting to open a popup window. + * As such, this method should only be called after a user click event, otherwise + * the popup window will be blocked by most browsers. + * + * @param options optional ILoginOption to add params such as scope. + */ + login(options: LoginOptions): void; + /** * The method FB.logout() logs the user out of your site and, in some cases, Facebook. * * @param callback function to handle the response */ - logout(callback: (response: StatusResponse) => void): void; + logout(callback?: (response: StatusResponse) => void): void; /** * @see https://developers.facebook.com/docs/sharing/reference/share-dialog */ - ui(params: ShareDialogParams, callback: (response: ShareDialogResponse) => void): void; + ui(params: ShareDialogParams, callback?: (response: ShareDialogResponse) => void): void; + + /** + * @see https://developers.facebook.com/docs/sharing/reference/share-dialog + */ + ui(params: ShareOpenGraphDialogParams, callback?: (response: ShareOpenGraphDialogResponse) => void): void; + + /** + * @see https://developers.facebook.com/docs/pages/page-tab-dialog + */ + ui(params: AddPageTabDialogParams, callback?: (response: DialogResponse) => void): void; /** * @see https://developers.facebook.com/docs/games/services/gamerequests */ - ui(params: GameRequestDialogParams, callback: (response: GameRequestDialogResponse) => void): void; + ui(params: GameRequestDialogParams, callback?: (response: GameRequestDialogResponse) => void): void; /** * @see https://developers.facebook.com/docs/payments/reference/paydialog */ - ui(params: PayDialogParams, callback: (response: PayDialogResponse) => void): void; + ui(params: PayDialogParams, callback?: (response: PayDialogResponse) => void): void; /** * @see https://developers.facebook.com/docs/games_payments/payments_lite */ - ui(params: PaymentsLiteDialogParams, callback: (response: PaymentsLiteDialogResponse) => void): void; - + ui(params: PaymentsLiteDialogParams, callback?: (response: PaymentsLiteDialogResponse) => void): void; + /** - * @see https://developers.facebook.com/docs/videos/live-video/exploring-live + * @see https://developers.facebook.com/docs/videos/live-video/exploring-live#golivedialog */ - ui(params: LiveDialogParams, callback: (response: LiveDialogResponse) => void): void; + ui(params: LiveDialogParams, callback?: (response: LiveDialogResponse) => void): void; /** * @see https://developers.facebook.com/docs/sharing/reference/send-dialog - * @see https://developers.facebook.com/docs/pages/page-tab-dialog */ - ui(params: SendDialogParams | AddPageTabDialogParams, callback: (response: null) => void): void; + ui(params: SendDialogParams, callback?: (response: DialogResponse) => void): void; + + /** + * @see https://developers.facebook.com/docs/marketing-api/guides/offer-ads/#create-offer-dialog + */ + ui(params: CreateOfferDialogParams, callback?: (response: CreateOfferDialogResponse) => void): void; + + /** + * @see https://developers.facebook.com/docs/marketing-api/guides/lead-ads/create#create-leadgen-dialog + */ + ui(params: LeadgenDialogParams, callback?: (response: LeadgenDialogResponse) => void): void; + + /** + * @see https://developers.facebook.com/docs/marketing-api/guides/canvas-ads#canvas-ads-dialog + */ + ui(params: InstantExperiencesAdsDialogParams, callback?: (response: InstantExperiencesAdsDialogResponse) => void): void; + + /** + * @see https://developers.facebook.com/docs/marketing-api/guides/canvas-ads#canvas-preview-dialog + */ + ui(params: InstantExperiencesPreviewDialogParams, callback?: (response: DialogResponse) => void): void; + + /** + * @see https://developers.facebook.com/docs/marketing-api/guides/collection#collection-ads-dialog + */ + ui(params: CollectionAdsDialogParams, callback?: (response: CollectionAdsDialogResponse) => void): void; XFBML: any; } @@ -97,10 +146,11 @@ declare namespace facebook { xfbml?: boolean; frictionlessRequests?: boolean; hideFlashCallback?: boolean; + autoLogAppEvents?: boolean; } interface LoginOptions { - auth_type?: string; + auth_type?: 'rerequest'; scope?: string; return_scopes?: boolean; enable_profile_selector?: boolean; @@ -122,12 +172,21 @@ declare namespace facebook { interface ShareDialogParams extends DialogParams { method: 'share'; href: string; - picture?: string; hashtag?: string; quote?: string; mobile_iframe?: boolean; } + interface ShareOpenGraphDialogParams extends DialogParams { + method: 'share_open_graph'; + action_type: string; + action_properties: { [property: string]: any }; + href: string; + hashtag?: string; + quote?: string; + mobile_iframe?: false; + } + interface AddPageTabDialogParams extends DialogParams { method: 'pagetab'; redirect_uri: string; @@ -137,13 +196,13 @@ declare namespace facebook { method: 'apprequests'; message: string; action_type?: 'send' | 'askfor' | 'turn'; - data?: number; + data?: string; exclude_ids?: string[]; filters?: 'app_users' | 'app_non_users' | Array<{ name: string, user_ids: string[] }>; max_recipients?: number; object_id?: string; suggestions?: string[]; - title?: number; + title?: string; to?: string | number; } @@ -160,10 +219,11 @@ declare namespace facebook { quantity?: number; quantity_min?: number; quantity_max?: number; + pricepoint_id?: string; request_id?: string; test_currency?: string; } - + interface PaymentsLiteDialogParams extends DialogParams { method: 'pay'; action: 'purchaseiap'; @@ -179,6 +239,43 @@ declare namespace facebook { broadcast_data?: LiveDialogResponse; } + interface CreateOfferDialogParams extends DialogParams { + account_id: string; + display: 'popup'; + method: 'create_offer'; + objective: 'APP_INSTALLS' | 'CONVERSIONS' | 'LINK_CLICKS' | 'OFFER_CLAIMS' | 'PRODUCT_CATALOG_SALES' | 'STORE_VISITS'; + page_id: string; + } + + interface LeadgenDialogParams extends DialogParams { + account_id: string; + display: 'popup'; + method: 'lead_gen'; + page_id: string; + } + + interface InstantExperiencesAdsDialogParams extends DialogParams { + display: 'popup'; + method: 'canvas_editor'; + business_id: string; + page_id: string; + canvas_id?: string; + } + + interface InstantExperiencesPreviewDialogParams extends DialogParams { + display: 'popup'; + method: 'canvas_preview'; + canvas_id: string; + } + + interface CollectionAdsDialogParams extends InstantExperiencesAdsDialogParams { + account_id: string; + canvas_id?: undefined; + template_id: string; + product_catalog_id?: string; + product_set_id?: string; + } + //////////////////////// // // RESPONSES @@ -190,48 +287,73 @@ declare namespace facebook { signedRequest: string; userID: string; grantedScopes?: string; + reauthorize_required_in?: number; } - + interface StatusResponse { - status: string; + status: 'authorization_expired' | 'connected' | 'not_authorized' | 'unknown'; authResponse: AuthResponse; } - interface ShareDialogResponse { - post_id?: string; + interface DialogResponse { + error_code?: number; error_message?: string; } - interface GameRequestDialogResponse { + interface ShareDialogResponse extends DialogResponse { + post_id: string; + } + + interface ShareOpenGraphDialogResponse extends DialogResponse { + post_id: string; + } + + interface GameRequestDialogResponse extends DialogResponse { request: string; to: string[]; } - interface PayDialogResponse { + interface PayDialogResponse extends DialogResponse { payment_id: string; amount: string; currency: string; quantity: string; - request_id: string; - status: string; + request_id?: string; + status: 'completed' | 'initiated'; signed_request: string; } - interface PaymentsLiteDialogResponse { + interface PaymentsLiteDialogResponse extends DialogResponse { + app_id: number; developer_payload?: string; payment_id: number; - product_id?: string; - purchase_time?: number; - purchase_token?: string; - signed_request?: string; - error_code?: number; - error_message?: string; + product_id: string; + purchase_time: number; + purchase_token: string; + signed_request: string; } - - interface LiveDialogResponse { + + interface LiveDialogResponse extends DialogResponse { id: string; stream_url: string; secure_stream_url: string; status: string; } + + interface CreateOfferDialogResponse extends DialogResponse { + id: string; + success: boolean; + } + + interface LeadgenDialogResponse extends DialogResponse { + formID: string; + success: boolean; + } + + interface InstantExperiencesAdsDialogResponse extends DialogResponse { + id: string; + success: boolean; + } + + interface CollectionAdsDialogResponse extends InstantExperiencesAdsDialogResponse {} } 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/gamepad/gamepad-tests.ts b/types/gamepad/gamepad-tests.ts index af3095adb0..b71203eb7c 100644 --- a/types/gamepad/gamepad-tests.ts +++ b/types/gamepad/gamepad-tests.ts @@ -1,70 +1,69 @@ +/// +import gamepad = require('gamepad'); +// Initialize the library +gamepad.init(); +// List the state of all currently attached devices +for (let i = 0, l = gamepad.numDevices(); i < l; i++) { + console.log(i, gamepad.deviceAtIndex(i)); +} -()=>{ - function runAnimation() - { - window.requestAnimationFrame(runAnimation); +// Create a game loop and poll for events +setInterval(gamepad.processEvents, 16); +// Scan for new gamepads as a slower rate +setInterval(gamepad.detectDevices, 500); - var gamepads = navigator.getGamepads(); - - for (var i = 0; i < gamepads.length; ++i) - { - var pad = gamepads[i]; - // todo; simple demo of displaying pad.axes and pad.buttons +// Listen for new gamepads being attached +gamepad.on('attach', (deviceID, device) => { + console.log('attach', { + deviceID, + device: { + deviceID: device.deviceID, + description: device.description, + vendorID: device.vendorID, + productID: device.productID, + axisStates: device.axisStates, + buttonStates: device.buttonStates, } - } + }); +}); - window.requestAnimationFrame(runAnimation); -}; +// Listen for new gamepads being removed +gamepad.on('remove', deviceID => { + console.log('remove', { + deviceID + }); +}); -(()=>{ - var gamepadconnected = (e: Gamepad.GamepadEvent) => { - console.log('Gamepad ' + e.gamepad.index + ' connected!'); - if(e.gamepad.mapping == 'standard'){ - console.log("The Gamepad's controls have been mapped to the Standard Gamepad layout."); - } - }; - var gamepaddisconnected = (e: Gamepad.GamepadEvent) => { - console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); - }; +// Listen for button down events on all gamepads +gamepad.on('up', (deviceID, buttonID, timestamp) => { + console.log('up', { + deviceID, + buttonID, + timestamp + }); +}); - window.addEventListener('GamepadConnected', gamepadconnected, false); - window.addEventListener('GamepadDisconnected', gamepaddisconnected, false); - window.addEventListener('webkitGamepadConnected', gamepadconnected, false); - window.addEventListener('webkitGamepadDisconnected', gamepaddisconnected, false); - window.addEventListener('mozGamepadConnected', gamepadconnected, false); - window.addEventListener('mozGamepadDisconnected', gamepaddisconnected, false); +// Listen for button down events on all gamepads +gamepad.on('down', (deviceID, buttonID, timestamp) => { + console.log('down', { + deviceID, + buttonID, + timestamp + }); +}); - var requestAnimationFrame = window.requestAnimationFrame || (window).mozRequestAnimationFrame; - var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; - if(getGamepads){ - function runAnimation() - { - requestAnimationFrame.call(window, runAnimation); +// Listen for move events on all gamepads +gamepad.on('move', (deviceID, axisID, value, lastValue, timestamp) => { + console.log('move', { + deviceID, + axisID, + value, + lastValue, + timestamp + }); +}); - var gamepads: Gamepad.Gamepad[] = getGamepads.call(navigator); - for(var i = 0; i < gamepads.length; i++){ - var pad: Gamepad.Gamepad = gamepads[i]; - if(pad && pad.connected){ - for (var k = 0; k < pad.buttons.length; k++) - { - var button: Gamepad.GamepadButton = pad.buttons[k]; - if(button.pressed){ - console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button.value); - } - } - for (var k = 0; k < pad.axes.length; k++) - { - var axis = pad.axes[k]; - if(Math.abs(axis) > 0.1){ - console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis); - } - } - } - } - } - - runAnimation(); - } -})(); \ No newline at end of file +// Shutdown the library +gamepad.shutdown(); diff --git a/types/gamepad/index.d.ts b/types/gamepad/index.d.ts index 3678190522..b66e13336b 100644 --- a/types/gamepad/index.d.ts +++ b/types/gamepad/index.d.ts @@ -1,97 +1,33 @@ -// Type definitions for Gamepad API -// Project: http://www.w3.org/TR/gamepad/ -// Definitions by: Kon +// Type definitions for gamepad 1.5 +// Project: https://github.com/creationix/node-gamepad#readme +// Definitions by: Alex Van Camp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 -declare namespace Gamepad{ - /** - * This interface defines an individual gamepad device. - */ - export interface Gamepad{ - /** - * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. - * @readonly - */ - id:string; +import { EventEmitter } from 'events'; - /** - * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. - * @readonly - */ - index:number; +declare const nodeGamepad: NodeGamepad; +export = nodeGamepad; - /** - * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. - * @readonly - */ - timestamp:number; +interface NodeGamepad extends EventEmitter { + init(): void; + shutdown(): void; + numDevices(): number; + deviceAtIndex(deviceIndex: number): GamepadInstance; + detectDevices(): void; + processEvents(): void; - /** - * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. - * @readonly - */ - axes:number[]; - - /** - * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. - * @readonly - */ - buttons:GamepadButton[]; - - /** - * Indicates whether the physical device represented by this object is still connected to the system. When a gamepad becomes unavailable, whether by being physically disconnected, powered off or otherwise unusable, the connected attribute must be set to false. - * @readonly - */ - connected:boolean; - - /** - * The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it should indicate that a mapping is in use by setting this property to a known mapping name. Currently the only known mapping is "standard", which corresponds to the Standard Gamepad layout. If the user agent does not have knowledge of the device layout and is simply providing the controls as represented by the driver in use, then it must set the mapping property to an empty string. - * @readonly - */ - mapping:string; - } - - /** - * - */ - export interface GamepadEvent extends Event{ - /** - * The single gamepad attribute provides access to the associated gamepad data for this event. - * @readonly - */ - gamepad:Gamepad; - } - - export interface GamepadList{ - [index: number]: Gamepad; - length: number; - } - - export interface GamepadButton{ - pressed: boolean; - value: number; - } - - /* - * @event gamepadconnected - * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. - */ - - /* - * @event gamepaddisconnected - * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. - */ + on(event: 'attach', listener: (deviceID: number, device: GamepadInstance) => void): this; + on(event: 'remove', listener: (deviceID: number) => void): this; + on(event: 'down' | 'up', listener: (deviceID: number, buttonID: number, timestamp: number) => void): this; + on(event: 'move', listener: (deviceID: number, axisID: number, value: number, lastValue: number, timestamp: number) => void): this; } -interface Navigator{ - /** - * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. - * @readonly - */ - getGamepads(): Gamepad.Gamepad[]; - - webkitGetGamepads(): Gamepad.GamepadList; - - // Not supported yet :( - // mozGetGamepads(): Gamepad[]; +interface GamepadInstance { + deviceID: number; + description: string; + vendorID: number; + productID: number; + axisStates: number[]; + buttonStates: boolean[]; } diff --git a/types/gamepad/tsconfig.json b/types/gamepad/tsconfig.json index 4cb63f3d80..39d007a909 100644 --- a/types/gamepad/tsconfig.json +++ b/types/gamepad/tsconfig.json @@ -2,13 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +20,4 @@ "index.d.ts", "gamepad-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/gamepad/tslint.json b/types/gamepad/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/gamepad/tslint.json +++ b/types/gamepad/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/gapi.auth2/gapi.auth2-tests.ts b/types/gapi.auth2/gapi.auth2-tests.ts index 16818e414e..1fc03f7f4f 100644 --- a/types/gapi.auth2/gapi.auth2-tests.ts +++ b/types/gapi.auth2/gapi.auth2-tests.ts @@ -55,8 +55,8 @@ function test_render() { const success = (googleUser: gapi.auth2.GoogleUser): void => { console.log(googleUser); }; - const failure = (): void => { - console.log('Failure callback'); + const failure = (reason: { error: string }): void => { + console.log(`Failure callback: ${reason.error}`); }; gapi.signin2.render('testId', { diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index fdb4c08cc3..bd40ce9650 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -349,7 +349,7 @@ declare namespace gapi.signin2 { /** * The callback function to call when sign-in fails (default: none). */ - onfailure?(): void; + onfailure?(reason: { error: string }): void; /** * The package name of the Android app to install over the air. See diff --git a/types/gapi.client.dfareporting/index.d.ts b/types/gapi.client.dfareporting/index.d.ts index e8050193e4..8914fbb3e5 100644 --- a/types/gapi.client.dfareporting/index.d.ts +++ b/types/gapi.client.dfareporting/index.d.ts @@ -2237,7 +2237,7 @@ declare namespace gapi.client { /** Tag format type for the floodlight activity. If left blank, the tag format will default to HTML. */ tagFormat?: string; /** - * Value of the cat= paramter in the floodlight tag, which the ad servers use to identify the activity. This is optional: if empty, a new tag string will + * Value of the cat= parameter in the floodlight tag, which the ad servers use to identify the activity. This is optional: if empty, a new tag string will * be generated for you. This string must be 1 to 8 characters long, with valid characters being [a-z][A-Z][0-9][-][ _ ]. This tag string must also be * unique among activities of the same activity group. This field is read-only after insertion. */ diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 09a1e611ea..4b8a69aa93 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -48,6 +48,7 @@ pool.use((conn: Connection) => 'test') pool.acquire() .then((conn: Connection) => { + console.log(pool.isBorrowedResource(conn)); // => true return pool.release(conn); }).then(() => { return pool.acquire(5); diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index e50682ab12..7a446243db 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -24,6 +24,7 @@ export class Pool extends EventEmitter { drain(): PromiseLike; clear(): PromiseLike; use(cb: (resource: T) => U): PromiseLike; + isBorrowedResource(resource: T): boolean; } export interface Factory { diff --git a/types/git-rev-sync/git-rev-sync-tests.ts b/types/git-rev-sync/git-rev-sync-tests.ts new file mode 100644 index 0000000000..380a1069ed --- /dev/null +++ b/types/git-rev-sync/git-rev-sync-tests.ts @@ -0,0 +1,13 @@ +import * as gitRevSync from "git-rev-sync"; + +gitRevSync.branch(); +gitRevSync.count(); +gitRevSync.date(); +gitRevSync.isDirty(); +gitRevSync.isTagDirty(); +gitRevSync.long(); +gitRevSync.message(); +gitRevSync.remoteUrl(); +gitRevSync.short(); +gitRevSync.short(); +gitRevSync.tag(); diff --git a/types/git-rev-sync/index.d.ts b/types/git-rev-sync/index.d.ts new file mode 100644 index 0000000000..e982f6b9ff --- /dev/null +++ b/types/git-rev-sync/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for git-rev-sync 1.12 +// Project: https://github.com/kurttheviking/git-rev-sync-js +// Definitions by: khoi-fish +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function short(filePath?: string, length?: number): string; +export function long(filePath?: string): string; +export function branch(branch?: string): void; +export function count(): number; +export function date(): Date; +export function isDirty(): boolean; +export function isTagDirty(): boolean; +export function message(): string; +export function remoteUrl(): string; +export function tag(makeDirty?: boolean): string; diff --git a/types/git-rev-sync/tsconfig.json b/types/git-rev-sync/tsconfig.json new file mode 100644 index 0000000000..4ab561dfec --- /dev/null +++ b/types/git-rev-sync/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "git-rev-sync-tests.ts"] +} diff --git a/types/git-rev-sync/tslint.json b/types/git-rev-sync/tslint.json new file mode 100644 index 0000000000..1bec602599 --- /dev/null +++ b/types/git-rev-sync/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": true + } +} diff --git a/types/glue/v4/glue-tests.ts b/types/glue/v4/glue-tests.ts new file mode 100644 index 0000000000..1b67554725 --- /dev/null +++ b/types/glue/v4/glue-tests.ts @@ -0,0 +1,69 @@ +import * as glue from "glue"; +import * as hapi from "hapi"; + +const manifest: glue.Manifest = { + server: { + debug: false, + }, + connections: [ + { + port: 8000, + labels: ['web'] + }, + { + port: 8001, + labels: ['admin'] + } + ], + registrations: [ + { + plugin: { + register: './assets', + options: { + uglify: true + } + } + }, + { + plugin: './ui-user', + options: { + select: ['web'] + } + }, + { + plugin: { + register: './ui-admin', + options: { + sessiontime: 500 + } + }, + options: { + select: ['admin'], + routes: { + prefix: '/admin' + } + } + }, + { + plugin: { + register: require('./awesome-plugin.js'), + options: { + whyNot: true + } + } + }, + ] +}; + +const options: glue.Options = { + relativeTo: `${__dirname}/modules` +}; + +glue.compose(manifest, options, (err, server) => { + if (err) { + throw err; + } + server.start(() => { + console.log('hapi days!'); + }); +}); diff --git a/types/glue/v4/index.d.ts b/types/glue/v4/index.d.ts new file mode 100644 index 0000000000..69c7d56d01 --- /dev/null +++ b/types/glue/v4/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for glue 4.2 +// Project: https://github.com/hapijs/glue +// Definitions by: Greg Jednaszewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Server, ServerConnectionOptions, ServerOptions } from "hapi"; + +export interface Options { + relativeTo: string; + preConnections?: (Server: Server, next: (err: any) => void) => void; + preRegister?: (Server: Server, next: (err: any) => void) => void; +} + +export interface Plugin { + plugin: string | { + register: string; + options?: any; + }; + options?: any; +} + +export interface Manifest { + server: ServerOptions; + connections: ServerConnectionOptions[]; + registrations?: Plugin[]; +} + +export function compose(manifest: Manifest, + options?: Options, + callback?: (err?: any, server?: Server) => void): Promise; diff --git a/types/glue/v4/tsconfig.json b/types/glue/v4/tsconfig.json new file mode 100644 index 0000000000..ead9b81629 --- /dev/null +++ b/types/glue/v4/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "boom": [ "boom/v4" ], + "catbox": [ "catbox/v7" ], + "hapi": [ "hapi/v16" ], + "glue": [ "glue/v4" ] + } + }, + "files": [ + "index.d.ts", + "glue-tests.ts" + ] +} diff --git a/types/mali/tslint.json b/types/glue/v4/tslint.json similarity index 94% rename from types/mali/tslint.json rename to types/glue/v4/tslint.json index d88586e5bd..30a1bdde2e 100644 --- a/types/mali/tslint.json +++ b/types/glue/v4/tslint.json @@ -1,3 +1,3 @@ { "extends": "dtslint/dt.json" -} +} \ No newline at end of file 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/react-i18next/v1/tsconfig.json b/types/got/v8/tsconfig.json similarity index 62% rename from types/react-i18next/v1/tsconfig.json rename to types/got/v8/tsconfig.json index b16cb92b25..a5ffba23b0 100644 --- a/types/react-i18next/v1/tsconfig.json +++ b/types/got/v8/tsconfig.json @@ -13,22 +13,17 @@ "typeRoots": [ "../../" ], + "types": [], "paths": { - "react-i18next": [ - "react-i18next/v1" - ], - "i18next": [ - "i18next/v2" + "got": [ + "got/v8" ] }, - "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, - "jsx": "react", - "experimentalDecorators": true + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "react-i18next-tests.tsx" + "got-tests.ts" ] -} \ No newline at end of file +} 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/graphlib-dot/index.d.ts b/types/graphlib-dot/index.d.ts new file mode 100644 index 0000000000..0a9eb1cb7a --- /dev/null +++ b/types/graphlib-dot/index.d.ts @@ -0,0 +1,56 @@ +// Type definitions for graphlib-dot 0.6 +// Project: https://github.com/dagrejs/graphlib-dot +// Definitions by: Dom Parfitt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Graph } from 'graphlib'; + +/** + * Reads a single DOT graph from the str and returns it a Graph representation. + * @param str a string in the DOT language representing a graph + */ +export function read(str: string): Graph; + +/** + * Parses one or more DOT graphs from str in a manner similar to that used by parse for individual graphs. + * @param str a string in the DOT language representing one or more graphs + */ +export function readMany(str: string): Graph[]; + +/** + * Writes a String representation of the given graph in the DOT language. + * @param g a graphlib Graph object + */ +export function write(g: Graph): string; + +/** + * Contains the version of the graphlib library used by graphlib-dot. + */ +export const graphlib: any; + +declare global { + namespace graphlibDot { + /** + * Reads a single DOT graph from the str and returns it a Graph representation. + * @param str a string in the DOT language representing a graph + */ + function read(str: string): Graph; + + /** + * Parses one or more DOT graphs from str in a manner similar to that used by parse for individual graphs. + * @param str a string in the DOT language representing one or more graphs + */ + function readMany(str: string): Graph[]; + + /** + * Writes a String representation of the given graph in the DOT language. + * @param g a graphlib Graph object + */ + function write(g: Graph): string; + + /** + * Contains the version of the graphlib library used by graphlib-dot. + */ + const graphlib: any; + } +} diff --git a/types/graphlib-dot/test/graphlib-dot-global-tests.ts b/types/graphlib-dot/test/graphlib-dot-global-tests.ts new file mode 100644 index 0000000000..7c427f21da --- /dev/null +++ b/types/graphlib-dot/test/graphlib-dot-global-tests.ts @@ -0,0 +1,6 @@ +// Global tests +const graph = graphlibDot.read('digraph {node 1}'); + +const graphs = graphlibDot.readMany('digraph { node1 }'); + +const dotStr = graphlibDot.write(graph); diff --git a/types/graphlib-dot/test/graphlib-dot-tests.ts b/types/graphlib-dot/test/graphlib-dot-tests.ts new file mode 100644 index 0000000000..138b9fdfe7 --- /dev/null +++ b/types/graphlib-dot/test/graphlib-dot-tests.ts @@ -0,0 +1,9 @@ +import { Graph } from "graphlib"; +import { read, readMany, write } from 'graphlib-dot'; + +// Module tests +const graph: Graph = read('digraph {node 1}'); + +const graphs: Graph[] = readMany('digraph { node1 }'); + +const dotStr: string = write(graph); diff --git a/types/graphlib-dot/tsconfig.json b/types/graphlib-dot/tsconfig.json new file mode 100644 index 0000000000..2e5efa560d --- /dev/null +++ b/types/graphlib-dot/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/graphlib-dot-tests.ts", + "test/graphlib-dot-global-tests.ts" + ] +} diff --git a/types/graphlib-dot/tslint.json b/types/graphlib-dot/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphlib-dot/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/graphql-resolvers/graphql-resolvers-tests.ts b/types/graphql-resolvers/graphql-resolvers-tests.ts new file mode 100644 index 0000000000..3acb3ccf27 --- /dev/null +++ b/types/graphql-resolvers/graphql-resolvers-tests.ts @@ -0,0 +1,19 @@ +import { + combineResolvers, + pipeResolvers, + allResolvers, + resolveDependee, + resolveDependees, + isDependee, + skip +} from "graphql-resolvers"; + +const resolverOne = () => skip; +const resolverTwo = () => skip; + +const combined = combineResolvers(resolverOne, resolverTwo); +const piped = pipeResolvers(resolverOne, resolverTwo); +const all = allResolvers([resolverOne, resolverTwo]); +const dependee = resolveDependee("resolverOne"); +const dependees = resolveDependees(["resolverOne", "resolverTwo"]); +const isDependent = isDependee(resolverOne); diff --git a/types/graphql-resolvers/index.d.ts b/types/graphql-resolvers/index.d.ts new file mode 100644 index 0000000000..292c22cf73 --- /dev/null +++ b/types/graphql-resolvers/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for graphql-resolvers 0.2 +// Project: https://github.com/lucasconstantino/graphql-resolvers#readme +// Definitions by: Mike Engel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { IFieldResolver } from "graphql-tools"; + +export const skip: undefined; + +export interface TArgs { + [argument: string]: any; +} + +export function combineResolvers( + ...resolvers: Array> +): IFieldResolver; + +export function pipeResolvers( + ...resolvers: Array> +): IFieldResolver; + +export function allResolvers( + resolvers: Array> +): IFieldResolver; + +export function resolveDependee( + dependeeName: string +): IFieldResolver; + +export function resolveDependees( + dependeeNames: string[] +): IFieldResolver; + +export function isDependee( + resolver: IFieldResolver +): IFieldResolver; diff --git a/types/graphql-resolvers/package.json b/types/graphql-resolvers/package.json new file mode 100644 index 0000000000..a3e9046d27 --- /dev/null +++ b/types/graphql-resolvers/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "graphql-tools": "^4.0.2" + } +} diff --git a/types/graphql-resolvers/tsconfig.json b/types/graphql-resolvers/tsconfig.json new file mode 100644 index 0000000000..602aa171ad --- /dev/null +++ b/types/graphql-resolvers/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "esnext.asynciterable"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "graphql-resolvers-tests.ts"] +} diff --git a/types/graphql-resolvers/tslint.json b/types/graphql-resolvers/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-resolvers/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gsap/Animation.d.ts b/types/gsap/Animation.d.ts index 3c58f9b12a..8744e205bf 100644 --- a/types/gsap/Animation.d.ts +++ b/types/gsap/Animation.d.ts @@ -1,9 +1,14 @@ declare namespace gsap { - export class Animation { - /** Base class for all TweenLite, TweenMax, TimelineLite, and TimelineMax classes, providing core methods/properties/() => voidality, but there is no reason to create an instance of this class directly. */ + class Animation { + /** + * Base class for all TweenLite, TweenMax, TimelineLite, and TimelineMax classes, providing core methods/properties/() => voidality, but there is no reason to create an instance of this + * class directly. + */ constructor(duration?: number, vars?: any); - /** A place to store any data you want (initially populated with vars.data if it exists). */ + /** + * A place to store any data you want (initially populated with vars.data if it exists). + */ data: any; /** [Read-only] Parent timeline. */ @@ -20,14 +25,23 @@ declare namespace gsap { duration(): number; duration(value: number): Animation; - /** Gets or sets an event callback like "onComplete", "onUpdate", "onStart", "onReverseComplete" or "onRepeat" (onRepeat only applies to TweenMax or TimelineMax instances) along with any parameters that should be passed to that callback. */ + /** + * Gets or sets an event callback like "onComplete", "onUpdate", "onStart", "onReverseComplete" or "onRepeat" (onRepeat only applies to TweenMax or TimelineMax instances) along with any + * parameters that should be passed to that callback. + */ eventCallback(type: string): () => void; eventCallback(type: string, callback: () => void, params?: any[], scope?: any): Animation; - /** Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ + /** + * Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded + * starting values. + */ invalidate(): Animation; - /** Indicates whether or not the animation is currently active (meaning the virtual playhead is actively moving across this instance's time span and it is not paused, nor are any of its ancestor timelines). */ + /** + * Indicates whether or not the animation is currently active (meaning the virtual playhead is actively moving across this instance's time span and it is not paused, nor are any of its + * ancestor timelines). + */ isActive(): boolean; /** Kills the animation entirely or in part depending on the parameters. */ @@ -43,7 +57,10 @@ declare namespace gsap { /** Begins playing forward, optionally from a specific time (by default playback begins from wherever the playhead currently is). */ play(from?: any, suppressEvents?: boolean): Animation; - /** Gets or sets the animations's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ + /** + * Gets or sets the animations's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is at the + * halfway point, and 1 is at the end (complete). + */ progress(): number; progress(value: number, suppressEvents?: boolean): Animation; @@ -67,7 +84,10 @@ declare namespace gsap { startTime(): number; startTime(value: number): Animation; - /** Gets or sets the local position of the playhead (essentially the current time), described in seconds (or frames for frames-based animations) which will never be less than 0 or greater than the animation's duration. */ + /** + * Gets or sets the local position of the playhead (essentially the current time), described in seconds (or frames for frames-based animations) which will never be less than 0 or greater + * than the animation's duration. + */ time(): number; time(value: number, suppressEvents?: boolean): Animation; @@ -79,7 +99,10 @@ declare namespace gsap { totalDuration(): number; totalDuration(value: number): Animation; - /** Gets or sets the animation's total progress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ + /** + * Gets or sets the animation's total progress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is at + * the halfway point, and 1 is at the end (complete). + */ totalProgress(): number; totalProgress(value: number, suppressEvents?: boolean): Animation; diff --git a/types/gsap/Ease.d.ts b/types/gsap/Ease.d.ts index ea2d7e1d84..56603b5ed1 100644 --- a/types/gsap/Ease.d.ts +++ b/types/gsap/Ease.d.ts @@ -1,52 +1,51 @@ declare namespace gsap { - export class Ease { + class Ease { constructor(func?: () => void, extraParams?: any[], type?: number, power?: number); /** Translates the tween's progress ratio into the corresponding ease ratio. */ getRatio(p: number): number; } - export class EaseLookup { - static find(name: string): Ease; + interface EaseLookup { + find(name: string): Ease; } - export class Back extends Ease { + class Back extends Ease { static easeIn: Back; static easeInOut: Back; static easeOut: Back; config(overshoot: number): Elastic; - } - export class Bounce extends Ease { + class Bounce extends Ease { static easeIn: Bounce; static easeInOut: Bounce; static easeOut: Bounce; } - export class Circ extends Ease { + class Circ extends Ease { static easeIn: Circ; static easeInOut: Circ; static easeOut: Circ; } - export class Cubic extends Ease { + class Cubic extends Ease { static easeIn: Cubic; static easeInOut: Cubic; static easeOut: Cubic; } - export class Elastic extends Ease { + class Elastic extends Ease { static easeIn: Elastic; static easeInOut: Elastic; static easeOut: Elastic; config(amplitude: number, period: number): Elastic; } - export class Expo extends Ease { + class Expo extends Ease { static easeIn: Expo; static easeInOut: Expo; static easeOut: Expo; } - export class Linear extends Ease { + class Linear extends Ease { static ease: Linear; static easeIn: Linear; static easeInOut: Linear; @@ -54,60 +53,59 @@ declare namespace gsap { static easeOut: Linear; } - export class Quad extends Ease { + class Quad extends Ease { static easeIn: Quad; static easeInOut: Quad; static easeOut: Quad; } - export class Quart extends Ease { + class Quart extends Ease { static easeIn: Quart; static easeInOut: Quart; static easeOut: Quart; } - export class Quint extends Ease { + class Quint extends Ease { static easeIn: Quint; static easeInOut: Quint; static easeOut: Quint; } - export class Sine extends Ease { + class Sine extends Ease { static easeIn: Sine; static easeInOut: Sine; static easeOut: Sine; } - export class SlowMo extends Ease { + class SlowMo extends Ease { static ease: SlowMo; config(linearRatio: number, power: number, yoyoMode: boolean): SlowMo; } - export class SteppedEase extends Ease { + class SteppedEase extends Ease { constructor(staps: number); config(steps: number): SteppedEase; } - export interface RoughEaseConfig { + interface RoughEaseConfig { clamp?: boolean; points?: number; randomize?: boolean; strength?: number; - taper?: 'in' | 'out' | 'both' | 'none'; + taper?: "in" | "out" | "both" | "none"; template?: Ease; } - export class RoughEase extends Ease { + class RoughEase extends Ease { static ease: RoughEase; constructor(vars: RoughEaseConfig); config(steps?: number): RoughEase; } - - export var Power0: typeof Linear; - export var Power1: typeof Quad; - export var Power2: typeof Cubic; - export var Power3: typeof Quart; - export var Power4: typeof Quint; - export var Strong: typeof Quint; + const Power0: typeof Linear; + const Power1: typeof Quad; + const Power2: typeof Cubic; + const Power3: typeof Quart; + const Power4: typeof Quint; + const Strong: typeof Quint; } diff --git a/types/gsap/Plugins.d.ts b/types/gsap/Plugins.d.ts index d7ceca7bf8..3d6e3db73e 100644 --- a/types/gsap/Plugins.d.ts +++ b/types/gsap/Plugins.d.ts @@ -1,15 +1,15 @@ declare namespace gsap { - export interface BezierPlugin extends TweenPlugin { + interface BezierPlugin extends TweenPlugin { bezierThrough(values: any[], curviness?: number, quadratic?: boolean, correlate?: string, prepend?: {}, calcDifs?: boolean): {}; cubicToQuadratic(a: number, b: number, c: number, d: number): any[]; quadraticToCubic(a: number, b: number, c: number): {}; } - export interface CSSRulePlugin extends TweenPlugin { + interface CSSRulePlugin extends TweenPlugin { getRule(selector: string): {}; } - export interface TweenPlugin { + interface TweenPlugin { activate(plugins: any[]): boolean; } } diff --git a/types/gsap/Timeline.d.ts b/types/gsap/Timeline.d.ts index 9d14b2d4c5..60292e354d 100644 --- a/types/gsap/Timeline.d.ts +++ b/types/gsap/Timeline.d.ts @@ -1,8 +1,11 @@ declare namespace gsap { - export type Timeline = SimpleTimeline | TimelineLite | TimelineMax; + type Timeline = SimpleTimeline | TimelineLite | TimelineMax; - export class SimpleTimeline extends Animation { - /** SimpleTimeline is the base class for TimelineLite and TimelineMax, providing the most basic timeline () => voidality and it is used for the root timelines in TweenLite but is only intended for internal use in the GreenSock tweening platform. It is meant to be very fast and lightweight. */ + class SimpleTimeline extends Animation { + /** + * SimpleTimeline is the base class for TimelineLite and TimelineMax, providing the most basic timeline () => voidality and it is used for the root timelines in TweenLite but is only + * intended for internal use in the GreenSock tweening platform. It is meant to be very fast and lightweight. + */ constructor(vars?: any); /** If true, child tweens/timelines will be removed as soon as they complete. */ @@ -18,7 +21,7 @@ declare namespace gsap { render(time: number, suppressEvents?: boolean, force?: boolean): SimpleTimeline; } - export class TimelineLite extends SimpleTimeline { + class TimelineLite extends SimpleTimeline { constructor(vars?: {}); /** Adds a tween, timeline, callback, or label (or an array of them) to the timeline. */ @@ -30,7 +33,10 @@ declare namespace gsap { /** Inserts a special callback that pauses playback of the timeline at a particular time or label. */ addPause(position?: any, callback?: () => void, params?: any[], scope?: any): TimelineLite; - /** Adds a callback to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.delayedCall(...) ) but with less code. */ + /** + * Adds a callback to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as + * add( TweenLite.delayedCall(...) ) but with less code. + */ call(callback: () => void, params?: any[], scope?: any, position?: any): TimelineLite; /** Empties the timeline of all tweens, timelines, and callbacks (and optionally labels too). */ @@ -39,10 +45,16 @@ declare namespace gsap { /** Returns the time at which the animation will finish according to the parent timeline's local time. */ endTime(includeRepeats?: boolean): number; - /** Seamlessly transfers all tweens, timelines, and [optionally] delayed calls from the root timeline into a new TimelineLite so that you can perform advanced tasks on a seemingly global basis without affecting tweens/timelines that you create after the export. */ + /** + * Seamlessly transfers all tweens, timelines, and [optionally] delayed calls from the root timeline into a new TimelineLite so that you can perform advanced tasks on a seemingly global + * basis without affecting tweens/timelines that you create after the export. + */ static exportRoot(vars?: {}, omitDelayedCalls?: boolean): TimelineLite; - /** Adds a TweenLite.from() tween to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.from(...) ) but with less code. */ + /** + * Adds a TweenLite.from() tween to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as + * add( TweenLite.from(...) ) but with less code. + */ from(target: {}, duration: number, vars: {}, position?: any): TimelineLite; /** Adds a TweenLite.fromTo() tween to the end of the timeline - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.fromTo(...) ) but with less code. */ @@ -57,7 +69,10 @@ declare namespace gsap { /** Returns the tweens of a particular object that are inside this timeline. */ getTweensOf(target: {}, nested?: boolean): Tween[]; - /** Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ + /** + * Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded + * starting values. + */ invalidate(): TimelineLite; /** Returns the most recently added child tween/timeline/callback regardless of its position in the timeline. */ @@ -72,22 +87,65 @@ declare namespace gsap { /** Jumps to a specific time (or label) without affecting whether or not the instance is paused or reversed. */ seek(position: string | number, supressEvents: boolean): TimelineLite; - /** Adds a zero-duration tween to the end of the timeline (or elsewhere using the "position" parameter) that sets values immediately (when the virtual playhead reaches that position on the timeline) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.to(target, 0, {...}) ) but with less code. */ + /** + * Adds a zero-duration tween to the end of the timeline (or elsewhere using the "position" parameter) that sets values immediately (when the virtual playhead reaches that + * position on the timeline) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.to(target, 0, {...}) ) but with less code. + */ set(target: {}, vars: {}, position?: any): TimelineLite; /** Shifts the startTime of the timeline's children by a certain amount and optionally adjusts labels too. */ shiftChildren(amount: number, adjustLabels?: boolean, ignoreBeforeTime?: number): TimelineLite; - /** Tweens an array of targets from a common set of destination values (using the current values as the destination), but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ - staggerFrom(targets: any, duration: number, vars: {}, stagger?: number, position?: any, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteScope?: any): TimelineLite; + /** + * Tweens an array of targets from a common set of destination values (using the current values as the destination), but staggers their start times by a specified amount of time, + * creating an evenly-spaced sequence with a surprisingly small amount of code. + */ + staggerFrom( + targets: any, + duration: number, + vars: {}, + stagger?: number, + position?: any, + onCompleteAll?: () => void, + onCompleteAllParams?: any[], + onCompleteScope?: any + ): TimelineLite; - /** Tweens an array of targets from and to a common set of values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ - staggerFromTo(targets: any, duration: number, fromVars: {}, toVars: {}, stagger?: number, position?: any, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; + /** + * Tweens an array of targets from and to a common set of values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly + * small amount of code. + */ + staggerFromTo( + targets: any, + duration: number, + fromVars: {}, + toVars: {}, + stagger?: number, + position?: any, + onCompleteAll?: () => void, + onCompleteAllParams?: any[], + onCompleteAllScope?: any + ): TimelineLite; - /** Tweens an array of targets to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ - staggerTo(targets: any, duration: number, vars: {}, stagger: number, position?: any, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; + /** + * Tweens an array of targets to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly + * small amount of code. + */ + staggerTo( + targets: any, + duration: number, + vars: {}, + stagger: number, + position?: any, + onCompleteAll?: () => void, + onCompleteAllParams?: any[], + onCompleteAllScope?: any + ): TimelineLite; - /** Adds a TweenLite.to() tween to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.to(...) ) but with less code. */ + /** + * Adds a TweenLite.to() tween to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as + * add( TweenLite.to(...) ) but with less code. + */ to(target: {}, duration: number, vars: {}, position?: any): TimelineLite; usesFrames(): boolean; @@ -95,7 +153,7 @@ declare namespace gsap { useFrames(): boolean; } - export class TimelineMax extends TimelineLite { + class TimelineMax extends TimelineLite { constructor(vars?: {}); addCallback(callback: () => void, position: any, params?: any[], scope?: any): TimelineMax; @@ -104,7 +162,7 @@ declare namespace gsap { getActive(nested?: boolean, tweens?: boolean, timelines?: boolean): Tween | Timeline[]; getLabelAfter(time: number): string; getLabelBefore(time: number): string; - getLabelsArray(): Array<{ name: string; time: number; }>; + getLabelsArray(): Array<{ name: string; time: number }>; removeCallback(callback: () => void, timeOrLabel?: any): TimelineMax; removePause(position: any): TimelineMax; repeat(): number; diff --git a/types/gsap/Tween.d.ts b/types/gsap/Tween.d.ts index b11260ef4c..11de164f00 100644 --- a/types/gsap/Tween.d.ts +++ b/types/gsap/Tween.d.ts @@ -1,6 +1,6 @@ declare namespace gsap { - export type Tween = TweenLite | TweenMax; - export class TweenLite extends Animation { + type Tween = TweenLite | TweenMax; + class TweenLite extends Animation { constructor(target: any, duration: number, vars: any); /** Provides An easy way to change the default easing equation. */ @@ -15,22 +15,37 @@ declare namespace gsap { /** Target object (or array of objects) whose properties the tween affects. */ readonly target: any; - /** The object that dispatches a "tick" event each time the engine updates, making it easy for you to add your own listener(s) to run custom logic after each update (great for game developers). */ + /** + * The object that dispatches a "tick" event each time the engine updates, making it easy for you to add your own listener(s) to run custom logic after each update + * (great for game developers). + */ static ticker: any; /** Provides a simple way to call a () => void after a set amount of time (or frames). */ static delayedCall(delay: number, callback: () => void, params?: any[], scope?: any, useFrames?: boolean): TweenLite; - /** Static method for creating a TweenLite instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for doing things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere. */ + /** + * Static method for creating a TweenLite instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for doing + * things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere. + */ static from(target: any, duration: number, vars: any): TweenLite; - /** Static method for creating a TweenLite instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's current values at one end or the other). */ + /** + * Static method for creating a TweenLite instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's + * current values at one end or the other). + */ static fromTo(target: any, duration: number, fromVars: any, toVars: any): TweenLite; - /** Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a few seconds after the tween completes. */ + /** + * Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a few + * seconds after the tween completes. + */ static getTweensOf(target: any, onlyActive?: boolean): TweenLite[]; - /** [override] Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ + /** + * [override] Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously + * recorded starting values. + */ invalidate(): TweenLite; /** Immediately kills all of the delayedCalls to a particular () => void. */ @@ -42,7 +57,10 @@ declare namespace gsap { /** Permits you to control what happens when too much time elapses between two ticks (updates) of the engine, adjusting the core timing mechanism to compensate and avoid "jumps". */ static lagSmoothing(threshold: number, adjustedLag: number): void; - /** Forces a render of all active tweens which can be useful if, for example, you set up a bunch of from() tweens and then you need to force an immediate render (even of "lazy" tweens) to avoid a brief delay before things render on the very next tick. */ + /** + * Forces a render of all active tweens which can be useful if, for example, you set up a bunch of from() tweens and then you need to force an immediate render (even of "lazy" tweens) to + * avoid a brief delay before things render on the very next tick. + */ static render(): void; /** Immediately sets properties of the target accordingly - essentially a zero-duration to() tween with a more intuitive name. */ @@ -52,26 +70,35 @@ declare namespace gsap { static to(target: any, duration: number, vars: any): TweenLite; } - export class TweenMax extends TweenLite { + class TweenMax extends TweenLite { constructor(target: {}, duration: number, vars: {}); /** Provides a simple way to call a () => void after a set amount of time (or frames). */ static delayedCall(delay: number, callback: () => void, params?: any[], scope?: {}, useFrames?: boolean): TweenMax; - /** Static method for creating a TweenMax instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for doing things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere. */ + /** + * Static method for creating a TweenMax instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for + * doing things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere. + */ static from(target: {}, duration: number, vars: {}): TweenMax; - /** Static method for creating a TweenMax instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's current values at one end or the other). */ + /** + * Static method for creating a TweenMax instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's + * current values at one end or the other). + */ static fromTo(target: {}, duration: number, fromVars: {}, toVars: {}): TweenMax; /** Returns an array containing all tweens (and optionally timelines too, excluding the root timelines). */ static getAllTweens(includeTimelines?: boolean): Tween[]; - /** Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a few seconds after the tween completes. */ + /** + * Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a + * few seconds after the tween completes. + */ static getTweensOf(target: {}): Tween[]; /** Gets or sets the global timeScale which is a multiplier that affects ALL animations equally. This is a great way to globally speed up or slow down all animations at once. */ - static globalTimeScale(value: number): void; + static globalTimeScale(value?: number): number; /** Reports whether or not a particular object is actively tweening. */ static isTweening(target: {}): boolean; @@ -91,7 +118,10 @@ declare namespace gsap { /** Pauses all tweens and/or delayedCalls/callbacks and/or timelines. */ static pauseAll(tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; - /** Gets or sets the tween's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is halfway complete, and 1 is complete. */ + /** + * Gets or sets the tween's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is halfway + * complete, and 1 is complete. + */ repeat(): number; repeat(value: number): TweenMax; @@ -105,14 +135,48 @@ declare namespace gsap { /** Immediately sets properties of the target accordingly - essentially a zero-duration to() tween with a more intuitive name. */ static set(target: {}, vars: {}): TweenMax; - /** Tweens an array of targets from a common set of destination values (using the current values as the destination), but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ - static staggerFrom(targets: any, duration: number, vars: {}, stagger: number, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + /** + * Tweens an array of targets from a common set of destination values (using the current values as the destination), but staggers their start times by a specified amount of time, creating + * an evenly-spaced sequence with a surprisingly small amount of code. + */ + static staggerFrom( + targets: any, + duration: number, + vars: {}, + stagger: number, + onCompleteAll?: () => void, + onCompleteAllParams?: any[], + onCompleteAllScope?: any + ): any[]; - /** Tweens an array of targets from a common set of destination values to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ - static staggerFromTo(targets: any, duration: number, fromVars: {}, toVars: {}, stagger: number, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + /** + * Tweens an array of targets from a common set of destination values to a common set of destination values, but staggers their start times by a specified amount of time, creating an + * evenly-spaced sequence with a surprisingly small amount of code. + */ + static staggerFromTo( + targets: any, + duration: number, + fromVars: {}, + toVars: {}, + stagger: number, + onCompleteAll?: () => void, + onCompleteAllParams?: any[], + onCompleteAllScope?: any + ): any[]; - /** Tweens an array of targets to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ - static staggerTo(targets: any, duration: number, vars: {}, stagger: number, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + /** + * Tweens an array of targets to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly + * small amount of code. + */ + static staggerTo( + targets: any, + duration: number, + vars: {}, + stagger: number, + onCompleteAll?: () => void, + onCompleteAllParams?: any[], + onCompleteAllScope?: any + ): any[]; /** Static method for creating a TweenMax instance that animates to the specified destination values (from the current values). */ static to(target: {}, duration: number, vars: TweenConfig): TweenMax; diff --git a/types/gsap/TweenConfig.d.ts b/types/gsap/TweenConfig.d.ts index 33cde9c6ae..38b00404e6 100644 --- a/types/gsap/TweenConfig.d.ts +++ b/types/gsap/TweenConfig.d.ts @@ -1,10 +1,11 @@ declare namespace gsap { - export interface TweenConfig { - + interface TweenConfig { /** Any tweenable property */ [p: string]: any; - /** Amount of delay in seconds (or frames for frames-based tweens) before the animation should begin.*/ + /** + * Amount of delay in seconds (or frames for frames-based tweens) before the animation should begin. + */ delay?: number; /** Ease (or () => void or String) - You can choose from various eases to control the rate of change during the animation, giving it a specific "feel". */ @@ -15,7 +16,10 @@ declare namespace gsap { /** If true, the tween will pause itself immediately upon creation. */ paused?: boolean; - /** Controls how (and if) other tweens of the same target are overwritten. There are several modes to choose from, but "auto" is the default (although you can change the default mode using theTweenLite.defaultOverwrite property) */ + /** + * Controls how (and if) other tweens of the same target are overwritten. There are several modes to choose from, but "auto" is the default (although you can change the default mode using + * theTweenLite.defaultOverwrite property) + */ overwrite?: string | number; /** A () => void that should be called when the animation has completed. */ @@ -27,7 +31,11 @@ declare namespace gsap { /** Defines the scope of the onComplete () => void (what "this" refers to inside that () => void). */ onCompleteScope?: {}; - /** Normally when you create a tween, it begins rendering on the very next frame (update cycle) unless you specify a delay. However, if you prefer to force the tween to render immediately when it is created, setimmediateRender to true. Or to prevent a from() from rendering immediately, set immediateRender to false. By default, from() tweens set immediateRender to true. */ + /** + * Normally when you create a tween, it begins rendering on the very next frame (update cycle) unless you specify a delay. However, if you prefer to force the tween to render + * immediately when it is created, setimmediateRender to true. Or to prevent a from() from rendering immediately, set immediateRender to false. By default, from() tweens set + * immediateRender to true. + */ immediateRender?: boolean; /** A () => void that should be called when the tween has reached its beginning again from the reverse direction. */ @@ -57,10 +65,19 @@ declare namespace gsap { /** Defines the scope of the onUpdate () => void (what "this" refers to inside that () => void). */ onUpdateScope?: {}; - /** If useFrames is true, the tweens's timing will be based on frames instead of seconds because it is intially added to the root frames-based timeline. This causes both its duration and delay to be based on frames. An animations's timing mode is always determined by its parent timeline. */ + /** + * If useFrames is true, the tweens's timing will be based on frames instead of seconds because it is intially added to the root frames-based timeline. This causes both its duration and + * delay to be based on frames. An animations's timing mode is always determined by its parent timeline. + */ useFrames?: boolean; - /** When a tween renders for the very first time and reads its starting values, GSAP will automatically "lazy render" that particular tick by default, meaning it will try to delay the rendering (writing of values) until the very end of the "tick" cycle which can improve performance because it avoids the read/write/read/write layout thrashing that some browsers do. If you would like to disable lazy rendering for a particular tween, you can set lazy:false. Or, since zero-duration tweens do not lazy-render by default, you can specifically give it permission to lazy-render by setting lazy:true like TweenLite.set(element, {opacity:0, lazy:true});. In most cases, you won't need to set lazy. */ + /** + * When a tween renders for the very first time and reads its starting values, GSAP will automatically "lazy render" that particular tick by default, meaning it will try to delay the + * rendering (writing of values) until the very end of the "tick" cycle which can improve performance because it avoids the read/write/read/write layout thrashing that some browsers do. + * + * If you would like to disable lazy rendering for a particular tween, you can set lazy:false. Or, since zero-duration tweens do not lazy-render by default, you can specifically give it + * permission to lazy-render by setting lazy:true like TweenLite.set(element, {opacity:0, lazy:true});. In most cases, you won't need to set lazy. + */ lazy?: boolean; /** A () => void that should be called when the tween gets overwritten by another tween. */ diff --git a/types/gsap/index.d.ts b/types/gsap/index.d.ts index 77d589603a..5e3081cc6a 100644 --- a/types/gsap/index.d.ts +++ b/types/gsap/index.d.ts @@ -1,6 +1,10 @@ -// Type definitions for GSAP 1.19 +// Type definitions for GSAP 1.20.6 // Project: http://greensock.com/ -// Definitions by: VILIC VANE , Robert S , Richard Fox , Philip Bulley +// Definitions by: VILIC VANE , +// Robert S , +// Richard Fox , +// Philip Bulley , +// Leonardo Melo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -10,6 +14,6 @@ /// /// -declare module 'gsap' { +declare module "gsap" { export = gsap; } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index dcde50413d..167d6532d3 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -2976,6 +2976,21 @@ declare namespace Highcharts { * @since 3.0.1 */ printChart?: string; + /** + * The text for the label for the "from" input box in the range selector. + * @default 'From' + */ + rangeSelectorFrom?: string; + /** + * The text for the label for the "to" input box in the range selector. + * @default 'To' + */ + rangeSelectorTo?: string; + /** + * The text for the label for the range selector buttons. + * @default 'Zoom' + */ + rangeSelectorZoom?: String; /** * The text for the label appearing when a chart is zoomed. * @default 'Reset zoom' diff --git a/types/hosted-git-info/hosted-git-info-tests.ts b/types/hosted-git-info/hosted-git-info-tests.ts new file mode 100644 index 0000000000..0e4ef56cb7 --- /dev/null +++ b/types/hosted-git-info/hosted-git-info-tests.ts @@ -0,0 +1,22 @@ +import info = require("hosted-git-info"); + +info.fromUrl(''); +const result = info.fromUrl('', {}); + +result.hashformat(''); +result.hash(); +result.ssh({}); +result.sshurl({}); +result.browse('', '', {}); +result.browse('', {}); +result.browse({}); +result.docs({}); +result.bugs({}); +result.https({}); +result.git({}); +result.shortcut({}); +result.path({}); +result.tarball({}); +result.file('', {}); +result.getDefaultRepresentation(); +result.toString({}); diff --git a/types/hosted-git-info/index.d.ts b/types/hosted-git-info/index.d.ts new file mode 100644 index 0000000000..a8e5cbdeda --- /dev/null +++ b/types/hosted-git-info/index.d.ts @@ -0,0 +1,96 @@ +// Type definitions for hosted-git-info 2.7 +// Project: https://github.com/npm/hosted-git-info +// Definitions by: Jason +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class HostedGitInfo { + host: HostedGitInfo.hosts; + user: string | null; + auth: string | null; + project: string | null; + committish: string | null; + default: string; + opts: HostedGitInfo.Options; + + constructor( + host: HostedGitInfo.hosts, + user: string | null, + auth: string | null, + project: string | null, + committish: string | null, + defaultRepresentation: string, + opts?: HostedGitInfo.Options + ); + + // From git-host-info + + // defaults + sshtemplate: string; + sshurltemplate: string; + browsetemplate: string; + docstemplate: string; + filetemplate: string; + shortcuttemplate: string; + pathtemplate: string; + + pathmatch: RegExp; + protocols_re: RegExp; + hashformat(fragment: string): string; + + // special + protocols: string[]; + domain: string; + bugstemplate: string; + gittemplate: string; + browsefiletemplate: string; + httpstemplate: string; + treepath: string; + tarballtemplate: string; + + // /From git-host-info + + hash(): string; + ssh(opts?: HostedGitInfo.FillOptions): string | undefined; + sshurl(opts?: HostedGitInfo.FillOptions): string | undefined; + browse( + path: string, + fragment: string, + opts?: HostedGitInfo.FillOptions + ): string | undefined; + browse(path: string, opts?: HostedGitInfo.FillOptions): string | undefined; + browse(opts?: HostedGitInfo.FillOptions): string | undefined; + docs(opts?: HostedGitInfo.FillOptions): string | undefined; + bugs(opts?: HostedGitInfo.FillOptions): string | undefined; + https(opts?: HostedGitInfo.FillOptions): string | undefined; + git(opts?: HostedGitInfo.FillOptions): string | undefined; + shortcut(opts?: HostedGitInfo.FillOptions): string | undefined; + path(opts?: HostedGitInfo.FillOptions): string | undefined; + tarball(opts?: HostedGitInfo.FillOptions): string | undefined; + file(path: string, opts?: HostedGitInfo.FillOptions): string | undefined; + getDefaultRepresentation(): string; + toString(opts?: HostedGitInfo.FillOptions): string | undefined; + + static fromUrl( + gitUrl: string, + options?: HostedGitInfo.Options + ): HostedGitInfo; +} + +declare namespace HostedGitInfo { + interface Options { + noCommittish?: boolean; + noGitPlus?: boolean; + } + + interface FillOptions extends Options { + path?: string; + auth?: string; + fragment?: string; + committish?: string; + treepath?: string; + } + + type hosts = 'github' | 'bitbucket' | 'gitlab' | 'gist'; +} + +export = HostedGitInfo; diff --git a/types/hosted-git-info/tsconfig.json b/types/hosted-git-info/tsconfig.json new file mode 100644 index 0000000000..5736539a96 --- /dev/null +++ b/types/hosted-git-info/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", + "hosted-git-info-tests.ts" + ] +} diff --git a/types/hosted-git-info/tslint.json b/types/hosted-git-info/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hosted-git-info/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next-browser-languagedetector/v0/index.d.ts b/types/i18next-browser-languagedetector/v0/index.d.ts index 9d8f58a52a..8b0f6b6317 100644 --- a/types/i18next-browser-languagedetector/v0/index.d.ts +++ b/types/i18next-browser-languagedetector/v0/index.d.ts @@ -28,7 +28,7 @@ declare namespace i18nextBrowserLanguageDetector { interface CustomDetector { name: string; - // todo: Checks paramters type. + // todo: Checks parameters type. cacheUserLanguage(lng: string, options: {}): void; lookup(options: {}): string; } diff --git a/types/ibm_db/ibm_db-tests.ts b/types/ibm_db/ibm_db-tests.ts index 93802c662f..cc896b8d05 100644 --- a/types/ibm_db/ibm_db-tests.ts +++ b/types/ibm_db/ibm_db-tests.ts @@ -10,3 +10,14 @@ ibmdb.open("DATABASE=;HOSTNAME=;UID=db2user;PWD=password;PORT= void): void; - _executeSync(params: any[]): ODBCResult; + _executeSync(params?: any[]): ODBCResult; _executeDirect(sql: string, cb: (err: Error, result: any[]) => void): void; @@ -170,7 +170,7 @@ export class ODBCStatement { execute(cb: (err: Error, result: any[], outparams: any) => void): void; execute(params: any[]): Promise<{result: any[], outparams: any}>; - executeSync(params: any[]): ODBCResult; + executeSync(params?: any[]): ODBCResult; executeDirect(sql: string, cb: (err: Error, result: any[]) => void): void; diff --git a/types/inquirer-npm-name/index.d.ts b/types/inquirer-npm-name/index.d.ts new file mode 100644 index 0000000000..bca64cd7ac --- /dev/null +++ b/types/inquirer-npm-name/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for inquirer-npm-name 3.0 +// Project: https://github.com/SBoudrias/inquirer-npm-name +// Definitions by: manuth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.3 + +import { Inquirer, Answers, Question } from "inquirer"; + +declare function askName(name: string | Question, inquirer: Inquirer): Promise<{ [key: string]: string }>; +export = askName; diff --git a/types/inquirer-npm-name/inquirer-npm-name-tests.ts b/types/inquirer-npm-name/inquirer-npm-name-tests.ts new file mode 100644 index 0000000000..aee1b039d7 --- /dev/null +++ b/types/inquirer-npm-name/inquirer-npm-name-tests.ts @@ -0,0 +1,13 @@ +import inquirer = require("inquirer"); +import askName = require("inquirer-npm-name"); + +// $ExpectType Promise<{ [key: string]: string; }> +askName("moduleName", inquirer); + +// $ExpectType Promise<{ [key: string]: string; }> +askName( + { + name: "moduleName", + message: "Whar's the name of your module?" + }, + inquirer); diff --git a/types/inquirer-npm-name/tsconfig.json b/types/inquirer-npm-name/tsconfig.json new file mode 100644 index 0000000000..99dee30a17 --- /dev/null +++ b/types/inquirer-npm-name/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", + "inquirer-npm-name-tests.ts" + ] +} diff --git a/types/inquirer-npm-name/tslint.json b/types/inquirer-npm-name/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/inquirer-npm-name/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ip/index.d.ts b/types/ip/index.d.ts index c51a8d37f5..ed9ba584bc 100644 --- a/types/ip/index.d.ts +++ b/types/ip/index.d.ts @@ -26,7 +26,7 @@ declare module "ip" { /** * Convert an IP string into a buffer. **/ - export function toBuffer(ip: string, buffer?: number, offset?: number): Buffer; + export function toBuffer(ip: string, buffer?: Buffer, offset?: number): Buffer; /** * Convert an IP buffer into a string. diff --git a/types/ip/ip-tests.ts b/types/ip/ip-tests.ts index 13abf1f4a6..f1fbf4726d 100644 --- a/types/ip/ip-tests.ts +++ b/types/ip/ip-tests.ts @@ -20,3 +20,7 @@ ip.toString(buff); ip.subnet('192.168.1.134', '255.255.255.192'); ip.cidrSubnet('192.168.1.134/26'); ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.134'); +var buf = new Buffer(128); +var offset = 64; +ip.toBuffer('127.0.0.1', buf, offset); +ip.toString(buf, offset, 4); diff --git a/types/jest-axe/index.d.ts b/types/jest-axe/index.d.ts index f16f4e7651..60375e3605 100644 --- a/types/jest-axe/index.d.ts +++ b/types/jest-axe/index.d.ts @@ -82,4 +82,7 @@ declare global { toHaveNoViolations: IToHaveNoViolations; } } + + // axe-core depends on a global Node + interface Node {} } diff --git a/types/jest-axe/tsconfig.json b/types/jest-axe/tsconfig.json index 1889f0045d..887813c869 100644 --- a/types/jest-axe/tsconfig.json +++ b/types/jest-axe/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/jest-axe/tslint.json b/types/jest-axe/tslint.json index 3db14f85ea..4f44991c3c 100644 --- a/types/jest-axe/tslint.json +++ b/types/jest-axe/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false + } +} diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 8451987011..2b378a6048 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -345,7 +345,14 @@ declare namespace jest { } interface ExpectExtendMap { - [key: string]: (this: MatcherUtils, received: any, ...actual: any[]) => { message(): string | (() => string), pass: boolean } | Promise<{ message(): string, pass: boolean }>; + [key: string]: CustomMatcher; + } + + type CustomMatcher = (this: MatcherUtils, received: any, ...actual: any[]) => CustomMatcherResult | Promise; + + interface CustomMatcherResult { + pass: boolean; + message: string | (() => string); } interface SnapshotSerializerOptions { @@ -386,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. @@ -468,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 4082bd9e31..de1ba90456 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -433,6 +433,14 @@ expect.extend({ }; } }); +expect.extend({ + foo(this: jest.MatcherUtils, received: {}, ...actual: Array<{}>) { + return { + message: JSON.stringify(received), + pass: false, + }; + } +}); expect.extend({ async foo(this: jest.MatcherUtils, received: {}, ...actual: Array<{}>) { return { @@ -441,6 +449,14 @@ expect.extend({ }; } }); +expect.extend({ + async foo(this: jest.MatcherUtils, received: {}, ...actual: Array<{}>) { + return { + message: JSON.stringify(received), + pass: false + }; + } +}); expect.extend({ foo(this: jest.MatcherUtils) { const isNot: boolean = this.isNot; @@ -730,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 f3432036cf..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; /** @@ -909,16 +892,29 @@ export interface BinarySchema extends AnySchema { } export interface DateSchema extends AnySchema { + /** + * Specifies that the value must be greater than date. + * 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. + */ + greater(date: 'now' | Date | number | string | Reference): this; + + /** + * Specifies that the value must be less than date. + * 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. + */ + less(date: 'now' | Date | number | string | Reference): this; + /** * 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; + min(date: 'now' | Date | number | string | Reference): this; /** * Specifies the latest date allowed. @@ -926,17 +922,13 @@ export interface DateSchema extends AnySchema { * 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; + max(date: 'now' | Date | number | string | 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; + format(format: string | string[]): this; /** * Requires the string value to be in valid ISO 8601 date format. @@ -978,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; } @@ -1028,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; +} + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- /** @@ -1104,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; /** @@ -1152,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. @@ -1242,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. @@ -1284,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 832858c7e9..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[]; @@ -514,15 +514,28 @@ binSchema = binSchema.length(num); dateSchema = Joi.date(); +dateSchema = dateSchema.greater('now'); +dateSchema = dateSchema.less('now'); +dateSchema = dateSchema.min('now'); +dateSchema = dateSchema.max('now'); + +dateSchema = dateSchema.greater(date); +dateSchema = dateSchema.less(date); dateSchema = dateSchema.min(date); dateSchema = dateSchema.max(date); +dateSchema = dateSchema.greater(str); +dateSchema = dateSchema.less(str); dateSchema = dateSchema.min(str); dateSchema = dateSchema.max(str); +dateSchema = dateSchema.greater(num); +dateSchema = dateSchema.less(num); dateSchema = dateSchema.min(num); dateSchema = dateSchema.max(num); +dateSchema = dateSchema.greater(ref); +dateSchema = dateSchema.less(ref); dateSchema = dateSchema.min(ref); dateSchema = dateSchema.max(ref); @@ -893,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/jquery-formatdatetime/index.d.ts b/types/jquery-formatdatetime/index.d.ts new file mode 100644 index 0000000000..308d58fe7f --- /dev/null +++ b/types/jquery-formatdatetime/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for JQuery formatDateTime 1.1 +// Project: https://github.com/agschwender/jquery.formatDateTime +// Definitions by: Anderson Friaça +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export type Options = Partial<{ + /** + * Names of the months, e.g. January + */ + monthNames: string[]; + + /** + * Shortened names of the months, e.g. Jan + */ + monthNamesShort: string[]; + + /** + * Names of the days, e.g. Sunday + */ + dayNames: string[]; + + /** + * Shortened names of the days, e.g. Sun + */ + dayNamesShort: string[]; + + /** + * Names of the 12-hour clock periods, e.g. AM + */ + ampmNames: string[]; + + /** + * Callback to convert number to ordinal suffix, e.g. 1 to st + */ + getSuffix: ((num: number) => string); + + /** + * Attribute which contains the datetime + */ + attribute: string; + + /** + * Attribute which contains the datetime format + */ + formatAttribute: string; + + /** + * Render dates in UTC instead of local timezone + */ + utc: boolean; +}>; + +declare global { + interface JQuery { + formatDateTime(format: string, options?: Options): JQuery; + } + + interface JQueryStatic { + formatDateTime(format: string, date: Date, options?: Options): string; + } +} diff --git a/types/jquery-formatdatetime/jquery-formatdatetime-tests.ts b/types/jquery-formatdatetime/jquery-formatdatetime-tests.ts new file mode 100644 index 0000000000..fe5949f757 --- /dev/null +++ b/types/jquery-formatdatetime/jquery-formatdatetime-tests.ts @@ -0,0 +1,40 @@ +import { Options } from "jquery-formatdatetime"; + +// basic usage +$('#example').formatDateTime('mm/dd/y g:ii a'); + +const date = new Date('2012/07/05 09:55:03'); + +$.formatDateTime('mm/dd/y g:ii a', date); + +// with options +const options: Options = { + monthNames: [ + 'Janeiro', + 'Fevereiro', + 'Março', + 'Abril', + 'Maio', + 'Junho', + 'Julho', + 'Agosto', + 'Setembro', + 'Outubro', + 'Novembro', + 'Dezembro' + ], + dayNames: [ + 'Domingo', + 'Segunda-Feira', + 'Terça-Feira', + 'Quarta-Feira', + 'Quinta-Feira', + 'Sexta-Feira', + 'Sábado' + ], + ampmNames: ['AM', 'PM'] +}; + +$.formatDateTime('mm/dd/y g:ii a', date, options); + +$('#example').formatDateTime('mm/dd/y g:ii a', options); diff --git a/types/jquery-formatdatetime/tsconfig.json b/types/jquery-formatdatetime/tsconfig.json new file mode 100644 index 0000000000..a6ba781d22 --- /dev/null +++ b/types/jquery-formatdatetime/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery-formatdatetime-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-formatdatetime/tslint.json b/types/jquery-formatdatetime/tslint.json new file mode 100644 index 0000000000..d04fe2e1fa --- /dev/null +++ b/types/jquery-formatdatetime/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} \ No newline at end of file diff --git a/types/json-rpc-random-id/index.d.ts b/types/json-rpc-random-id/index.d.ts new file mode 100644 index 0000000000..14b5ba0ff0 --- /dev/null +++ b/types/json-rpc-random-id/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for json-rpc-random-id 1.0 +// Project: https://github.com/kumavis/json-rpc-random-id#readme +// Definitions by: Micah Riggan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Returns a function that generates a random number + * This number is to be used with web3 rpc + */ +declare function IdIterator(options?: { + max?: number; + start?: number; +}): () => number; + +export = IdIterator; diff --git a/types/json-rpc-random-id/json-rpc-random-id-tests.ts b/types/json-rpc-random-id/json-rpc-random-id-tests.ts new file mode 100644 index 0000000000..c71a7581e8 --- /dev/null +++ b/types/json-rpc-random-id/json-rpc-random-id-tests.ts @@ -0,0 +1,2 @@ +import jsonRPCRandomID = require("json-rpc-random-id"); +const generateId = jsonRPCRandomID(); diff --git a/types/json-rpc-random-id/tsconfig.json b/types/json-rpc-random-id/tsconfig.json new file mode 100644 index 0000000000..c39a0a4e2b --- /dev/null +++ b/types/json-rpc-random-id/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", + "json-rpc-random-id-tests.ts" + ] +} diff --git a/types/json-rpc-random-id/tslint.json b/types/json-rpc-random-id/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-rpc-random-id/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsonquery/index.d.ts b/types/jsonquery/index.d.ts new file mode 100644 index 0000000000..48afcf8d0a --- /dev/null +++ b/types/jsonquery/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for jsonquery 0.1 +// Project: https://github.com/eugeneware/jsonquery +// Definitions by: Jim Buck +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare function jsonquery(query: jsonquery.Query): NodeJS.ReadWriteStream; + +declare namespace jsonquery { + function match(haystack: T, predicate: Query): boolean; + + type Query = BinaryQueryCondition | QueryValue | PathQuery; + + interface OrQueryCondition { + $or: ReadonlyArray>; + } + + interface AndQueryCondition { + $and: ReadonlyArray>; + } + + type BinaryQueryCondition = OrQueryCondition | AndQueryCondition; + + interface BaseCondition

{ + $lt: P; + $lte: P; + $gt: P; + $gte: P; + $mod: [number, number]; + $ne: P; + $in: ReadonlyArray

; + $nin: ReadonlyArray

; + $all: ReadonlyArray

; + $elemMatch: Partial

; + } + + interface PathQuery { + [path: string]: any; + } + + type QueryValue = { + [P in keyof T]?: T[P] | BaseCondition; + }; +} + +export = jsonquery; diff --git a/types/jsonquery/jsonquery-tests.ts b/types/jsonquery/jsonquery-tests.ts new file mode 100644 index 0000000000..904f61d01c --- /dev/null +++ b/types/jsonquery/jsonquery-tests.ts @@ -0,0 +1,120 @@ +import jsonquery = require('jsonquery'); + +interface TestData { + name: string; + number: string; + val: number; + favorites: number[]; + awesome: boolean; + nullify: null; + tree: { + a: number; + b: number; + }; +} + +const testDataInstance: TestData = { + name: "Name 1", + number: "Number 1", + val: 10, + favorites: [10, 20], + awesome: true, + nullify: null, + tree: { + a: 1, + b: 2, + } +}; + +// $ExpectType ReadWriteStream +jsonquery({ number: 'Number 7' }); + +// $ExpectType ReadWriteStream +jsonquery({ number: 'Number 7', val: 70 }); + +// $ExpectType ReadWriteStream +jsonquery({ $or: [ { number: 'Number 7' }, { val: 50 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $and: [ { number: 'Number 7' }, { val: 70 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $or: [ { $and: [ { number: 'Number 7' }, { val: 70 } ] }, { val: 50 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $in: [ 70, 50 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $or: [ { $in: [ 70, 50 ] }, { $in: [ 60, 20 ] } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $gt: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $lt: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $or: [ { $lt: 20 }, { $gt: 950 } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $and: [ { $gt: 970 }, { $gt: 950 } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $ne: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $lte: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $gte: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $all: [50, 60] } }); + +// $ExpectType ReadWriteStream +jsonquery({ tree: { $elemMatch: { a: 1, b: 2 } } }); + +// $ExpectType ReadWriteStream +jsonquery({ 'tree.a': 1 }); + +// $ExpectType ReadWriteStream +jsonquery({ 'tree.a': { $in: [1, 5] } }); + +// $ExpectType ReadWriteStream +jsonquery({ number: /er 7$/ }); + +// $ExpectType ReadWriteStream +jsonquery({ number: { $in: [ /er 7$/, /er 5$/ ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $all: [/^50$/, /^60$/] } }); + +// $ExpectType ReadWriteStream +jsonquery({ tree: { $elemMatch: { a: /^1$/, b: 2 } } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $nin: [ 70, 50 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $mod: [ 7, 1 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $size: 2 } }); + +// $ExpectType ReadWriteStream +jsonquery({ $and: [ { tree: { $exists: true } }, { missing: { $exists: false } } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $not: { number: 'Number 7', val: 70 } }); + +// $ExpectType ReadWriteStream +jsonquery({ number: { $not: { $nin: ['Number 7'] } } }); + +// $ExpectType ReadWriteStream +jsonquery({ foo: { $all: ['bar'] } }); + +// $ExpectType boolean +jsonquery.match(testDataInstance, { val: 7 }); + +// $ExpectType boolean +jsonquery.match(testDataInstance, { 'tree.a': { $in: [1, 5] } }); diff --git a/types/jsonquery/tsconfig.json b/types/jsonquery/tsconfig.json new file mode 100644 index 0000000000..ffb3eb6209 --- /dev/null +++ b/types/jsonquery/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", + "jsonquery-tests.ts" + ] +} diff --git a/types/jsonquery/tslint.json b/types/jsonquery/tslint.json new file mode 100644 index 0000000000..02db66c29b --- /dev/null +++ b/types/jsonquery/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules":{ + "no-unnecessary-generics": false + } +} diff --git a/types/jsonwebtoken/index.d.ts b/types/jsonwebtoken/index.d.ts index f54d3862c9..d1c3aeee5f 100644 --- a/types/jsonwebtoken/index.d.ts +++ b/types/jsonwebtoken/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for jsonwebtoken 7.2.2 +// Type definitions for jsonwebtoken 8.3 // Project: https://github.com/auth0/node-jsonwebtoken // Definitions by: Maxime LUCE , // Daniel Heim , // Brice BERNARD , -// Veli-Pekka Kestilä +// Veli-Pekka Kestilä , +// Daniel Parker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -43,9 +44,9 @@ export interface SignOptions { */ algorithm?: string; keyid?: string; - /** @member {string} - expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ expiresIn?: string | number; - /** @member {string} - expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ notBefore?: string | number; audience?: string | string[]; subject?: string; @@ -67,8 +68,8 @@ export interface VerifyOptions { jwtid?: string; subject?: string; /** - *@deprecated - *@member {string} - Max age of token + * @deprecated + * Max age of token */ maxAge?: string; } @@ -77,28 +78,45 @@ export interface DecodeOptions { complete?: boolean; json?: boolean; } -export type VerifyErrors=JsonWebTokenError | NotBeforeError | TokenExpiredError; -export interface VerifyCallback { - ( - err: VerifyErrors, - decoded: object | string, - ): void; +export type VerifyErrors= JsonWebTokenError | NotBeforeError | TokenExpiredError; +export type VerifyCallback = ( + err: VerifyErrors, + decoded: object | string, +) => void; + +export type SignCallback = ( + err: Error, encoded: string +) => void; + +export interface JwtHeader { + alg: string; + typ?: string; + kid?: string; + jku?: string; + x5u?: string; + x5t?: string; } -export interface SignCallback { - (err: Error, encoded: string): void; -} +export type SigningKeyCallback = ( + err: any, + signingKey?: Secret, +) => void; + +export type GetPublicKeyOrSecret = ( + header: JwtHeader, + callback: SigningKeyCallback +) => void; export type Secret = string | Buffer | { key: string; passphrase: string }; /** * Synchronously sign the given payload into a JSON Web Token string - * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string - * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. - * @param {SignOptions} [options] - Options for the signature - * @returns {String} The JSON Web Token string + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * returns - The JSON Web Token string */ -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions, @@ -106,17 +124,17 @@ export declare function sign( /** * Sign the given payload into a JSON Web Token string - * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string - * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. - * @param {SignOptions} [options] - Options for the signature - * @param {Function} callback - Callback to get the encoded token on + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * callback - Callback to get the encoded token on */ -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, callback: SignCallback, ): void; -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, options: SignOptions, @@ -125,16 +143,12 @@ export declare function sign( /** * Synchronously verify given token using a secret or a public key to get a decoded token - * @param {String} token - JWT string to verify - * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. - * @param {VerifyOptions} [options] - Options for the verification - * @returns The decoded token. + * token - JWT string to verify + * secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * [options] - Options for the verification + * returns - The decoded token. */ -export declare function verify( - token: string, - secretOrPublicKey: string | Buffer, -): object | string; -export declare function verify( +export function verify( token: string, secretOrPublicKey: string | Buffer, options?: VerifyOptions, @@ -142,31 +156,32 @@ export declare function verify( /** * Asynchronously verify given token using a secret or a public key to get a decoded token - * @param {String} token - JWT string to verify - * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. - * @param {VerifyOptions} [options] - Options for the verification - * @param {Function} callback - Callback to get the decoded token on + * token - JWT string to verify + * secretOrPublicKey - A string or buffer containing either the secret for HMAC algorithms, + * or the PEM encoded public key for RSA and ECDSA. If jwt.verify is called asynchronous, + * secretOrPublicKey can be a function that should fetch the secret or public key + * [options] - Options for the verification + * callback - Callback to get the decoded token on */ -export declare function verify( +export function verify( token: string, - secretOrPublicKey: string | Buffer, + secretOrPublicKey: string | Buffer | GetPublicKeyOrSecret, callback?: VerifyCallback, ): void; -export declare function verify( +export function verify( token: string, - secretOrPublicKey: string | Buffer, + secretOrPublicKey: string | Buffer | GetPublicKeyOrSecret, options?: VerifyOptions, callback?: VerifyCallback, ): void; /** * Returns the decoded payload without verifying if the signature is valid. - * @param {String} token - JWT string to decode - * @param {DecodeOptions} [options] - Options for decoding - * @returns {Object} The decoded Token + * token - JWT string to decode + * [options] - Options for decoding + * returns - The decoded Token */ -export declare function decode( +export function decode( token: string, options?: DecodeOptions, ): null | { [key: string]: any } | string; - diff --git a/types/jsonwebtoken/jsonwebtoken-tests.ts b/types/jsonwebtoken/jsonwebtoken-tests.ts index f20fbba5cc..5884ff6d63 100644 --- a/types/jsonwebtoken/jsonwebtoken-tests.ts +++ b/types/jsonwebtoken/jsonwebtoken-tests.ts @@ -7,10 +7,10 @@ import jwt = require("jsonwebtoken"); import fs = require("fs"); -var token: string; -var cert: Buffer; +let token: string; +let cert: Buffer; -interface ITestObject { +interface TestObject { foo: string; } @@ -44,10 +44,10 @@ const secret = { key: privKey.toString(), passphrase: "keypwd" }; token = jwt.sign(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case // sign asynchronously -jwt.sign(testObject, cert, { algorithm: "RS256" }, function( +jwt.sign(testObject, cert, { algorithm: "RS256" }, ( err: Error, token: string, -) { +) => { console.log(token); }); @@ -56,57 +56,70 @@ jwt.sign(testObject, cert, { algorithm: "RS256" }, function( * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ // verify a token symmetric -jwt.verify(token, "shhhhh", function(err, decoded) { - const result = decoded as ITestObject; +jwt.verify(token, "shhhhh", (err, decoded) => { + const result = decoded as TestObject; console.log(result.foo); // bar }); // use external time for verifying -jwt.verify(token, 'shhhhh', { clockTimestamp: 1 }, function(err, decoded) { - const result = decoded as ITestObject +jwt.verify(token, 'shhhhh', { clockTimestamp: 1 }, (err, decoded) => { + const result = decoded as TestObject; - console.log(result.foo) // bar + console.log(result.foo); // bar }); // invalid token -jwt.verify(token, "wrong-secret", function(err, decoded) { +jwt.verify(token, "wrong-secret", (err, decoded) => { // err // decoded undefined }); // verify a token asymmetric cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, function(err, decoded) { - const result = decoded as ITestObject; +jwt.verify(token, cert, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// verify a token assymetric with async key fetch function +function getKey(header: jwt.JwtHeader, callback: jwt.SigningKeyCallback) { + cert = fs.readFileSync("public.pem"); + + callback(null, cert); +} + +jwt.verify(token, getKey, (err, decoded) => { + const result = decoded as TestObject; console.log(result.foo); // bar }); // verify audience cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { audience: "urn:foo" }, function(err, decoded) { +jwt.verify(token, cert, { audience: "urn:foo" }, (err, decoded) => { // if audience mismatch, err == invalid audience }); // verify issuer cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { audience: "urn:foo", issuer: "urn:issuer" }, function( +jwt.verify(token, cert, { audience: "urn:foo", issuer: "urn:issuer" }, ( err, decoded, -) { +) => { // if issuer mismatch, err == invalid issuer }); // verify algorithm cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { algorithms: ["RS256"] }, function(err, decoded) { +jwt.verify(token, cert, { algorithms: ["RS256"] }, (err, decoded) => { // if algorithm mismatch, err == invalid algorithm }); // verify without expiration check cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) { +jwt.verify(token, cert, { ignoreExpiration: true }, (err, decoded) => { // if ignoreExpration == false and token is expired, err == expired token }); @@ -114,7 +127,7 @@ jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) { * jwt.decode * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken */ -var decoded = jwt.decode(token); +let decoded = jwt.decode(token); decoded = jwt.decode(token, { complete: false }); diff --git a/types/jsonwebtoken/tslint.json b/types/jsonwebtoken/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/jsonwebtoken/tslint.json +++ b/types/jsonwebtoken/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/just-debounce-it/index.d.ts b/types/just-debounce-it/index.d.ts new file mode 100644 index 0000000000..248f6a27f8 --- /dev/null +++ b/types/just-debounce-it/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for just-debounce-it 1.1 +// Project: https://github.com/angus-c/just#readme +// Definitions by: Aziz Khambati +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +type ArgumentTypes = F extends (...args: infer A) => any ? A : never; + +/*~ This declaration specifies that the function + *~ is the exported object from the file + */ +export = debounce; + +declare function debounce( + fn: T, + wait?: 0, + callFirst?: boolean +): T; + +declare function debounce( + fn: T, + wait: number, + callFirst: true +): T; + +declare function debounce( + fn: T, + wait: number, + callFirst?: false +): (...args: ArgumentTypes) => void; diff --git a/types/just-debounce-it/just-debounce-it-tests.ts b/types/just-debounce-it/just-debounce-it-tests.ts new file mode 100644 index 0000000000..32dd33c9e7 --- /dev/null +++ b/types/just-debounce-it/just-debounce-it-tests.ts @@ -0,0 +1,23 @@ +import debounce = require("just-debounce-it"); + +const doThings = () => 1; + +const num: number = debounce(doThings)(); +const num2: number = debounce(doThings, 0)(); +const num3: number = debounce(doThings, 0, true)(); +const num4: number = debounce(doThings, 0, false)(); +const num5: number = debounce(doThings, 1000, true)(); + +// $ExpectType void +debounce(doThings, 1000)(); + +const exclaim = (a: string) => a + '!'; + +const str: string = debounce(exclaim)('hey'); +const str2: string = debounce(exclaim, 0)('hi'); +const str3: string = debounce(exclaim, 0, true)('hi'); +const str4: string = debounce(exclaim, 0, false)('hi'); +const str5: string = debounce(exclaim, 1000, true)('hooray'); + +// $ExpectType void +debounce(exclaim, 1000)('hello'); diff --git a/types/just-debounce-it/tsconfig.json b/types/just-debounce-it/tsconfig.json new file mode 100644 index 0000000000..d1a7dbd8b0 --- /dev/null +++ b/types/just-debounce-it/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", + "just-debounce-it-tests.ts" + ] +} diff --git a/types/just-debounce-it/tslint.json b/types/just-debounce-it/tslint.json new file mode 100644 index 0000000000..5bc412fb1e --- /dev/null +++ b/types/just-debounce-it/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false + } +} diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 4d9b1b25f5..5f9f3a7d6c 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Knex.js 0.14 +// Type definitions for Knex.js 0.15 // Project: https://github.com/tgriesser/knex // Definitions by: Qubo // Pablo Rodríguez @@ -14,13 +14,13 @@ import events = require("events"); import stream = require ("stream"); import Bluebird = require("bluebird"); -type Callback = Function; -type Client = Function; -type Value = string | number | boolean | Date | Array | Array | Array | Array | Buffer | Knex.Raw; -type ValueMap = { [key: string]: Value | Knex.QueryBuilder }; +type Callback = (...args: any[]) => void; +type Client = (...args: any[]) => void; +type Value = string | number | boolean | Date | string[] | number[] | Date[] | boolean[] | Buffer | Knex.Raw; +interface ValueMap { [key: string]: Value | Knex.QueryBuilder; } type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string }; type TableName = string | Knex.Raw | Knex.QueryBuilder; -type Identifier = { [alias: string]: string }; +interface Identifier { [alias: string]: string; } interface Knex extends Knex.QueryInterface { (tableName?: TableName | Identifier): Knex.QueryBuilder; @@ -29,7 +29,7 @@ interface Knex extends Knex.QueryInterface { raw: Knex.RawBuilder; transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; - destroy(callback: Function): void; + destroy(callback: (...args: any[]) => void): void; destroy(): Bluebird; batchInsert(tableName: TableName, data: any[], chunkSize?: number): Knex.QueryBuilder; schema: Knex.SchemaBuilder; @@ -39,7 +39,7 @@ interface Knex extends Knex.QueryInterface { migrate: Knex.Migrator; seed: any; fn: Knex.FunctionHelper; - on(eventName: string, callback: Function): Knex.QueryBuilder; + on(eventName: string, callback: (...args: any[]) => void): Knex.QueryBuilder; } declare function Knex(config: Knex.Config): Knex; @@ -138,18 +138,18 @@ declare namespace Knex { // Aggregation count(...columnNames: string[]): QueryBuilder; - count(columnName: Record | Knex.Raw): QueryBuilder; - countDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + count(columnName: Record | Raw): QueryBuilder; + countDistinct(columnName: string | Record | Raw): QueryBuilder; min(columnName: string, ...columnNames: string[]): QueryBuilder; - min(columnName: Record | Knex.Raw): QueryBuilder; + min(columnName: Record | Raw): QueryBuilder; max(columnName: string, ...columnNames: string[]): QueryBuilder; - max(columnName: Record | Knex.Raw): QueryBuilder; + max(columnName: Record | Raw): QueryBuilder; sum(columnName: string, ...columnNames: string[]): QueryBuilder; - sum(columnName: Record | Knex.Raw): QueryBuilder; - sumDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + sum(columnName: Record | Raw): QueryBuilder; + sumDistinct(columnName: string | Record | Raw): QueryBuilder; avg(columnName: string, ...columnNames: string[]): QueryBuilder; - avg(columnName: Record | Knex.Raw): QueryBuilder; - avgDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + avg(columnName: Record | Raw): QueryBuilder; + avgDistinct(columnName: string | Record | Raw): QueryBuilder; increment(columnName: string, amount?: number): QueryBuilder; decrement(columnName: string, amount?: number): QueryBuilder; @@ -180,11 +180,11 @@ declare namespace Knex { } interface Table { - (tableName: TableName | Identifier): QueryBuilder; - (callback: Function): QueryBuilder; - (raw: Raw): QueryBuilder; + // tslint:disable-next-line ban-types + (tableName: TableName | Identifier | Function | Raw): QueryBuilder; } + // tslint:disable-next-line no-empty-interface interface Distinct extends ColumnNameQueryBuilder { } @@ -258,7 +258,7 @@ declare namespace Knex { interface WithRaw { (alias: string, raw: Raw): QueryBuilder; - (alias: string, sql: string, bindings?: Value[] | Object): QueryBuilder; + (alias: string, sql: string, bindings?: Value[] | object): QueryBuilder; } interface WithSchema { @@ -273,7 +273,7 @@ declare namespace Knex { interface Where extends WhereRaw, WhereWrapped, WhereNull { (raw: Raw): QueryBuilder; (callback: QueryCallback): QueryBuilder; - (object: Object): QueryBuilder; + (object: object): QueryBuilder; (columnName: string, value: Value | null): QueryBuilder; (columnName: string, operator: string, value: Value | QueryBuilder | null): QueryBuilder; (left: Raw, operator: string, right: Value | QueryBuilder | null): QueryBuilder; @@ -318,8 +318,8 @@ declare namespace Knex { interface Union { (callback: QueryCallback | QueryBuilder | Raw, wrap?: boolean): QueryBuilder; - (callbacks: (QueryCallback | QueryBuilder | Raw)[], wrap?: boolean): QueryBuilder; - (...callbacks: (QueryCallback | QueryBuilder | Raw)[]): QueryBuilder; + (callbacks: Array, wrap?: boolean): QueryBuilder; + (...callbacks: Array): QueryBuilder; // (...callbacks: QueryCallback[], wrap?: boolean): QueryInterface; } @@ -339,8 +339,8 @@ declare namespace Knex { } interface RawQueryBuilder { - (sql: string, ...bindings: (Value | QueryBuilder)[]): QueryBuilder; - (sql: string, bindings: (Value | QueryBuilder)[] | ValueMap): QueryBuilder; + (sql: string, ...bindings: Array): QueryBuilder; + (sql: string, bindings: Array | ValueMap): QueryBuilder; (raw: Raw): QueryBuilder; } @@ -352,8 +352,8 @@ declare namespace Knex { interface RawBuilder { (value: Value): Raw; - (sql: string, ...bindings: (Value | QueryBuilder)[]): Raw; - (sql: string, bindings: (Value | QueryBuilder)[] | ValueMap): Raw; + (sql: string, ...bindings: Array): Raw; + (sql: string, bindings: Array | ValueMap): Raw; } // @@ -367,7 +367,7 @@ declare namespace Knex { or: QueryBuilder; and: QueryBuilder; - //TODO: Promise? + // TODO: Promise? columnInfo(column?: string): Bluebird; forUpdate(): QueryBuilder; @@ -375,7 +375,7 @@ declare namespace Knex { toSQL(): Sql; - on(event: string, callback: Function): QueryBuilder; + on(event: string, callback: (...args: any[]) => void): QueryBuilder; } interface Sql { @@ -398,6 +398,7 @@ declare namespace Knex { stream(handler: (readable: stream.PassThrough) => any): Bluebird; stream(options: { [key: string]: any }, handler: (readable: stream.PassThrough) => any): Bluebird; stream(options?: { [key: string]: any }): stream.PassThrough; + // tslint:disable-next-line no-unnecessary-generics pipe(writable: T, options?: { [key: string]: any }): stream.PassThrough; } @@ -444,25 +445,26 @@ declare namespace Knex { timestamp(columnName: string, standard?: boolean): ColumnBuilder; timestamps(useTimestampType?: boolean, makeDefaultNow?: boolean): ColumnBuilder; binary(columnName: string, length?: number): ColumnBuilder; - enum(columnName: string, values: Value[]): ColumnBuilder; - enu(columnName: string, values: Value[]): ColumnBuilder; + enum(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; + enu(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; json(columnName: string): ColumnBuilder; jsonb(columnName: string): ColumnBuilder; uuid(columnName: string): ColumnBuilder; comment(val: string): TableBuilder; specificType(columnName: string, type: string): ColumnBuilder; primary(columnNames: string[]): TableBuilder; - index(columnNames: (string | Raw)[], indexName?: string, indexType?: string): TableBuilder; - unique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + index(columnNames: Array, indexName?: string, indexType?: string): TableBuilder; + unique(columnNames: Array, indexName?: string): TableBuilder; foreign(column: string, foreignKeyName?: string): ForeignConstraintBuilder; foreign(columns: string[], foreignKeyName?: string): MultikeyForeignConstraintBuilder; dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; - dropUnique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + dropUnique(columnNames: Array, indexName?: string): TableBuilder; dropPrimary(constraintName?: string): TableBuilder; - dropIndex(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + dropIndex(columnNames: Array, indexName?: string): TableBuilder; dropTimestamps(): ColumnBuilder; } + // tslint:disable-next-line no-empty-interface interface CreateTableBuilder extends TableBuilder { } @@ -472,9 +474,11 @@ declare namespace Knex { collate(val: string): CreateTableBuilder; } + // tslint:disable-next-line no-empty-interface interface AlterTableBuilder extends TableBuilder { } + // tslint:disable-next-line no-empty-interface interface MySqlAlterTableBuilder extends AlterTableBuilder { } @@ -509,6 +513,7 @@ declare namespace Knex { inTable(tableName: string): ColumnBuilder; } + // tslint:disable-next-line no-empty-interface interface AlterColumnBuilder extends ColumnBuilder { } @@ -517,6 +522,11 @@ declare namespace Knex { after(columnName: string): AlterColumnBuilder; } + interface EnumOptions { + useNative: boolean; + enumName: string; + } + // // Configurations // @@ -650,10 +660,10 @@ declare namespace Knex { interface PoolConfig { name?: string; - create?: Function; - afterCreate?: Function; - destroy?: Function; - beforeDestroy?: Function; + create?: (...args: any[]) => void; + afterCreate?: (...args: any[]) => void; + destroy?: (...args: any[]) => void; + beforeDestroy?: (...args: any[]) => void; min?: number; max?: number; refreshIdle?: boolean; @@ -661,7 +671,7 @@ declare namespace Knex { reapIntervalMillis?: number; returnToHead?: boolean; priorityRange?: number; - validate?: Function; + validate?: (...args: any[]) => void; log?: boolean; // generic-pool v3 configs diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 193eea8cf6..1f22e08df0 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1,14 +1,15 @@ import Knex = require('knex'); +import { WriteStream } from 'fs'; // Initializing the Library -var knex = Knex({ +let knex = Knex({ client: 'sqlite3', connection: { filename: "./mydb.sqlite" } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -19,7 +20,7 @@ var knex = Knex({ } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'pg', version: '9.5', @@ -33,7 +34,7 @@ var knex = Knex({ } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'mssql', connection: { @@ -47,7 +48,7 @@ var knex = Knex({ }); // Mariasql configuration -var knex = Knex({ +knex = Knex({ debug: true, client: 'mariasql', connection: { @@ -59,7 +60,7 @@ var knex = Knex({ }); // Mysql configuration -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -72,28 +73,24 @@ var knex = Knex({ }); // Pooling -var knex = Knex({ - client: 'mysql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - }, - pool: { - min: 0, - max: 7, - afterCreate: (connection: any, callback: Function) => { - return callback(null, connection); +knex = Knex({ + client: "mysql", + connection: { + host: "127.0.0.1", + user: "your_database_user", + password: "your_database_password", + database: "myapp_test" }, - beforeDestroy: (connection: any, callback: Function) => { - return callback(null, connection); + pool: { + min: 0, + max: 7, + afterCreate: (connection: any, callback: (...args: any[]) => void) => callback(null, connection), + beforeDestroy: (connection: any, callback: (...args: any[]) => void) => callback(null, connection) } - } }); // acquireConnectionTimeout -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -106,41 +103,41 @@ var knex = Knex({ }); // Pure Query Builder without a connection -var knex = Knex({}); +knex = Knex({}); // Pure Query Builder without a connection, using a specific flavour of SQL -var knex = Knex({ +knex = Knex({ client: 'pg' }); // searchPath -var knex = Knex({ +knex = Knex({ client: 'pg', searchPath: 'public', }); -var knex = Knex({ +knex = Knex({ client: 'pg', searchPath: ['public', 'private'], }); // postProcessResponse -var knex = Knex({ +knex = Knex({ client: 'pg', - postProcessResponse: function(result, queryContext){ + postProcessResponse(result, queryContext) { return result; } }); // wrapIdentifier -var knex = Knex({ +knex = Knex({ client: 'pg', - wrapIdentifier: function(value, origImpl, queryContext){ + wrapIdentifier(value, origImpl, queryContext) { return origImpl(value + 'foo'); } }); // useNullAsDefault -var knex = Knex({ +knex = Knex({ client: 'sqlite', useNullAsDefault: true, }); @@ -148,14 +145,14 @@ var knex = Knex({ // Using custom client class TestClient extends Knex.Client {} -var knex = Knex({ +knex = Knex({ client: TestClient, }); knex('books').insert({title: 'Test'}).returning('*').toString(); // Migrations -var knex = Knex({ +knex = Knex({ client: 'mysql', connection: { host : '127.0.0.1', @@ -176,7 +173,7 @@ knex.select('title', 'author', 'year').from('books'); knex.select({ name: 'title', writer: 'author' }).from(knex.raw('books')); knex.select().table('books'); -knex.avg('sum_column1').from(function() { +knex.avg('sum_column1').from(() => { this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1'); }).as('ignored_alias'); @@ -208,20 +205,20 @@ knex('users').where(knex.raw('votes + 1'), '>', 101); knex('users').where(knex.raw('votes + 1'), '>', knex.raw('100 + 1')); knex('users').where('votes', '>', knex.raw('100 + 1')); -var subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); +let subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); knex('accounts').where('id', 'in', subquery); knex.select('name').from('users') .whereIn('id', [1, 2, 3]) .orWhereIn('id', [4, 5, 6]); -var subquery = knex.select('id').from('accounts'); +subquery = knex.select('id').from('accounts'); knex.select('name').from('users') .whereIn('account_id', subquery); knex('users') .where('name', '=', 'John') - .orWhere(function() { + .orWhere(() => { this.where('votes', '>', 100).andWhere('title', '<>', 'Admin'); }); @@ -233,13 +230,13 @@ knex('users').whereNull('updated_at'); knex('users').whereNotNull('created_at'); -knex('users').whereExists(function() { +knex('users').whereExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); knex('users').whereExists(knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')); -knex('users').whereNotExists(function() { +knex('users').whereNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); @@ -324,15 +321,15 @@ knex('users') .join(knex('contacts').select('user_id', 'phone').as('contacts'), { 'users.id': 'contacts.user_id' }) .select('users.id', 'contacts.phone'); -knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), function() { +knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', function() { +knex.select('*').from('users').join('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', function(join: Knex.JoinClause) { +knex.select('*').from('users').join('accounts', (join: Knex.JoinClause) => { if (this !== join) { throw new Error("join() callback call semantics wrong"); } @@ -344,116 +341,116 @@ knex.select('*').from('user').join('contacts', () => { this.on('users.id', '=', knex.raw(7)); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').andOnExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').orOnExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').andOnNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').orOnNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); @@ -478,7 +475,7 @@ knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); -knex('users').innerJoin('accounts', function() { +knex('users').innerJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -488,7 +485,7 @@ knex('users').innerJoin('accounts', (join: Knex.JoinClause) => { knex.select('*').from('users').leftJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftJoin('accounts', function() { +knex.select('*').from('users').leftJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -505,13 +502,13 @@ knex.select('*').from('users').leftJoin('accounts', (join) => { knex.select('*').from('users').leftOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftOuterJoin('accounts', function() { +knex.select('*').from('users').leftOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').rightJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightJoin('accounts', function() { +knex.select('*').from('users').rightJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -521,13 +518,13 @@ knex.select('*').from('users').rightJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').rightOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightOuterJoin('accounts', function() { +knex.select('*').from('users').rightOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').outerJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').outerJoin('accounts', function() { +knex.select('*').from('users').outerJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -537,7 +534,7 @@ knex.select('*').from('users').outerJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').fullOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').fullOuterJoin('accounts', function() { +knex.select('*').from('users').fullOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -552,43 +549,42 @@ knex.select('*').from('accounts').joinRaw('natural full join table1').where('id' knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); knex.select('*').from('accounts') - .join(function() { + .join(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftJoin(function() { + .leftJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftOuterJoin(function() { + .leftOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightJoin(function() { + .rightJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightOuterJoin(function() { + .rightOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .innerJoin(function() { + .innerJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .crossJoin(function() { + .crossJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .fullOuterJoin(function() { + .fullOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .outerJoin(function() { + .outerJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); - knex('customers') .distinct('first_name', 'last_name') .select(); @@ -635,7 +631,7 @@ knex('accounts').where('activated', false).delete(); knex('accounts').where('activated', false).delete('id'); knex('accounts').where('activated', false).delete(['id', 'title']); -knex.with('old_books', function(qb) { +knex.with('old_books', (qb) => { qb.select('*').from('books').where('published_date', '<', 1970); }).select('*').from('old_books'); @@ -657,30 +653,30 @@ knex.withRaw('recent_books', 'select * from books where published_date >= :year' knex.withRaw('recent_books', knex.raw('select * from books where published_date >= ?', [2013])) .select('*').from('recent_books'); -knex.withWrapped("antique_books", function (qb) { +knex.withWrapped("antique_books", (qb) => { qb.select('*').from('books').where('published_date', '<', 1899); }).select('*').from('antique_books'); knex.withWrapped('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) .select('*').from('new_books'); -var someExternalMethod: Function; +const someExternalMethod: (...args: any[]) => void = () => {}; -knex.transaction(function(trx) { +knex.transaction((trx) => { knex('books').transacting(trx).insert({name: 'Old Books'}) - .then(function(resp) { - var id = resp[0]; - return someExternalMethod(id, trx); + .then((resp) => { + const id = resp[0]; + someExternalMethod(id, trx); }) .then(trx.commit) .catch(trx.rollback); -}).then(function() { +}).then(() => { console.log('Transaction complete.'); -}).catch(function(err) { +}).catch((err) => { console.error(err); }); -knex.transaction(function(trx) { +knex.transaction((trx) => { knex('tableName') .transacting(trx) .forUpdate() @@ -692,11 +688,13 @@ knex.transaction(function(trx) { .select('*'); }); -const transactionReturnValue = knex.transaction(function(trx) { +const transactionReturnValue = knex.transaction((trx) => { return knex("table") .insert({ foo: "bar" }) .returning(["id"]) - .then(function(result) { return result[0].id as number; }); + .then((result) => { + return result[0].id as number; + }); }); // Tests that the transaction has kept the type of its return value by referencing a method of number @@ -728,31 +726,30 @@ knex('accounts').where('userid', '=', 1).decrement('balance', 5); knex('accounts').truncate(); -knex.table('users').first('id').then(function(ids) { +knex.table('users').first('id').then((ids) => { console.log(ids); }); -knex.table('users').first('id', 'name').then(function(row) { +knex.table('users').first('id', 'name').then((row) => { console.log(row); }); -knex.table('users').first(knex.raw('round(sum(products)) as p')).then(function(row) { +knex.table('users').first(knex.raw('round(sum(products)) as p')).then((row) => { console.log(row); }); -knex.table('users').select('*').clearSelect().select('id').then(function(rows) { +knex.table('users').select('*').clearSelect().select('id').then((rows) => { console.log(rows); }); -knex('accounts').where('userid', '=', 1).clearWhere().select().then(function (rows) { +knex('accounts').where('userid', '=', 1).clearWhere().select().then((rows) => { console.log(rows); }); // Using trx as a query builder: -knex.transaction(function(trx) { - - var info: any; - var books: any[] = [ +knex.transaction((trx) => { + const info: any = {}; + const books: any[] = [ {title: 'Canterbury Tales'}, {title: 'Moby Dick'}, {title: 'Hamlet'} @@ -761,42 +758,41 @@ knex.transaction(function(trx) { return trx .insert({name: 'Old Books'}, 'id') .into('catalogues') - .then(function(ids) { - return Promise.all(books.map(function (book: any) { + .then((ids) => { + return Promise.all(books.map((book: any) => { book.catalogue_id = ids[0]; // Some validation could take place here. return trx.insert(info).into('books'); })); }); }) -.then(function(inserts) { +.then((inserts) => { console.log(inserts.length + ' new books saved.'); }) -.catch(function(error) { +.catch((error) => { // If we get here, that means that neither the 'Old Books' catalogues insert, // nor any of the books inserts will have taken place. console.error(error); }); // Using trx as a transaction object: -knex.transaction<{ length: number }>(function(trx) { - +knex.transaction<{ length: number }>((trx) => { trx.raw(''); - trx.on('query-error', function(error: Error) { + trx.on('query-error', (error: Error) => { console.error(error); }); - trx.savepoint(function(nestedTrx) { + trx.savepoint((nestedTrx) => { nestedTrx.rollback(new Error('something went terribly wrong')); }); - trx.transaction(function(nestedTrx) { + trx.transaction((nestedTrx) => { nestedTrx.commit(); }); - var info: any; - var books: any[] = [ + const info: any = {}; + const books: any[] = [ {title: 'Canterbury Tales'}, {title: 'Moby Dick'}, {title: 'Hamlet'} @@ -805,8 +801,8 @@ knex.transaction<{ length: number }>(function(trx) { knex.insert({name: 'Old Books'}, 'id') .into('catalogues') .transacting(trx) - .then(function(ids) { - return Promise.all(books.map(function(book: any) { + .then((ids) => { + return Promise.all(books.map((book: any) => { book.catalogue_id = ids[0]; // Some validation could take place here. @@ -817,10 +813,10 @@ knex.transaction<{ length: number }>(function(trx) { .then(trx.commit) .catch(trx.rollback); }) -.then(function(inserts) { +.then((inserts) => { console.log(inserts.length + ' new books saved.'); }) -.catch(function(error) { +.catch((error) => { // If we get here, that means that neither the 'Old Books' catalogues insert, // nor any of the books inserts will have taken place. console.error(error); @@ -831,7 +827,7 @@ knex.insert({ name: 'Old Books'}).transacting(undefined); knex.schema.withSchema("public").hasTable("table"); // $ExpectType Bluebird -knex.schema.createTable('users', function (table) { +knex.schema.createTable('users', (table) => { table.increments(); table.string('name'); table.enu('favorite_color', ['red', 'blue', 'green']); @@ -840,7 +836,7 @@ knex.schema.createTable('users', function (table) { table.timestamps(true, true); }); -knex.schema.alterTable('users', function (table) { +knex.schema.alterTable('users', (table) => { table.string('role').nullable(); }); @@ -848,9 +844,9 @@ knex.schema.renameTable('users', 'old_users'); knex.schema.dropTable('users'); -knex.schema.hasTable('users').then(function(exists) { +knex.schema.hasTable('users').then((exists) => { if (!exists) { - return knex.schema.createTable('users', function(t) { + return knex.schema.createTable('users', (t) => { t.increments('id').primary(); t.string('first_name', 100); t.string('last_name', 100); @@ -859,20 +855,20 @@ knex.schema.hasTable('users').then(function(exists) { } }); -var tableName: string; -var columnName: string; +const tableName = ''; +const columnName = ''; knex.schema.hasColumn(tableName, columnName); knex.schema.dropTableIfExists('users'); -knex.schema.table('users', function (table) { +knex.schema.table('users', (table) => { table.dropColumn('name'); table.string('first_name'); table.string('last_name'); }); knex.schema.raw("SET sql_mode='TRADITIONAL'") -.table('users', function (table) { +.table('users', (table) => { table.dropColumn('name'); table.string('first_name'); table.string('last_name'); @@ -888,12 +884,12 @@ knex('users') .orWhere(knex.raw('status <> ?', [1])) .groupBy('status'); -knex.raw('select * from users where id = ?', [1]).then(function(resp) { +knex.raw('select * from users where id = ?', [1]).then((resp) => { // ... }); (() => { - var subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') + const subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') .wrap('(', ') avg_sal_dept'); knex.select('e.lastname', 'e.salary', subcolumn) @@ -902,7 +898,7 @@ knex.raw('select * from users where id = ?', [1]).then(function(resp) { })(); (() => { - var subcolumn = knex.avg('salary') + const subcolumn = knex.avg('salary') .from('employee') .whereRaw('dept_no = e.dept_no') .as('avg_sal_dept'); @@ -912,70 +908,70 @@ knex.raw('select * from users where id = ?', [1]).then(function(resp) { .whereRaw('dept_no = e.dept_no'); })(); -var x: number; +const x = 1; knex.select('name').from('users') .where('id', '>', 20) .andWhere('id', '<', 200) .limit(10) .offset(x) - .then(function(rows) { + .then((rows) => { return rows.map((r: any) => r.name); }) - .then(function(names: any) { + .then((names: any) => { return knex.select('id').from('nicknames').whereIn('nickname', names); }) - .then(function(rows) { + .then((rows) => { console.log(rows); }) - .catch(function(error) { + .catch((error) => { console.error(error); }); knex.select('*').from('users').where({name: 'Tim'}) - .then(function(rows) { + .then((rows) => { return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts'); - }).then(function(id) { + }).then((id) => { console.log('Inserted Account ' + id); - }).catch(function(error) { + }).catch((error) => { console.error(error); }); knex.insert({id: 1, name: 'Test'}, 'id').into('accounts') - .catch(function(error) { + .catch((error) => { console.error(error); - }).then(function() { + }).then(() => { return knex.select('*').from('accounts').where('id', 1); - }).then(function(rows) { + }).then((rows) => { console.log(rows[0]); - }).catch(function(error) { + }).catch((error) => { console.error(error); }); -var query: any; -query.then(function(x: any) { +const query: any = () => {}; +query.then((x: any) => { // doSideEffectsHere(x); return x; }); -knex.select('name').from('users').limit(10).then(function (rows: any[]): string[] { - return rows.map(function (row: any): string { +knex.select('name').from('users').limit(10).then((rows: any[]): string[] => { + return rows.map((row: any): string => { return row.name; }); -}).then(function(names: string[]) { +}).then((names: string[]) => { console.log(names); -}).catch(function(e: Error) { +}).catch((e: Error) => { console.error(e); }); -knex.select('name').from('users').limit(10).then(function (rows: any[]) { - return rows.reduce(function(memo: any, row: any) { +knex.select('name').from('users').limit(10).then((rows: any[]) => { + return rows.reduce((memo: any, row: any) => { memo.names.push(row.name); memo.count++; return memo; }, {count: 0, names: []}); -}).then(function(obj: any) { +}).then((obj: any) => { console.log(obj); -}).catch(function(e: Error) { +}).catch((e: Error) => { console.error(e); }); @@ -984,10 +980,10 @@ knex.select('name').from('users') .then(console.log.bind(console)) .catch(console.error.bind(console)); -var values: any[]; +const values: any[] = []; knex.insert(values).into('users') - .then(function() { + .then(() => { return {inserted: true}; }); @@ -998,36 +994,40 @@ knex.select('name').from('users') .offset(x); // Retrieve the stream: -var stream = knex.select('*').from('users').stream(); -var writableStream: NodeJS.WritableStream; +let stream = knex.select('*').from('users').stream(); +const writableStream: NodeJS.WritableStream = new WriteStream(); stream.pipe(writableStream); // With options: -var stream = knex.select('*').from('users').stream({highWaterMark: 5}); +stream = knex.select('*').from('users').stream({highWaterMark: 5}); stream.pipe(writableStream); // Use as a promise: (() => { - -var stream = knex.select('*').from('users').where(knex.raw('id = ?', [1])).stream(function(stream: any) { - stream.pipe(writableStream); -}).then(function() { - // ... -}).catch(function(e: Error) { - console.error(e); -}); - + knex + .select("*") + .from("users") + .where(knex.raw("id = ?", [1])) + .stream((stream: any) => { + stream.pipe(writableStream); + }) + .then(() => { + // ... + }) + .catch((e: Error) => { + console.error(e); + }); })(); -var stream = knex.select('*').from('users').pipe(writableStream); -var app: any; +stream = knex.select('*').from('users').pipe(writableStream); +const app: any = () => {}; knex.select('*') .from('users') - .on('query', function(data: any) { + .on('query', (data: any) => { app.log(data); }) - .then(function() { + .then(() => { // ... }); @@ -1040,66 +1040,66 @@ knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); // knex('users') .select('*') - .join('contacts', function(builder) { - this.on(function(builder) { + .join('contacts', (builder) => { + this.on((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).andOn(function(builder) { + }).andOn((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).orOn(function(builder) { + }).orOn((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).onExists(function(builder) { + }).onExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).orOnExists(function(builder) { + }).orOnExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).andOnExists(function(builder) { + }).andOnExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).onNotExists(function(builder) { + }).onNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).andOnNotExists(function(builder) { + }).andOnNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).orOnNotExists(function(builder) { + }).orOnNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; }); - }).where(function(builder) { + }).where((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhere(function(builder) { + }).orWhere((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).andWhere(function(builder) { + }).andWhere((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereIn('column', function(builder) { + }).whereIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereIn('column', function(builder) { + }).orWhereIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereNotIn('column', function(builder) { + }).whereNotIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereNotIn('column', function(builder) { + }).orWhereNotIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereWrapped(function(builder) { + }).whereWrapped((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).union(function(builder) { + }).union((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).unionAll(function(builder) { + }).unionAll((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).modify(function(builder, aBool) { + }).modify((builder, aBool) => { let self: Knex.QueryBuilder = this; self = builder; }, true); @@ -1107,7 +1107,7 @@ knex('users') // // Migrations // -var config = { +const config = { directory: "./migrations", extension: "js", tableName: "knex_migrations", @@ -1131,7 +1131,6 @@ knex.seed.make(name); knex.seed.run(config); knex.seed.run(); - knex.schema .dropTableIfExists('A') .createTable('A', table => { @@ -1142,21 +1141,20 @@ knex.schema table.timestamp('T', false).notNullable(); }); - -//creating table in MySQL with binary primary key with known field length -knex.schema.createTable('testTable', function (table) { - table.binary('binaryKey', 16).primary(); //will make table with binaryKey type BINARY(16) +// creating table in MySQL with binary primary key with known field length +knex.schema.createTable('testTable', (table) => { + table.binary('binaryKey', 16).primary(); // will make table with binaryKey type BINARY(16) }); // allow creating decimal column that can store that can store numbers of any // precision and scale. (Only supported for Oracle, SQLite, Postgres) -var knex = Knex({ +knex = Knex({ client: 'pg' }); knex.schema .dropTableIfExists('testTable') - .createTable('testTable', function (table) { + .createTable('testTable', (table) => { table.decimal('dec', null); }) .dropTable('testTable'); @@ -1165,10 +1163,10 @@ knex.schema knex.schema .dropTableIfExists('foo') .dropTableIfExists('bar') - .createTable('foo', function (table) { + .createTable('foo', (table) => { table.uuid('id').primary(); }) - .createTable('bar', function (table) { + .createTable('bar', (table) => { table.uuid('id').primary(); }); @@ -1194,12 +1192,12 @@ knex('characters') knex('characters') .select() - .whereIn('name', function() { + .whereIn('name', () => { this.select('name').from('characters'); }); knex('characters') .select() - .whereIn(['name', 'class'], function() { + .whereIn(['name', 'class'], () => { this.select('name', 'class').from('characters'); }); diff --git a/types/knex/tslint.json b/types/knex/tslint.json index d84fe24e60..604d5950cf 100644 --- a/types/knex/tslint.json +++ b/types/knex/tslint.json @@ -1,76 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "unified-signatures": false + "unified-signatures": false, + "callable-types": false } } diff --git a/types/knuddels-userapps-api/index.d.ts b/types/knuddels-userapps-api/index.d.ts index 1985c305a2..f190821ba8 100644 --- a/types/knuddels-userapps-api/index.d.ts +++ b/types/knuddels-userapps-api/index.d.ts @@ -1,22 +1,22 @@ -// Type definitions for Knuddels UserApps API 1.00109481 +// Type definitions for Knuddels UserApps API 1.00111486 // Project: https://developer.knuddels.de // Definitions by: Knuddels GmbH & Co. KG // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // helper types -export type JsonData = string | number | boolean | Date | Json | JsonArray; -export type KnuddelsJsonData = string | number | boolean | Date | KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable; -export type KnuddelsSerializable = string | number | boolean | User | BotUser; +export type JsonData = string | number | boolean | Date | Json | JsonArray | undefined; +export type KnuddelsJsonData = string | number | boolean | Date | KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable | undefined; +export type KnuddelsSerializable = string | number | boolean | User | BotUser | undefined; export type KnuddelsEvent = string | Json | KnuddelsEventArray; // helper interfaces declare global { interface Json { - [x: string]: JsonData; + [x: string]: JsonData | undefined; } interface KnuddelsJson { - [x: string]: KnuddelsJsonData; + [x: string]: KnuddelsJsonData | undefined; } interface JsonArray extends Array { @@ -1026,12 +1026,12 @@ declare global { * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getAppViewMode * @since Applet: 9.0byl */ - getAppViewMode(): void; + getAppViewMode(): string; /** * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getBrowserType * @since Applet: 9.0bzp */ - getBrowserType(): void; + getBrowserType(): string; } } diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 8402d8bc9b..0fafcb73c9 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -919,6 +919,12 @@ export class GeoJSON

extends FeatureGroup

{ */ resetStyle(layer: Layer): Layer; + /** + * Same as FeatureGroup's setStyle method, but style-functions are also + * allowed here to set the style according to the feature. + */ + setStyle(style: PathOptions | StyleFunction

): this; + options: GeoJSONOptions

; } diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index d1375fa83f..5e8a876774 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -414,6 +414,14 @@ let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); nestedTwoCoords = L.GeoJSON.latLngsToCoords(nestedLatLngs, 1); +const geojson = new L.GeoJSON(); +const style: L.PathOptions = { + className: "string", +}; +const styler: L.StyleFunction = () => style; +geojson.setStyle(style); +geojson.setStyle(styler); + class MyMarker extends L.Marker { constructor() { super([12, 13]); diff --git a/types/lzma-native/index.d.ts b/types/lzma-native/index.d.ts new file mode 100644 index 0000000000..33165885da --- /dev/null +++ b/types/lzma-native/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for lzma-native 4.0 +// Project: https://github.com/addaleax/lzma-native +// Definitions by: Evan Cameron +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/// + +import { Stream } from "stream"; +export interface LzmaOptions { + synchronous?: boolean; + bufsize?: number; + memlimit?: number; + check?: Check; + preset?: Preset; + flags?: + | "TELL_NO_CHECK" + | "TELL_UNSUPPORTED_CHECK" + | "TELL_ANY_CHECK" + | "CONCATENATED"; + threads?: number; + blockSize?: number; + timeout?: number; +} + +export type Check = + | "CHECK_CRC32" + | "CHECK_CRC64" + | "CHECK_NONE" + | "CHECK_SHA256"; + +export type Coders = + | "easyEncoder" + | "aloneDecoder" + | "rawEncoder" + | "autoDecoder" + | "aloneEncoder" + | "streamEncoder" + | "streamDecoder"; + +export type Preset = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + +export interface FileOptions { + fileSize: number; + memlimit?: number; + read: ( + count: number, + offset: number, + cb: (err: any, buffer: Buffer) => void + ) => void; +} + +export interface StreamInfo { + streamPadding: number; + memlimit: number; + streams: number; + blocks: number; + fileSize: number; + uncompressedSize: number; + checks: number; +} + +export function createStream( + coder: Coders, + options?: LzmaOptions +): JSLzmaStream; + +export function createCompressor(options?: LzmaOptions): JSLzmaStream; +export function createDecompressor(options?: LzmaOptions): JSLzmaStream; +export function crc32( + input: string, + encoding?: string, + previous?: number +): string; +export function isXZ(buf: Buffer | string): boolean; +export function versionString(): string; +export function versionNumber(): number; +export function checkSize(check: Check): number; +export function easyDecoderMemusage(preset: Preset): number; +export function easyEncoderMemusage(preset: Preset): number; +export function rawDecoderMemusage(preset: Preset): number; +export function rawEncoderMemusage(preset: Preset): number; + +export function Compressor( + preset?: Preset, + options?: LzmaOptions +): JSLzmaStream; +export function Decompressor(options?: LzmaOptions): JSLzmaStream; + +export function parseFileIndex( + options: FileOptions, + callback?: (err: any, info?: StreamInfo) => void +): void; +export function parseFileIndexFD( + fileDescriptor: number, + callback?: (err: any, info?: StreamInfo) => void +): void; + +export function compress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function decompress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function LZMA(): { + compress( + buf: Buffer | string, + mode: Preset, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; + decompress( + buf: Buffer | string, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; +}; + +export class JSLzmaStream extends Stream.Transform { + constructor(nativeStream: Stream, options: LzmaOptions); + bufsize(): number; + bufsize(size: number): void; + totalInt(): number; + totalOut(): number; + cleanUp(): void; +} diff --git a/types/lzma-native/lzma-native-tests.ts b/types/lzma-native/lzma-native-tests.ts new file mode 100644 index 0000000000..44a5eab221 --- /dev/null +++ b/types/lzma-native/lzma-native-tests.ts @@ -0,0 +1,55 @@ +import * as lzma from "lzma-native"; +import * as fs from "fs"; + +const compressor = lzma.createCompressor(); +const input = fs.createReadStream("tsconfig.json"); +const output = fs.createWriteStream("tsconfig.json.xz"); + +input.pipe(compressor).pipe(output); + +lzma.compress("Banana", undefined, result => { + console.log(result); // +}); + +lzma.compress("Bananas", 6, result => { + lzma.decompress(result, undefined, decompressedResult => { + console.log(decompressedResult.toString() === "Bananas"); + }); +}); + +lzma.LZMA().compress("Bananas", 4, result => { + lzma.LZMA().decompress(result, decompressedResult => { + console.log("Bananas" === decompressedResult.toString()); + }); +}); + +const comp = lzma.Compressor(); + +process.stdin.pipe(comp).pipe(process.stdout); +lzma.crc32("Banana"); // => 69690105 +lzma.checkSize("CHECK_SHA256"); // => 16 +lzma.checkSize("CHECK_CRC32"); // => 4 +lzma.easyDecoderMemusage(6); // => 8454192 +lzma.easyEncoderMemusage(6); // => 97620499 +lzma.versionString(); // => '5.2.3' +lzma.versionNumber(); // => 50020012 +lzma.isXZ("Banana"); // => false + +fs.open("test/hamlet.txt.xz", "r", (err: any, fd: number) => { + if (err) return; + // handle error + lzma.parseFileIndexFD(fd, (err, info) => { + // handle error + if (err) { + console.log(err); + } + // do something with e.g. info.uncompressedSize + + fs.close(fd, (err: any) => { + /* handle error */ + if (err) { + console.log(err); + } + }); + }); +}); diff --git a/types/lzma-native/tsconfig.json b/types/lzma-native/tsconfig.json new file mode 100644 index 0000000000..fa7667f123 --- /dev/null +++ b/types/lzma-native/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitThis": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "lzma-native-tests.ts"] +} diff --git a/types/lzma-native/tslint.json b/types/lzma-native/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lzma-native/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-expander/index.d.ts b/types/makeup-expander/index.d.ts new file mode 100644 index 0000000000..90bd660581 --- /dev/null +++ b/types/makeup-expander/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for makeup-expander 0.4 +// Project: https://github.com/makeup-js/makeup-expander +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +declare namespace Expander { + interface Options { + autoCollapse?: boolean; + collapseOnClickOut?: boolean; + collapseOnFocusOut?: boolean; + collapseOnMouseOut?: boolean; + contentSelector?: string; + expandOnClick?: boolean; + expandOnFocus?: boolean; + expandOnHover?: boolean; + focusManagement?: string | null; + hostSelector?: string; + } +} + +declare class Expander { + constructor(el: HTMLElement, selectedOptions?: Expander.Options); + + collapseOnClickOut: boolean; + + collapseOnFocusOut: boolean; + + collapseOnMouseOut: boolean; + + expandOnClick: boolean; + + expandOnFocus: boolean; + + expandOnHover: boolean; + + collapse(): void; + + expand(isKeyboard: boolean): void; + + isExpanded(): boolean; + + toggle(): void; +} + +export = Expander; diff --git a/types/makeup-expander/makeup-expander-tests.ts b/types/makeup-expander/makeup-expander-tests.ts new file mode 100644 index 0000000000..f35d7cd3bd --- /dev/null +++ b/types/makeup-expander/makeup-expander-tests.ts @@ -0,0 +1,21 @@ +import Expander = require('makeup-expander'); + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +const options: Expander.Options = { + expandOnClick: true +}; + +if (widgetEl) { + // $ExpectType Expander + new Expander(widgetEl); + + // $ExpectType Expander + const widget = new Expander(widgetEl, options); + + // $ExpectType void + widget.expand(true); + + // $ExpectType boolean + const expanded = widget.isExpanded(); +} diff --git a/types/makeup-expander/tsconfig.json b/types/makeup-expander/tsconfig.json new file mode 100644 index 0000000000..f247e79d82 --- /dev/null +++ b/types/makeup-expander/tsconfig.json @@ -0,0 +1,22 @@ +{ + "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", + "makeup-expander-tests.ts" + ] +} diff --git a/types/makeup-expander/tslint.json b/types/makeup-expander/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-expander/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-floating-label/index.d.ts b/types/makeup-floating-label/index.d.ts new file mode 100644 index 0000000000..7b35349554 --- /dev/null +++ b/types/makeup-floating-label/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for makeup-floating-label 0.0 +// Project: https://github.com/makeup-js/makeup-floating-label#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +declare class FloatingLabel { + constructor(el: any, userOptions?: any); + refresh(): void; +} + +export = FloatingLabel; diff --git a/types/makeup-floating-label/makeup-floating-label-tests.ts b/types/makeup-floating-label/makeup-floating-label-tests.ts new file mode 100644 index 0000000000..3883e4135f --- /dev/null +++ b/types/makeup-floating-label/makeup-floating-label-tests.ts @@ -0,0 +1,9 @@ +import FloatingLabel = require('makeup-floating-label'); + +const widgetEls = document.querySelectorAll('.floating-label'); + +widgetEls.forEach((el: Element) => { + const widget = new FloatingLabel(el); + + widget.refresh(); +}); diff --git a/types/makeup-floating-label/tsconfig.json b/types/makeup-floating-label/tsconfig.json new file mode 100644 index 0000000000..c7fed3a8c4 --- /dev/null +++ b/types/makeup-floating-label/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom", + "dom.iterable" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "makeup-floating-label-tests.ts" + ] +} diff --git a/types/makeup-floating-label/tslint.json b/types/makeup-floating-label/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-floating-label/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-screenreader-trap/index.d.ts b/types/makeup-screenreader-trap/index.d.ts new file mode 100644 index 0000000000..0995b62a3c --- /dev/null +++ b/types/makeup-screenreader-trap/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for makeup-screenreader-trap 0.0 +// Project: https://github.com/makeup-js/makeup-screenreader-trap#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function trap(el: HTMLElement): void; + +export function untrap(): void; diff --git a/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts new file mode 100644 index 0000000000..48b198ab2d --- /dev/null +++ b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts @@ -0,0 +1,9 @@ +import { trap, untrap } from 'makeup-screenreader-trap'; + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +if (widgetEl) { + trap(widgetEl); +} + +untrap(); diff --git a/types/makeup-screenreader-trap/tsconfig.json b/types/makeup-screenreader-trap/tsconfig.json new file mode 100644 index 0000000000..08df420e11 --- /dev/null +++ b/types/makeup-screenreader-trap/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", + "makeup-screenreader-trap-tests.ts" + ] +} diff --git a/types/makeup-screenreader-trap/tslint.json b/types/makeup-screenreader-trap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-screenreader-trap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mali/index.d.ts b/types/mali/index.d.ts deleted file mode 100644 index 8e536d5330..0000000000 --- a/types/mali/index.d.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Type definitions for mali 0.9 -// Project: https://github.com/malijs/mali -// Definitions by: Daniel Byrne -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -/// - -import { EventEmitter } from 'events'; -import { Stream } from 'stream'; - -declare class Mali extends EventEmitter { - constructor(path: any, name?: string | ReadonlyArray, options?: any); - name: string; - env: string; - ports: ReadonlyArray; - silent: boolean; - - addService(path: any, name: string | ReadonlyArray, options?: any): void; - use(service?: any, name?: any, fns?: any): void; - start(port: number | string, creds?: any, options?: any): any; // gnarly type inferring for these functions so Im just gonna let them handle it. - toJSON(): any; - close(): Promise; - inspect(): any; -} - -declare namespace Mali { - interface Context { - name: string; - fullName: string; - service: string; - package: string; - app: any; // ? app - call: any; - request: Request; - response: Response; - req: any; // ? - res: any; // ? - type: string; - metadata: string; - get(field: string): any; - set(field: any, val?: any): void; // do I need `?:` if its of type `any`? - sendMetadata(md: any): void; - getStatus(field: string): any; - setStatus(field: any, val?: any): void; // ^ - } - - class Request { - constructor(call: any, type: string); - call: any; - type: string; - metadata: any; - req: any; // ? - - getMetadata(): any; - get(field: string): any; - } - - class Response { - constructor(call: any, type: string); - call: any; - type: string; - metadata: any; - status: any; - res: any; // ? - set(field: any, val?: any): void; // is `val?:` necessary when its of type `any`? - get(field: string): any; - getMetadata(): any; - sendMetadata(md?: any): void; - getStatus(field: string): any; - setStatus(field: any, val?: any): void; // ^ same as above - } - - function exec(ctx: Context, handler: any, cb?: any): void; -} - -export = Mali; diff --git a/types/mali/mali-tests.ts b/types/mali/mali-tests.ts deleted file mode 100644 index d6d33a263f..0000000000 --- a/types/mali/mali-tests.ts +++ /dev/null @@ -1,16 +0,0 @@ -// example from https://github.com/malijs/mali#example - -import Mali = require('mali'); -import path = require('path'); - -const PROTO_PATH = path.resolve(__dirname, '../protos/helloworld.proto'); - -async function sayHello(ctx: Mali.Context) { - ctx.res = { message: 'Hello '.concat(ctx.req.name) }; -} - -const app = new Mali(PROTO_PATH); -// $ExpectType void -app.use({sayHello}); -// $ExpectType any -app.start('127.0.0.1:50051'); diff --git a/types/mali/tsconfig.json b/types/mali/tsconfig.json deleted file mode 100644 index 1a4f86d02c..0000000000 --- a/types/mali/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": ["es6"], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": ["../"], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "mali-tests.ts" - ] -} diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 1aad087460..33a619b9ae 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -692,6 +692,8 @@ declare namespace mapboxgl { clusterMaxZoom?: number; lineMetrics?: boolean; + + generateId?: boolean; } /** diff --git a/types/markdown-it-anchor/index.d.ts b/types/markdown-it-anchor/index.d.ts index fc4cead6d4..39cb91be45 100644 --- a/types/markdown-it-anchor/index.d.ts +++ b/types/markdown-it-anchor/index.d.ts @@ -4,7 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt, Core, Token } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Core = require('markdown-it/lib/parser_core'); +import Token = require('markdown-it/lib/token'); declare namespace anchor { interface AnchorInfo { diff --git a/types/markdown-it-anchor/markdown-it-anchor-tests.ts b/types/markdown-it-anchor/markdown-it-anchor-tests.ts index 3570ba764b..a9a865a469 100644 --- a/types/markdown-it-anchor/markdown-it-anchor-tests.ts +++ b/types/markdown-it-anchor/markdown-it-anchor-tests.ts @@ -1,4 +1,4 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); import anchor = require("markdown-it-anchor"); const md = new MarkdownIt(); diff --git a/types/markdown-it-container/index.d.ts b/types/markdown-it-container/index.d.ts index b0913972fa..2920f38f91 100644 --- a/types/markdown-it-container/index.d.ts +++ b/types/markdown-it-container/index.d.ts @@ -4,7 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt, Token, Renderer } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Renderer = require('markdown-it/lib/renderer'); +import Token = require('markdown-it/lib/token'); declare namespace markdownItContainer { interface ContainerOpts { diff --git a/types/markdown-it-container/markdown-it-container-tests.ts b/types/markdown-it-container/markdown-it-container-tests.ts index 3c8f3bf980..e6754f82f3 100644 --- a/types/markdown-it-container/markdown-it-container-tests.ts +++ b/types/markdown-it-container/markdown-it-container-tests.ts @@ -1,11 +1,13 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Token = require("markdown-it/lib/token"); + import MarkdownItContainer = require("markdown-it-container"); const md = new MarkdownIt(); md.use(MarkdownItContainer, 'spoiler', { validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), - render: (tokens: MarkdownIt.Token[], index: number) => { + render: (tokens: Token[], index: number) => { const match = tokens[index].info.trim().match(/^spoiler\s+(.*)$/); const onClick = "this.parentNode.classList.toggle('_expanded');" + diff --git a/types/markdown-it-lazy-headers/index.d.ts b/types/markdown-it-lazy-headers/index.d.ts index 0579118f80..43ac828764 100644 --- a/types/markdown-it-lazy-headers/index.d.ts +++ b/types/markdown-it-lazy-headers/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); declare function lazyheaders(md: MarkdownIt): void; diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 0948a6d353..e7d0ffa6e7 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -4,235 +4,5 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface MarkdownItStatic { - new (): MarkdownIt.MarkdownIt; - new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - new (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (): MarkdownIt.MarkdownIt; - (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; -} - -declare var MarkdownIt: MarkdownItStatic; +import MarkdownIt = require("./lib"); export = MarkdownIt; -export as namespace markdownit; - -declare module MarkdownIt { - interface MarkdownIt { - render(md: string, env?: any): string; - renderInline(md: string, env?: any): string; - parse(src: string, env: any): Token[]; - parseInline(src: string, env: any): Token[]; - - /* - // The following only works in 3.0 - // Since it's still not allowed to target 3.0, i'll leave the code commented out - - use = any[]>( - plugin: (md: MarkdownIt, ...params: T) => void, - ...params: T - ): MarkdownIt; - */ - - use(plugin: (md: MarkdownIt, ...params: any[]) => void, ...params: any[]): MarkdownIt; - - utils: { - assign(obj: any): any; - isString(obj: any): boolean; - has(object: any, key: string): boolean; - unescapeMd(str: string): string; - unescapeAll(str: string): string; - isValidEntityCode(str: any): boolean; - fromCodePoint(str: string): string; - escapeHtml(str: string): string; - arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] - isSpace(str: any): boolean; - isWhiteSpace(str: any): boolean - isMdAsciiPunct(str: any): boolean; - isPunctChar(str: any): boolean; - escapeRE(str: string): string; - normalizeReference(str: string): string; - } - - disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - set(options: Options): MarkdownIt; - normalizeLink(url: string): string; - normalizeLinkText(url: string): string; - validateLink(url: string): boolean; - block: ParserBlock; - core: Core; - helpers: any; - inline: ParserInline; - linkify: LinkifyIt; - renderer: Renderer; - } - interface Options { - html?: boolean; - xhtmlOut?: boolean; - breaks?: boolean; - langPrefix?: string; - linkify?: boolean; - typographer?: boolean; - quotes?: string; - highlight?: (str: string, lang: string) => void; - } - interface LinkifyIt { - tlds(lang: string, linkified: boolean): void; - } - interface Renderer { - rules: { [name: string]: TokenRender }; - render(tokens: Token[], options: any, env: any): string; - renderAttrs(token: Token): string; - renderInline(tokens: Token[], options: any, env: any): string; - renderToken(tokens: Token[], idx: number, options: any): string; - } - interface Token { - new (type: string, tag: string, nesting: number): Token; - attrGet: (name: string) => string | null; - attrIndex: (name: string) => number; - attrJoin: (name: string, value: string) => void; - attrPush: (attrData: string[]) => void; - attrSet: (name: string, value: string) => void; - attrs: string[][]; - block: boolean; - children: Token[]; - content: string; - hidden: boolean; - info: string; - level: number; - map: number[]; - markup: string; - meta: any; - nesting: number; - tag: string; - type: string; - } - - type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; - - interface Rule { - (state: S, silent?: boolean): boolean | void; - } - - interface RuleInline extends Rule {} - interface RuleBlock extends Rule {} - - interface Ruler { - after(afterName: string, ruleName: string, rule: Rule, options?: any): void; - at(name: string, rule: Rule, options?: any): void; - before(beforeName: string, ruleName: string, rule: Rule, options?: any): void; - disable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enableOnly(rule: string, ignoreInvalid?: boolean): void; - getRules(chain: string): Rule[]; - push(ruleName: string, rule: Rule, options?: any): void; - } - - interface RulerInline extends Ruler {} - interface RulerBlock extends Ruler {} - - interface ParserBlock { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - ruler: RulerBlock; - } - - interface Core { - process(state: any): void; - ruler: Ruler; - } - - interface ParserInline { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - tokenize(state: State): void; - skipToken(state: State): void; - ruler: RulerInline; - ruler2: RulerInline; - } - - interface Delimiter { - close: boolean; - end: number; - jump: number; - length: number; - level: number; - marker: number; - open: boolean; - token: number; - } - - interface State { - env: any; - level: number; - - /** Link to parser instance */ - md: MarkdownIt; - - /** The markdown source code that is being parsed. */ - src: string; - - tokens: Token[]; - - /** Return any for a yet untyped property */ - [undocumented: string]: any; - } - - interface StateInline extends State { - /** - * Stores `{ start: end }` pairs. Useful for backtrack - * optimization of pairs parse (emphasis, strikes). - */ - cache: { [start: number]: number }; - - /** Emphasis-like delimiters */ - delimiters: Delimiter[]; - - pending: string; - pendingLevel: number; - - /** Index of the first character of this token. */ - pos: number; - - /** Index of the last character that can be used (for example the one before the end of this line). */ - posMax: number; - - /** - * Push new token to "stream". - * If pending text exists, flush it as text token. - */ - push(type: string, tag: string, nesting: number): Token; - - /** Flush pending text */ - pushPending(): Token; - - /** - * Scan a sequence of emphasis-like markers and determine whether - * it can start an emphasis sequence or end an emphasis sequence. - * @param start - position to scan from (it should point to a valid marker) - * @param canSplitWord - determine if these markers can be found inside a word - */ - scanDelims(start: number, canSplitWord: boolean): { - can_open: boolean, - can_close: boolean, - length: number - }; - } - - interface StateBlock extends State { - /** Used in lists to determine if they interrupt a paragraph */ - parentType: 'blockquote' | 'list' | 'root' | 'paragraph' | 'reference'; - - eMarks: number[]; - bMarks: number[]; - bsCount: number[]; - sCount: number[]; - tShift: number[]; - - blkIndent: number; - ddIndent: number; - - line: number; - lineMax: number; - tight: boolean; - } -} diff --git a/types/markdown-it/lib/index.d.ts b/types/markdown-it/lib/index.d.ts new file mode 100644 index 0000000000..9a9caf37b6 --- /dev/null +++ b/types/markdown-it/lib/index.d.ts @@ -0,0 +1,113 @@ +import { LinkifyIt } from 'linkify-it' + +import State = require('./rules_core/state_core'); +import StateBlock = require('./rules_block/state_block'); +import StateInline = require('./rules_inline/state_inline'); + +import Core = require('./parser_core'); +import ParserBlock = require('./parser_block'); +import ParserInline = require('./parser_inline'); + +import Renderer = require('./renderer'); +import Ruler = require('./ruler'); +import Token = require('./token'); + +export = MarkdownIt; +export as namespace markdownit; + +declare const MarkdownIt: MarkdownItConstructor; + +interface MarkdownItConstructor { + new (): MarkdownIt; + new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt; + new (options: MarkdownIt.Options): MarkdownIt; + (): MarkdownIt; + (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt; + (options: MarkdownIt.Options): MarkdownIt; +} + +interface MarkdownIt { + render(md: string, env?: any): string; + renderInline(md: string, env?: any): string; + parse(src: string, env: any): Token[]; + parseInline(src: string, env: any): Token[]; + + /* + // The following only works in 3.0 + // Since it's still not allowed to target 3.0, i'll leave the code commented out + + use = any[]>( + plugin: (md: MarkdownIt, ...params: T) => void, + ...params: T + ): MarkdownIt; + */ + + use(plugin: (md: MarkdownIt, ...params: any[]) => void, ...params: any[]): MarkdownIt; + + utils: { + assign(obj: any): any; + isString(obj: any): boolean; + has(object: any, key: string): boolean; + unescapeMd(str: string): string; + unescapeAll(str: string): string; + isValidEntityCode(str: any): boolean; + fromCodePoint(str: string): string; + escapeHtml(str: string): string; + arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] + isSpace(str: any): boolean; + isWhiteSpace(str: any): boolean + isMdAsciiPunct(str: any): boolean; + isPunctChar(str: any): boolean; + escapeRE(str: string): string; + normalizeReference(str: string): string; + } + + disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + set(options: MarkdownIt.Options): MarkdownIt; + normalizeLink(url: string): string; + normalizeLinkText(url: string): string; + validateLink(url: string): boolean; + block: ParserBlock; + core: Core; + helpers: any; + inline: ParserInline; + linkify: LinkifyIt; + renderer: Renderer; +} + +declare module MarkdownIt { + interface Options { + html?: boolean; + xhtmlOut?: boolean; + breaks?: boolean; + langPrefix?: string; + linkify?: boolean; + typographer?: boolean; + quotes?: string; + highlight?: (str: string, lang: string) => void; + } + + interface Rule { + (state: S, silent?: boolean): boolean | void; + } + + interface RuleInline extends Rule {} + interface RuleBlock extends Rule {} + + interface RulerInline extends Ruler {} + interface RulerBlock extends Ruler {} + + type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; + + interface Delimiter { + close: boolean; + end: number; + jump: number; + length: number; + level: number; + marker: number; + open: boolean; + token: number; + } +} diff --git a/types/markdown-it/lib/parser_block.d.ts b/types/markdown-it/lib/parser_block.d.ts new file mode 100644 index 0000000000..2efc76b858 --- /dev/null +++ b/types/markdown-it/lib/parser_block.d.ts @@ -0,0 +1,9 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = ParserBlock; + +declare class ParserBlock { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + ruler: MarkdownIt.RulerBlock; +} diff --git a/types/markdown-it/lib/parser_core.d.ts b/types/markdown-it/lib/parser_core.d.ts new file mode 100644 index 0000000000..a6559bdfef --- /dev/null +++ b/types/markdown-it/lib/parser_core.d.ts @@ -0,0 +1,10 @@ +import MarkdownIt = require("."); +import Ruler = require("./ruler"); +import Token = require("./token"); + +export = ParserCore; + +declare class ParserCore { + process(state: any): void; + ruler: Ruler; +} diff --git a/types/markdown-it/lib/parser_inline.d.ts b/types/markdown-it/lib/parser_inline.d.ts new file mode 100644 index 0000000000..ad7aa26d93 --- /dev/null +++ b/types/markdown-it/lib/parser_inline.d.ts @@ -0,0 +1,13 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); +import Token = require("./token"); + +export = ParserInline; + +declare class ParserInline { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + tokenize(state: State): void; + skipToken(state: State): void; + ruler: MarkdownIt.RulerInline; + ruler2: MarkdownIt.RulerInline; +} diff --git a/types/markdown-it/lib/renderer.d.ts b/types/markdown-it/lib/renderer.d.ts new file mode 100644 index 0000000000..0231dad0f9 --- /dev/null +++ b/types/markdown-it/lib/renderer.d.ts @@ -0,0 +1,12 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = Renderer; + +declare class Renderer { + rules: { [name: string]: MarkdownIt.TokenRender }; + render(tokens: Token[], options: any, env: any): string; + renderAttrs(token: Token): string; + renderInline(tokens: Token[], options: any, env: any): string; + renderToken(tokens: Token[], idx: number, options: any): string; +} diff --git a/types/markdown-it/lib/ruler.d.ts b/types/markdown-it/lib/ruler.d.ts new file mode 100644 index 0000000000..62ab55e3de --- /dev/null +++ b/types/markdown-it/lib/ruler.d.ts @@ -0,0 +1,15 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); + +export = Ruler; + +declare class Ruler { + after(afterName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + at(name: string, rule: MarkdownIt.Rule, options?: any): void; + before(beforeName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + disable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enableOnly(rule: string, ignoreInvalid?: boolean): void; + getRules(chain: string): MarkdownIt.Rule[]; + push(ruleName: string, rule: MarkdownIt.Rule, options?: any): void; +} diff --git a/types/markdown-it/lib/rules_block/state_block.d.ts b/types/markdown-it/lib/rules_block/state_block.d.ts new file mode 100644 index 0000000000..6eebab4202 --- /dev/null +++ b/types/markdown-it/lib/rules_block/state_block.d.ts @@ -0,0 +1,23 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateBlock; + +declare class StateBlock extends State { + /** Used in lists to determine if they interrupt a paragraph */ + parentType: 'blockquote' | 'list' | 'root' | 'paragraph' | 'reference'; + + eMarks: number[]; + bMarks: number[]; + bsCount: number[]; + sCount: number[]; + tShift: number[]; + + blkIndent: number; + ddIndent: number; + + line: number; + lineMax: number; + tight: boolean; +} diff --git a/types/markdown-it/lib/rules_core/state_core.d.ts b/types/markdown-it/lib/rules_core/state_core.d.ts new file mode 100644 index 0000000000..7cf73134aa --- /dev/null +++ b/types/markdown-it/lib/rules_core/state_core.d.ts @@ -0,0 +1,20 @@ +import MarkdownIt = require(".."); +import Token = require("../token"); + +export = StateCore; + +declare class StateCore { + env: any; + level: number; + + /** Link to parser instance */ + md: MarkdownIt; + + /** The markdown source code that is being parsed. */ + src: string; + + tokens: Token[]; + + /** Return any for a yet untyped property */ + [undocumented: string]: any; +} diff --git a/types/markdown-it/lib/rules_inline/state_inline.d.ts b/types/markdown-it/lib/rules_inline/state_inline.d.ts new file mode 100644 index 0000000000..27938d99da --- /dev/null +++ b/types/markdown-it/lib/rules_inline/state_inline.d.ts @@ -0,0 +1,46 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateInline; + +declare class StateInline extends State { + /** + * Stores `{ start: end }` pairs. Useful for backtrack + * optimization of pairs parse (emphasis, strikes). + */ + cache: { [start: number]: number }; + + /** Emphasis-like delimiters */ + delimiters: MarkdownIt.Delimiter[]; + + pending: string; + pendingLevel: number; + + /** Index of the first character of this token. */ + pos: number; + + /** Index of the last character that can be used (for example the one before the end of this line). */ + posMax: number; + + /** + * Push new token to "stream". + * If pending text exists, flush it as text token. + */ + push(type: string, tag: string, nesting: number): Token; + + /** Flush pending text */ + pushPending(): Token; + + /** + * Scan a sequence of emphasis-like markers and determine whether + * it can start an emphasis sequence or end an emphasis sequence. + * @param start - position to scan from (it should point to a valid marker) + * @param canSplitWord - determine if these markers can be found inside a word + */ + scanDelims(start: number, canSplitWord: boolean): { + can_open: boolean, + can_close: boolean, + length: number + }; +} diff --git a/types/markdown-it/lib/token.d.ts b/types/markdown-it/lib/token.d.ts new file mode 100644 index 0000000000..1f71d54bfd --- /dev/null +++ b/types/markdown-it/lib/token.d.ts @@ -0,0 +1,23 @@ +export = Token; + +declare class Token { + constructor(type: string, tag: string, nesting: number); + attrGet: (name: string) => string | null; + attrIndex: (name: string) => number; + attrJoin: (name: string, value: string) => void; + attrPush: (attrData: string[]) => void; + attrSet: (name: string, value: string) => void; + attrs: string[][]; + block: boolean; + children: Token[]; + content: string; + hidden: boolean; + info: string; + level: number; + map: number[]; + markup: string; + meta: any; + nesting: number; + tag: string; + type: string; +} diff --git a/types/markdown-it/markdown-it-tests.ts b/types/markdown-it/markdown-it-tests.ts index f22fc5cb2d..343661ad87 100644 --- a/types/markdown-it/markdown-it-tests.ts +++ b/types/markdown-it/markdown-it-tests.ts @@ -1,4 +1,6 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Renderer = require("markdown-it/lib/renderer"); +import Token = require("markdown-it/lib/token"); { const md = new MarkdownIt(); @@ -141,7 +143,7 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { return ""; }, }); - md.renderer.rules["image"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["image"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { const token = tokens[index]; const aIndex = token.attrIndex("src"); token.attrs[aIndex][1]; @@ -154,11 +156,11 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { if (md.renderer.rules["link_open"]) { defaultLinkRender = md.renderer.rules["link_open"]; } else { - defaultLinkRender = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + defaultLinkRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { return self.renderToken(tokens, index, options); }; } - md.renderer.rules["link_open"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["link_open"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { tokens[index].attrPush(["target", "_blank"]); tokens[index].attrPush(["rel", "nofollow"]); return defaultLinkRender(tokens, index, options, env, self); diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 71f89b3e1a..6cb49323fa 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1345,7 +1345,7 @@ declare namespace math { * the Matrix/array being traversed. * @returns Transformed map of x */ - map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)): Matrix | MathArray; + map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => MathType | string)): Matrix | MathArray; /** * Create a matrix filled with ones. The created matrix can have one or @@ -2876,6 +2876,7 @@ declare namespace math { interface Parser { eval(expr: string): any; get(variable: string): any; + getAll(): { [key: string]: any; }; set: (variable: string, value: any) => void; clear: () => void; } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 7c3dfaec35..babfa3ff37 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -179,6 +179,7 @@ Expressions examples const x = parser.get('x'); const f = parser.get('f'); + const y = parser.getAll(); const g = f(3, 3); parser.set('h', 500); @@ -270,6 +271,13 @@ Matrices examples math.range('2:-1:-3'); math.factorial(math.range('1:6')); } + + // map matrix + { + math.map([1, 2, 3], function(value) { + return value * value; + }); // returns [1, 4, 9] + } } /* diff --git a/types/meteor-astronomy/index.d.ts b/types/meteor-astronomy/index.d.ts new file mode 100644 index 0000000000..2bef7e728c --- /dev/null +++ b/types/meteor-astronomy/index.d.ts @@ -0,0 +1,109 @@ +// Type definitions for meteor-astronomy 2.6 +// Project: https://github.com/jagi/meteor-astronomy/ +// Definitions by: Igor Golovin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +declare namespace MeteorAstronomy { + type TypeOptionsPrimitives = typeof String | typeof Date | typeof Boolean | typeof Object | typeof Number; + type TypeOptions = TypeOptionsPrimitives | TypeOptionsPrimitives[] | Class | Enum; + type MongoQuery = object | string; + + interface SaveAndValidateOptions { + fields?: K[]; + stopOnFirstError?: boolean; + simulation?: boolean; + cast?: boolean; + } + + type SaveAndValidateCallback = (err: any, id: any) => void; + type RemoveCallback = (err: any, result: any) => void; + + interface Validator { + type: string; + param: any; + } + + interface ModelFullField { + type: TypeOptions; + optional?: boolean; + transient?: boolean; + immutable?: boolean; + default?: () => Field | Field; + index?: string | number; + validators?: Validator[]; + resolve?: (doc: Doc) => Field; + } + + type ModelField = ModelFullField | TypeOptions; + + type Fields = { + [P in keyof T]: ModelField; + }; + + interface ClassModel { + name: string; + collection?: Mongo.Collection; + fields: Fields; + behaviors?: object; + secured?: { + insert: boolean, + update: boolean, + remove: boolean, + } | boolean; + helpers?: object; + events?: object; + meteorMethods?: object; + indexes?: object; + } + + interface EnumModel { + name: string; + identifiers: T[] | object; + } + + type Model = T & { + set(fields: Partial, options?: {cast?: boolean; clone?: boolean; merge?: boolean}): void; + set(field: string, value: any): void; + get(field: string): any; + get(fields: string[]): any[]; + isModified(field?: string): boolean; + getModified(): any; + getModifiedValues(options?: {old?: boolean, raw?: boolean}): Partial; + getModifier(): any; + raw(): T; + raw(field: string): any; + raw(fields: string[]): any[]; + save(options?: SaveAndValidateOptions, callback?: SaveAndValidateCallback): void; + save(callback?: SaveAndValidateCallback): void; + copy(save: boolean): any; + validate(options?: SaveAndValidateOptions, callback?: SaveAndValidateCallback): void; + validate(callback?: SaveAndValidateCallback): void; + remove(callback?: RemoveCallback): void; + }; + + interface Class { + new(data?: Partial): Model; + + findOne(query?: MongoQuery): Model; + find(query?: MongoQuery): Array>; + update(search: object | string, query: object, callback?: () => void): void; + } + + interface Enum { + getValues(): any[]; + getIdentifier(identifier: T): any; + } +} + +declare module 'meteor/jagi:astronomy' { // tslint:disable-line:no-single-declare-module + namespace Class { + function create(model: MeteorAstronomy.ClassModel): MeteorAstronomy.Class; + } + + namespace Enum { + function create(model: MeteorAstronomy.EnumModel): MeteorAstronomy.Enum; + } +} diff --git a/types/meteor-astronomy/meteor-astronomy-tests.ts b/types/meteor-astronomy/meteor-astronomy-tests.ts new file mode 100644 index 0000000000..871c02964b --- /dev/null +++ b/types/meteor-astronomy/meteor-astronomy-tests.ts @@ -0,0 +1,148 @@ +import { Class, Enum } from 'meteor/jagi:astronomy'; +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; + +interface PostInterface { + title: string; + userId: string; + publishedAt: Date; +} + +const Posts = new Mongo.Collection('posts'); + +const Post = Class.create({ + name: 'Post', + collection: Posts, + fields: { + title: { + type: String, + validators: [{ + type: 'minLength', + param: 3 + }] + }, + userId: String, + publishedAt: Date + }, + behaviors: { + timestamp: {} + }, +}); + +let post = new Post({ + title: 'text', +}); + +// Validate length of the "title" field. +post.save(); + +// Notice that we call the "findOne" method +// from the "Post" class not from the "Posts" collection. +post = Post.findOne('id'); +// Auto convert a string input value to a number. +post.title = 'input[name=title]'; +post.publishedAt = new Date(); +// Check if all fields are valid and update document +// with only the fields that have changed. +post.save({fields: ['title']}); + +interface UserProfileInterface { + nickname: string; + firstName: string; + createdAt: Date; + age: number; +} + +const UserProfile = Class.create({ + name: 'UserProfile', + fields: { + nickname: String, + firstName: String, + createdAt: Date, + age: Number, + } +}); + +interface UserInterface extends Meteor.User { + address: object; + phone: string; + phoneNumber: string; +} + +const User = Class.create({ + name: 'User', + collection: Meteor.users as Mongo.Collection, + fields: { + createdAt: Number, + emails: { + type: [Object], + default: () => [], + }, + profile: { + type: UserProfile, + default: () => {}, + }, + address: { + type: Object, + optional: true + }, + phoneNumber: { + type: String, + }, + phone: { + type: String, + resolve(doc) { + return doc.phoneNumber; + } + } + }, + indexes: { + fullName: { // Index name. + fields: { // List of fields. + phoneNumber: 1, + createdAt: 1 + }, + options: {} + } + } +}); + +const user = User.findOne(); +user.set({username: 'user1'}); +user.save(); + +enum IStatus { + OPENED, CLOSED, DONE, CANCELED +} + +const Status = Enum.create({ + name: 'Status', + identifiers: IStatus, +}); + +const Issue = Class.create({ + name: 'Issue', + fields: { + status: { + type: Status + } + } +}); + +Status.getValues(); // [0, 1, 2, 3] + +const StatusBis = Enum.create({ + name: 'Status', + identifiers: { + OPENED: 5, + CLOSED: null, + DONE: 15, + CANCELED: undefined + } +}); + +StatusBis.getValues(); // [5, 6, 15, 16] + +const statusNumber = IStatus.OPENED; + +Status.getIdentifier(statusNumber); // "OPENED" diff --git a/types/meteor-astronomy/tsconfig.json b/types/meteor-astronomy/tsconfig.json new file mode 100644 index 0000000000..90412b0069 --- /dev/null +++ b/types/meteor-astronomy/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "meteor-astronomy-tests.ts" + ] +} diff --git a/types/meteor-astronomy/tslint.json b/types/meteor-astronomy/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/meteor-astronomy/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/module-deps/index.d.ts b/types/module-deps/index.d.ts new file mode 100644 index 0000000000..94706542a1 --- /dev/null +++ b/types/module-deps/index.d.ts @@ -0,0 +1,181 @@ +// Type definitions for module-deps 6.1 +// Project: https://github.com/browserify/module-deps +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as browserResolve from "browser-resolve"; + +/** + * Return an object transform stream 'd' that expects entry filenames or '{ id: ..., file: ... }' objects + * as input and produces objects for every dependency from a recursive module traversal as output. + */ +declare function moduleDeps(opts?: moduleDeps.Options): moduleDeps.ModuleDepsObject; + +/** + * Walk the dependency graph to generate json output that can be fed into browser-pack + */ +declare namespace moduleDeps { + /** + * module-deps constructor options + */ + interface Options { + /** + * A string or array of string transforms + */ + transform?: string | string[]; + + /** + * An array path of strings showing where to look in the package.json + * for source transformations. If falsy, don't look at the package.json at all + */ + transformKey?: string[]; + + /** + * Custom resolve function using the opts.resolve(id, parent, cb) signature that browser-resolve has + */ + resolve?: (id: string, opts: browserResolve.SyncOpts, cb: (err?: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => void) => void; + + /** + * A custom dependency detection function. opts.detect(source) should return an array of dependency module names. By default detective is used + */ + detect?: (source: string) => string[]; + + /** + * A function (id) to skip resolution of some module id strings. If defined, + * opts.filter(id) should return truthy for all the ids to include and falsey for all the ids to skip. + */ + filter?: (id: string) => boolean; + + /** + * A function (id, file, pkg) that gets called after id has been resolved. + * Return false to skip this file + */ + postFilter?: (id: string, file: string, pkg: PackageObject) => (void | boolean); // tslint:disable-line:void-return + + /** + * Transform the parsed package.json contents before using the values. + * opts.packageFilter(pkg, dir) should return the new pkg object to use. + */ + packageFilter?: (pkg: PackageObject, dir: string) => PackageObject; + + /** + * An array of absolute paths to not parse for dependencies. + * Use this for large dependencies like jquery or threejs which take forever to parse. + */ + noParse?: boolean | string[]; + + /** + * An object mapping filenames to file objects to skip costly io + */ + cache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to their parent package.json contents + * for browser fields, main entries, and transforms + */ + packageCache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to raw source to avoid reading from disk. + */ + fileCache?: { [fileName: string]: string }; + + /** + * A complex cache handler that allows async and persistent caching of data. + */ + persistentCache?: (file: string, id: string, pkg: PackageObject, fallback: (dataAsString: string, cb: CacheCallback) => void, cb: CacheCallback) => void; + + /** + * Array of global paths to search. Defaults to splitting on ':' in process.env.NODE_PATH + */ + paths?: string[]; + + /** + * Ignore files that failed to resolve + */ + ignoreMissing?: boolean; + + // un-documented options used by module-deps + basedir?: string; + globalTransform?: any[]; + extensions?: string[]; + modules?: { [name: string]: any }; + expose?: { [name: string]: string }; + + [prop: string]: any; + } + + interface ModuleDepsObject extends NodeJS.ReadWriteStream { + resolve(id: string, parent: { id: string }, cb: (err: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => any): any; + + readFile(file: string, id?: any, pkg?: PackageObject): NodeJS.ReadableStream; + + getTransforms(file: string, pkg: PackageObject, opts?: { builtin?: boolean; inNodeModules?: boolean }): NodeJS.ReadWriteStream; + + walk(id: string | { file: string; id: string; entry?: boolean; expose?: string; noparse?: boolean; source?: string }, + parent: { modules: any }, + cb: (err: Error | null, file?: string) => void): void; + + parseDeps(file: string, src: string, cb: any): any[]; + + lookupPackage(file: string, cb: (a: any, b: any, c?: any) => any): void; + + _isTopLevel(file: string): boolean; + _transform(row: string | InputRow | InputTransform, enc: string, next: () => void): void; + _flush(): void; + + /** + * Every time a transform is applied to a file, a 'transform' event fires with the instantiated transform stream tr. + */ + on(event: "transform", listener: (tr: any, file: string) => any): this; + /** + * Every time a file is read, this event fires with the file path. + */ + on(event: "file", listener: (file: string, id: string) => any): this; + /** + * When opts.ignoreMissing is enabled, this event fires for each missing package. + */ + on(event: "missing", listener: (id: string, parent: { id: string; filename: string; [prop: string]: any }) => any): this; + /** + * Every time a package is read, this event fires. The directory name of the package is available in pkg.__dirname. + */ + on(event: "package", listener: (package: PackageObject) => any): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + } + + type CacheCallback = (err: Error | null, res?: { source: string; package: any; deps: { [dep: string]: boolean } }) => void; + + interface InputRow { + file: string; + id: string; + entry?: boolean; + expose: string; + noparse?: boolean; + } + + interface InputTransform { + transform: string | (() => any); + options: any; + global?: boolean; + } + + interface TransformObject { + id: string; + file: string; + entry: boolean; + expose: string; + source: string; + deps: { [requireName: string]: any }; + } + + /** + * Placeholder, feel free to redefine or put in a pull request to improve + */ + interface PackageObject { + [prop: string]: any; + } +} + +export = moduleDeps; diff --git a/types/module-deps/module-deps-tests.ts b/types/module-deps/module-deps-tests.ts new file mode 100644 index 0000000000..e0930f8f88 --- /dev/null +++ b/types/module-deps/module-deps-tests.ts @@ -0,0 +1,95 @@ +import moduleDeps = require("module-deps"); + +function coreDepsTest() { + const coreDeps: { [prop: string]: any } = {}; + const coreModules = { + assert: "./assert.js", + buffer: "./buffer.js", + path: "./path.js" + }; + + const opts = { + resolve: () => { }, + modules: coreModules, + extensions: [".js", ".json"] + }; + + const s = moduleDeps(opts); + + s.on("data", (obj) => { + for (const dep of Object.keys(obj.deps)) { + if (dep in coreModules) { + coreDeps[dep] = true; + } + } + }); +} + +function rifiTest() { + const md = moduleDeps({ + resolve: (id, parent, cb) => { + const dependency = id.substr(1); + }, + transform: [], + globalTransform: [], + cache: {} + }); + + md.once("error", (err) => { + console.error(err); + }); +} + +function browserifyTest(opts: moduleDeps.Options) { + const packOpts: moduleDeps.Options = { + basedir: opts.basedir || "./", + externalRequireName: opts["externalRequireName"] || "require", + hasExports: opts["hasExports"] || false, + prelude: opts["prelude"] || undefined, + preludePath: opts["preludePath"] || undefined, + raw: opts["raw"] || false, + sourceMapPrefix: opts["sourceMapPrefix"] || "//#", + standalone: opts["standalone"] || undefined, + standaloneModule: opts["standaloneModule"] || undefined, + }; + + const res = moduleDeps(); // 'opts' are optional + const res2 = moduleDeps(packOpts); + + // ensure return value is a stream + const res3 = res.pipe(res2); + + res.on("error", (err: any) => { + console.error("module-deps error: ", err); + }); + + const inst: moduleDeps.ModuleDepsObject = moduleDeps({ + expose: { id: "file.txt" }, + extensions: [ ".js", ".json" ], + transform: [], + transformKey: ["browserify", "transform"], + filter: (id) => { + if (opts.filter && !opts.filter(id)) return false; + if (["name"].indexOf(id) >= 0) return false; + return true; + }, + postFilter: (id, file, pkg) => { + console.log("postFilter", id, file, pkg); + }, + globalTransform: [], + modules: {}, + resolve: (id, parent, cb) => { + cb(null, "", {}); + } + }); + + inst.on("file", (file, id) => { + console.log("file", file, id); + }); + inst.on("package", (pkg) => { + console.log("package", pkg); + }); + inst.on("transform", (tr, file) => { + console.log("transform", tr, file); + }); +} diff --git a/types/module-deps/tsconfig.json b/types/module-deps/tsconfig.json new file mode 100644 index 0000000000..5dd4af3cc1 --- /dev/null +++ b/types/module-deps/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", + "module-deps-tests.ts" + ] +} \ No newline at end of file diff --git a/types/module-deps/tslint.json b/types/module-deps/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/module-deps/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 07b36603d4..ab4d2f4c02 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -707,8 +707,8 @@ export interface Collection { findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ findOneAndUpdate(filter: FilterQuery, update: Object, callback: MongoCallback>): void; - findOneAndUpdate(filter: FilterQuery, update: Object, options?: FindOneAndReplaceOption): Promise>; - findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: Object, options?: FindOneAndUpdateOption): Promise>; + findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndUpdateOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; @@ -804,17 +804,17 @@ export interface Collection { /** @deprecated use updateOne, updateMany or bulkWrite */ update(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback): void; /** @deprecated use updateOne, updateMany or bulkWrite */ - update(filter: FilterQuery, update: UpdateQuery | TSchema, options?: ReplaceOneOptions & { multi?: boolean }): Promise; + update(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateOneOptions & { multi?: boolean }): Promise; /** @deprecated use updateOne, updateMany or bulkWrite */ - update(filter: FilterQuery, update: UpdateQuery | TSchema, options: ReplaceOneOptions & { multi?: boolean }, callback: MongoCallback): void; + update(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateOneOptions & { multi?: boolean }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */ updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback): void; - updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options?: CommonOptions & { upsert?: boolean }): Promise; - updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options: CommonOptions & { upsert?: boolean }, callback: MongoCallback): void; + updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateManyOptions): Promise; + updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateManyOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */ updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback): void; - updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options?: ReplaceOneOptions): Promise; - updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options: ReplaceOneOptions, callback: MongoCallback): void; + updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateOneOptions): Promise; + updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateOneOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#watch */ watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; } @@ -1158,13 +1158,17 @@ export interface FindAndModifyWriteOpResultObject { } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndReplace */ -export interface FindOneAndReplaceOption { +export interface FindOneAndReplaceOption extends CommonOptions { projection?: Object; sort?: Object; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean; - session?: ClientSession; +} + +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ +export interface FindOneAndUpdateOption extends FindOneAndReplaceOption { + arrayFilters?: Object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ @@ -1356,6 +1360,17 @@ export interface ReplaceOneOptions extends CommonOptions { bypassDocumentValidation?: boolean; } +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */ +export interface UpdateOneOptions extends ReplaceOneOptions { + arrayFilters?: Object[]; +} + +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */ +export interface UpdateManyOptions extends CommonOptions { + upsert?: boolean; + arrayFilters?: Object[]; +} + /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~updateWriteOpResult */ export interface UpdateWriteOpResult { result: { ok: number, n: number, nModified: number }; diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 19551684e0..92447c3e9d 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 5.2.13 +// Type definitions for Mongoose 5.3.4 // Project: http://mongoosejs.com/ // Definitions by: horiuchi // sindrenm @@ -13,6 +13,8 @@ // Idan Dardikman // Dominik Heigl // Fazendaaa +// Norman Perrin +// Dan Manastireanu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -390,6 +392,8 @@ declare module "mongoose" { useNewUrlParser?: boolean; /** Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify(). */ useFindAndModify?: boolean; + /** If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). */ + useCreateIndex?: boolean; // TODO safe?: any; @@ -408,11 +412,6 @@ declare module "mongoose" { * models associated with this connection. */ autoIndex?: boolean; - - /** - * If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). - */ - useCreateIndex?: boolean; }; } @@ -869,6 +868,7 @@ declare module "mongoose" { /** controls document#toObject behavior when called manually - defaults to true */ minimize?: boolean; read?: string; + writeConcern?: WriteConcern; /** defaults to true. */ safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean }; @@ -1119,7 +1119,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. @@ -1554,7 +1554,7 @@ declare module "mongoose" { * been using Query, we set it as an alias of DocumentQuery. */ class Query extends DocumentQuery { } - class DocumentQuery extends mquery { + class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. * Only use $where when you have a condition that cannot be met using other MongoDB @@ -1634,8 +1634,8 @@ declare module "mongoose" { * Specifying this query as a count query. Passing a callback executes the query. * @param criteria mongodb selector */ - count(callback?: (err: any, count: number) => void): Query; - count(criteria: any, callback?: (err: any, count: number) => void): Query; + count(callback?: (err: any, count: number) => void): Query & QueryHelpers; + count(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Specifies this query as a `countDocuments()` query. Behaves like `count()`, @@ -1656,8 +1656,8 @@ declare module "mongoose" { * @param {Function} [callback] optional params are (error, count) * @return {Query} this */ - countDocuments(callback?: (err: any, count: number) => void): Query; - countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query; + countDocuments(callback?: (err: any, count: number) => void): Query & QueryHelpers; + countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Estimates the number of documents in the MongoDB collection. Faster than @@ -1669,8 +1669,8 @@ declare module "mongoose" { * @param {Function} [callback] optional params are (error, count) * @return {Query} this */ - estimatedDocumentCount(callback?: (err: any, count: number) => void): Query; - estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query; + estimatedDocumentCount(callback?: (err: any, count: number) => void): Query & QueryHelpers; + estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a @@ -1679,10 +1679,10 @@ declare module "mongoose" { cursor(options?: any): QueryCursor; /** Declares or executes a distict() operation. Passing a callback executes the query. */ - distinct(callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(callback?: (err: any, res: any[]) => void): Query & QueryHelpers; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query & QueryHelpers; distinct(field: string, criteria: any | Query, - callback?: (err: any, res: any[]) => void): Query; + callback?: (err: any, res: any[]) => void): Query & QueryHelpers; /** Specifies an $elemMatch condition */ elemMatch(criteria: (elem: Query) => void): this; @@ -1706,9 +1706,9 @@ declare module "mongoose" { * query is executed, the result will be an array of documents. * @param criteria mongodb selector */ - find(callback?: (err: any, res: DocType[]) => void): DocumentQuery; + find(callback?: (err: any, res: DocType[]) => void): DocumentQuery & QueryHelpers; find(criteria: any, - callback?: (err: any, res: DocType[]) => void): DocumentQuery; + callback?: (err: any, res: DocType[]) => void): DocumentQuery & QueryHelpers; /** * Declares the query a findOne operation. When executed, the first found document is @@ -1717,36 +1717,36 @@ declare module "mongoose" { * @param criteria mongodb selector * @param projection optional fields to return */ - findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery; + findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery & QueryHelpers; findOne(criteria: any, - callback?: (err: any, res: DocType | null) => void): DocumentQuery; + callback?: (err: any, res: DocType | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, - callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, and returns * the found document (if any) to the callback. The query executes immediately if callback is passed. */ - findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery; + findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(update: any, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; /** * Specifies a $geometry condition. geometry() must come after either intersects() or within(). @@ -1804,7 +1804,7 @@ declare module "mongoose" { * getters/setters or other Mongoose magic applied. * @param bool defaults to true */ - lean(bool?: boolean): Query; + lean(bool?: boolean): Query & QueryHelpers; /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ limit(val: number): this; @@ -1928,8 +1928,8 @@ declare module "mongoose" { * you must first call remove() and then execute it by using the exec() method. * @param criteria mongodb selector */ - remove(callback?: (err: any) => void): Query; - remove(criteria: any | Query, callback?: (err: any) => void): Query; + remove(callback?: (err: any) => void): Query & QueryHelpers; + remove(criteria: any | Query, callback?: (err: any) => void): Query & QueryHelpers; /** Specifies which document fields to include or exclude (also known as the query "projection") */ select(arg: string | any): this; @@ -2007,20 +2007,20 @@ declare module "mongoose" { * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): new (...args: any[]) => Query; - toConstructor(): new (...args: any[]) => DocumentQuery; + toConstructor(): new (...args: any[]) => Query & QueryHelpers; + toConstructor(): new (...args: any[]) => DocumentQuery & QueryHelpers; /** * Declare and/or execute this query as an update() operation. * All paths passed that are not $atomic operations will become $set ops. * @param doc the update command */ - update(callback?: (err: any, affectedRows: number) => void): Query; - update(doc: any, callback?: (err: any, affectedRows: number) => void): Query; + update(callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; + update(doc: any, callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; update(criteria: any, doc: any, - callback?: (err: any, affectedRows: number) => void): Query; + callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; update(criteria: any, doc: any, options: QueryUpdateOptions, - callback?: (err: any, affectedRows: number) => void): Query; + callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; /** Specifies a path for use with chaining. */ where(path?: string | any, val?: any): this; @@ -2606,7 +2606,7 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#model-js */ export var Model: Model; - interface Model extends NodeJS.EventEmitter, ModelProperties { + interface Model extends NodeJS.EventEmitter, ModelProperties { /** * Model constructor * Provides the interface to MongoDB collections as well as creates document instances. @@ -2656,11 +2656,11 @@ declare module "mongoose" { * @param projection optional fields to return */ findById(id: any | string | number, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findById(id: any | string | number, projection: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findById(id: any | string | number, projection: any, options: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; model(name: string): Model; @@ -2668,7 +2668,7 @@ declare module "mongoose" { * Creates a Query and specifies a $where condition. * @param argument is a javascript string or anonymous function */ - $where(argument: string | Function): DocumentQuery; + $where(argument: string | Function): DocumentQuery & QueryHelpers; /** * Performs aggregations on the models collection. @@ -2680,7 +2680,7 @@ declare module "mongoose" { aggregate(aggregations: any[], cb: Function): Promise; /** Counts number of matching documents in a database collection. */ - count(conditions: any, callback?: (err: any, count: number) => void): Query; + count(conditions: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Counts number of documents matching `criteria` in a database collection. @@ -2694,8 +2694,8 @@ declare module "mongoose" { * @param {Function} [callback] * @return {Query} */ - countDocuments(callback?: (err: any, count: number) => void): Query; - countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query; + countDocuments(callback?: (err: any, count: number) => void): Query & QueryHelpers; + countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Estimates the number of documents in the MongoDB collection. Faster than @@ -2707,8 +2707,8 @@ declare module "mongoose" { * @param {Function} [callback] * @return {Query} */ - estimatedDocumentCount(callback?: (err: any, count: number) => void): Query; - estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query; + estimatedDocumentCount(callback?: (err: any, count: number) => void): Query & QueryHelpers; + estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Shortcut for saving one or more documents to the database. MyModel.create(docs) @@ -2728,9 +2728,9 @@ declare module "mongoose" { discriminator(name: string, schema: Schema): Model; /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query & QueryHelpers; distinct(field: string, conditions: any, - callback?: (err: any, res: any[]) => void): Query; + callback?: (err: any, res: any[]) => void): Query & QueryHelpers; /** * Sends ensureIndex commands to mongo for each index declared in the schema. @@ -2750,12 +2750,12 @@ declare module "mongoose" { * Finds documents. * @param projection optional fields to return */ - find(callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery; + find(callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; + find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; find(conditions: any, projection?: any | null, - callback?: (err: any, res: T[]) => void): DocumentQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; find(conditions: any, projection?: any | null, options?: any | null, - callback?: (err: any, res: T[]) => void): DocumentQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; @@ -2766,15 +2766,15 @@ declare module "mongoose" { * Executes immediately if callback is passed, else a Query object is returned. * @param id value of _id to query by */ - findByIdAndRemove(): DocumentQuery; + findByIdAndRemove(): DocumentQuery & QueryHelpers; findByIdAndRemove(id: any | number | string, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndRemove(id: any | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: any; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** @@ -2786,28 +2786,28 @@ declare module "mongoose" { */ findByIdAndDelete(): DocumentQuery; findByIdAndDelete(id: any | number | string, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndDelete(id: any | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: any; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) * is equivalent to findOneAndUpdate({ _id: id }, ...). * @param id value of _id to query by */ - findByIdAndUpdate(): DocumentQuery; + findByIdAndUpdate(): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, options: { upsert: true, new: true } & ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Finds one document. @@ -2815,20 +2815,20 @@ declare module "mongoose" { * @param projection optional fields to return */ findOne(conditions?: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOne(conditions: any, projection: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOne(conditions: any, projection: any, options: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issue a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed else a Query object is returned. */ - findOneAndRemove(): DocumentQuery; + findOneAndRemove(): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2839,16 +2839,16 @@ declare module "mongoose" { maxTimeMS?: number; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findOneAndDelete command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndDelete(): DocumentQuery; + findOneAndDelete(): DocumentQuery & QueryHelpers; findOneAndDelete(conditions: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOneAndDelete(conditions: any, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2865,7 +2865,7 @@ declare module "mongoose" { rawResult?: boolean; /** overwrites the schema's strict mode option for this update */ strict?: boolean|string; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command. @@ -2873,15 +2873,15 @@ declare module "mongoose" { * and returns the found document (if any) to the callback. The query executes immediately * if callback is passed else a Query object is returned. */ - findOneAndUpdate(): DocumentQuery; + findOneAndUpdate(): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, - callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, options: { upsert: true, new: true } & ModelFindOneAndUpdateOptions, - callback?: (err: any, doc: T, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, options: ModelFindOneAndUpdateOptions, - callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; /** * Implements $geoSearch functionality for Mongoose @@ -2898,7 +2898,7 @@ declare module "mongoose" { limit?: number; /** return the raw object instead of the Mongoose Model */ lean?: boolean; - }, callback?: (err: any, res: T[]) => void): DocumentQuery; + }, callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; /** * Shortcut for creating a new Document from existing raw data, @@ -2958,35 +2958,35 @@ declare module "mongoose" { callback?: (err: any, res: T) => void): Promise; /** Removes documents from the collection. */ - remove(conditions: any, callback?: (err: any) => void): Query; - deleteOne(conditions: any, callback?: (err: any) => void): Query; - deleteMany(conditions: any, callback?: (err: any) => void): Query; + remove(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; + deleteOne(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; + deleteMany(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; /** * Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set). * This function triggers the following middleware: replaceOne */ - replaceOne(conditions: any, replacement: any, callback?: (err: any, raw: any) => void): Query; + replaceOne(conditions: any, replacement: any, callback?: (err: any, raw: any) => void): Query & QueryHelpers; /** * Updates documents in the database without returning them. * All update values are cast to their appropriate SchemaTypes before being sent. */ update(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; update(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateOne(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateOne(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateMany(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateMany(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; /** Creates a Query, applies the passed conditions, and returns the Query. */ - where(path: string, val?: any): Query; + where(path: string, val?: any): Query & QueryHelpers; } interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties { diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 20b24ba887..da5daf7266 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -22,12 +22,12 @@ const connection2: Promise = mongoose.connect(connectUri, { pass: 'housan', config: { autoIndex: true, - useCreateIndex: true, }, mongos: true, bufferCommands: false, useNewUrlParser: true, useFindAndModify: true, + useCreateIndex: true }); const connection3: null = mongoose.connect(connectUri, function (error) { error.stack; @@ -1989,3 +1989,40 @@ db.createCollection('customers'). // visible outside of the transaction. then(() => session.commitTransaction()). then(() => Customer.findOne({ name: 'Test' }).exec()) + +/** + * https://mongoosejs.com/docs/guide.html#writeConcern + */ +new mongoose.Schema({ name: String }, { + writeConcern: { + w: 'majority', + j: true, + wtimeout: 1000 + } +}); + +/* Query helpers: https://mongoosejs.com/docs/guide.html#query-helpers */ + +interface Animal2 extends mongoose.Document { + name: string; + type: string; + tags: string[]; +} +var animal2Schema = new mongoose.Schema({ + name: String, + type: String, + tags: { type: [String], index: true } // field level +}); +let animal2QueryHelpers = { + byName>(this: Q, name: string) { + return this.where({ name: new RegExp(name, 'i') }); + } +}; +animal2Schema.query = animal2QueryHelpers; +var Animal2 = mongoose.model>('Animal', animal2Schema); +Animal2.find().byName('fido').exec(function(err, animals) { + console.log(animals); +}); +Animal2.findOne().byName('fido').exec(function(err, animal) { + console.log(animal); +}); diff --git a/types/moo/index.d.ts b/types/moo/index.d.ts index fa3a59d2ab..fd53f98e0a 100644 --- a/types/moo/index.d.ts +++ b/types/moo/index.d.ts @@ -104,7 +104,7 @@ export interface Token { /** * The number of line breaks found in the match. (Always zero if this rule has lineBreaks: false.) */ - lineBreaks: boolean; + lineBreaks: number; /** * The line number of the beginning of the match, starting from 1. */ diff --git a/types/n3/index.d.ts b/types/n3/index.d.ts index 31a2975bb0..0c8c992030 100644 --- a/types/n3/index.d.ts +++ b/types/n3/index.d.ts @@ -2,8 +2,9 @@ // Project: https://github.com/RubenVerborgh/N3.js // Definitions by: Fred Eisele // Ruben Taelman +// Laurens Rietveld // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// @@ -12,93 +13,123 @@ import * as stream from "stream"; import * as RDF from "rdf-js"; import { EventEmitter } from "events"; -export interface Prefixes { - [key: string]: RDF.NamedNode; +export interface Prefixes { + [key: string]: I; } -export class Term implements RDF.Term { - termType: "NamedNode" | "BlankNode" | "Literal" | "Variable" | "DefaultGraph"; - id: string; +export type Term = NamedNode | BlankNode | Literal | Variable | DefaultGraph; +export type PrefixedToIri = (suffix: string) => RDF.NamedNode; + +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; @@ -109,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. @@ -131,79 +162,79 @@ 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 { format?: string; - prefixes?: Prefixes; + prefixes?: Prefixes; end?: boolean; } 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: string, done?: () => void): void; - addPrefixes(prefixes: Prefixes, done?: () => void): 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; @@ -218,6 +249,9 @@ export namespace Util { function isVariable(value: RDF.Term | null): boolean; function isDefaultGraph(value: RDF.Term | null): boolean; function inDefaultGraph(value: RDF.Quad): boolean; - function prefix(iri: string, factory?: RDF.DataFactory): (suffix: string) => RDF.NamedNode; - function prefixes(defaultPrefixes: Prefixes, factory?: RDF.DataFactory): (iri: string) => (suffix: string) => RDF.NamedNode; + function prefix(iri: RDF.NamedNode|string, factory?: RDF.DataFactory): PrefixedToIri; + function prefixes( + defaultPrefixes: Prefixes, + factory?: RDF.DataFactory + ): (prefix: string) => PrefixedToIri; } diff --git a/types/n3/n3-tests.ts b/types/n3/n3-tests.ts index a061777ad7..58d10892da 100644 --- a/types/n3/n3-tests.ts +++ b/types/n3/n3-tests.ts @@ -17,7 +17,8 @@ function test_add_prefixes() { writer.addPrefixes({ freebase: N3.DataFactory.namedNode("http://rdf.freebase.com/ns/"), - xsd: N3.DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#") + xsd: N3.DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#"), + rdf: 'http://test' }); writer.end((error, result) => { @@ -31,7 +32,7 @@ function test_serialize() { format: "ttl", prefixes: { foaf: "http://xmlns.com/foaf/0.1", - freebase: "http://rdf.freebase.com/ns/", + freebase: N3.DataFactory.namedNode("http://rdf.freebase.com/ns/"), g: "http://base.google.com/ns/1.0" } }); @@ -76,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(); @@ -177,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/next-server/router.d.ts b/types/next-server/router.d.ts index dff4f13a79..190138e3ed 100644 --- a/types/next-server/router.d.ts +++ b/types/next-server/router.d.ts @@ -82,13 +82,19 @@ export interface WithRouterProps { router: SingletonRouter; } +/** + * Remove properties `K` from `T`. + * + * @internal + */ +export type Omit = T extends any ? Pick> : never; + // Manually disabling the no-unnecessary-generics rule so users can -// retain type inference if they warp their component in withRouter +// retain type inference if they wrap their component in withRouter // without defining props explicitly export function withRouter( - // tslint:disable-next-line:no-unnecessary-generics - Component: React.ComponentType> -): React.ComponentType; + Component: React.ComponentType> +): React.ComponentType>>; declare const Router: SingletonRouter; export default Router; diff --git a/types/next-server/test/next-server-router-tests.tsx b/types/next-server/test/next-server-router-tests.tsx index 8b4397baad..bac699b4e7 100644 --- a/types/next-server/test/next-server-router-tests.tsx +++ b/types/next-server/test/next-server-router-tests.tsx @@ -70,14 +70,14 @@ Router.prefetch("/route").then(Component => { const element = ; }); -interface TestComponentProps { +interface TestComponentProps extends WithRouterProps { testValue: string; } -class TestComponent extends React.Component { +class TestComponent extends React.Component { state = { ready: false }; - constructor(props: TestComponentProps & WithRouterProps) { + constructor(props: TestComponentProps) { super(props); props.router.ready(() => { this.setState({ ready: true }); @@ -97,12 +97,57 @@ class TestComponent extends React.Component { + state = { ready: false }; + + constructor(props: TestComponent2Props) { + super(props); + props.router.ready(() => { + this.setState({ ready: true }); + }); + } + + render() { + return ( +

+ ); + } +} + +const TestComponent2WithRouter = withRouter(TestComponent2); +const res = ; + interface TestSFCQuery { test?: string; } -interface TestSFCProps extends WithRouterProps { } +interface TestSFCProps extends WithRouterProps { + testProp: string; +} const TestSFC: React.SFC = ({ router }) => { return
{router.query && router.query.test}
; }; +const TestSFCComponent = withRouter(TestSFC); + +const res2 = ; + +const TestSFC2 = withRouter(({ router }) => { + return
{router.query && router.query.test}
; +}); + +const res3 = ; + +const TestSFC3 = withRouter(({ router }) => { + return
{router.query && router.query.test}
; +}); + +const res4 = ; diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 99d3f5b45d..88d44b169a 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -73,7 +73,9 @@ declare module "node-forge" { prng?: any; algorithm?: string; } - + + function setPublicKey(n: any, e: any): any; + function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; } @@ -141,7 +143,8 @@ declare module "node-forge" { hash: any; }; extensions: any[]; - publicKey: any; + privateKey: Key; + publicKey: Key; md: any; /** * Sets the subject of this certificate. @@ -198,6 +201,16 @@ declare module "node-forge" { function decryptRsaPrivateKey(pem: PEM, passphrase?: string): Key; function createCertificate(): Certificate; + + function certificationRequestToPem(cert: Certificate, maxline?: number): PEM; + + function certificationRequestFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; + + function createCertificationRequest(): Certificate; + + function publicKeyToAsn1(publicKey: Key): any; + + function publicKeyToRSAPublicKey(publicKey: Key): any; } namespace ssh { @@ -411,6 +424,7 @@ declare module "node-forge" { function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; } + namespace pkcs7 { interface PkcsSignedData { content?: string | util.ByteBuffer; @@ -446,6 +460,10 @@ declare module "node-forge" { namespace sha256 { function create(): MessageDigest; } + + namespace sha512 { + function create(): MessageDigest; + } namespace md5 { function create(): MessageDigest; @@ -470,4 +488,14 @@ declare module "node-forge" { output: util.ByteStringBuffer; } } + + namespace pss { + function create(any: any): any; + } + + namespace mgf { + namespace mgf1 { + function create(any: any): any; + } + } } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 48d8340522..ee3fdad616 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -30,6 +30,7 @@ // Wilco Bakker // wwwy3y3 // Zane Hannan AU +// Jeremie Rodriguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -5665,7 +5666,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, * until an absolute path is found. If after using all {from} paths still no absolute path is found, @@ -6394,7 +6395,7 @@ declare module "crypto" { interface BasePrivateKeyEncodingOptions { format: T; - ciper: string; + cipher: string; passphrase: string; } diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index f243aa649e..ae26f38a46 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -1513,7 +1513,7 @@ async function asyncStreamPipelineFinished() { type: 'pkcs1', }, privateKeyEncoding: { - ciper: 'some-cipher', + cipher: 'some-cipher', format: 'pem', passphrase: 'secret', type: 'pkcs8', @@ -1531,7 +1531,7 @@ async function asyncStreamPipelineFinished() { type: 'spki', }, privateKeyEncoding: { - ciper: 'some-cipher', + cipher: 'some-cipher', format: 'der', passphrase: 'secret', type: 'pkcs8', @@ -1548,7 +1548,7 @@ async function asyncStreamPipelineFinished() { type: 'pkcs1', }, privateKeyEncoding: { - ciper: 'some-cipher', + cipher: 'some-cipher', format: 'pem', passphrase: 'secret', type: 'pkcs8', diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 2e91826cc8..1f29bbcc10 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -1483,7 +1483,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index a241b8b87e..26210a1857 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -2055,7 +2055,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 98b3f503c6..250a7b6640 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -3040,7 +3040,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index b834d238d4..55cea44126 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -3065,7 +3065,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index e0f904b1b0..d0497223dc 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -4770,7 +4770,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 1ea05db2b0..e7a6c41b10 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -4856,7 +4856,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/normalize-url/index.d.ts b/types/normalize-url/index.d.ts index ec70be130b..fd76c4f72a 100644 --- a/types/normalize-url/index.d.ts +++ b/types/normalize-url/index.d.ts @@ -1,14 +1,20 @@ -// Type definitions for normalize-url 1.9 +// Type definitions for normalize-url 3.3 // Project: https://github.com/sindresorhus/normalize-url // Definitions by: odin3 // BendingBender +// Mathieu M-Gosselin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace normalizeUrl { interface Options { + defaultProtocol?: string; + forceHttp?: boolean; + forceHttps?: boolean; normalizeProtocol?: boolean; normalizeHttps?: boolean; + sortQueryParameters?: boolean; stripFragment?: boolean; + stripHash?: boolean; stripWWW?: boolean; removeQueryParameters?: Array; removeTrailingSlash?: boolean; diff --git a/types/npm-package-arg/index.d.ts b/types/npm-package-arg/index.d.ts index bb1a0d8550..d83c95a6a7 100644 --- a/types/npm-package-arg/index.d.ts +++ b/types/npm-package-arg/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for npm-package-arg 5.1 +// Type definitions for npm-package-arg 6.1 // Project: https://github.com/npm/npm-package-arg // Definitions by: Melvin Groenhoff +// Jason // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /** * Throws if the package name is invalid, a dist-tag is invalid or a URL's protocol is not supported. @@ -20,7 +22,12 @@ declare namespace npa { * Something like: 1.2, ^1.7.17, http://x.com/foo.tgz, git+https://github.com/user/foo, bitbucket:user/foo, file:foo.tar.gz or file:../foo/bar/. If not included then the default is latest. * @param where Optionally the path to resolve file paths relative to. Defaults to process.cwd() */ - function resolve(name: string, spec: string, where?: string): Result; + function resolve(name: string, spec: string, where?: string): + FileResult | + HostedGitResult | + URLResult | + AliasResult | + RegistryResult; class Result { /** @@ -33,52 +40,95 @@ declare namespace npa { * * directory - A local directory. * * remote - An http url (presumably to a tgz) */ - type: "git" | "tag" | "version" | "range" | "file" | "directory" | "remote"; - /** - * If true this specifier refers to a resource hosted on a registry. This is true for tag, version and range types. - */ + type: + | "git" + | "tag" + | "version" + | "range" + | "file" + | "directory" + | "remote" + | "alias"; + + /** If true this specifier refers to a resource hosted on a registry. This is true for tag, version and range types. */ registry: boolean; - /** - * If known, the name field expected in the resulting pkg. - */ + + /** If known, the name field expected in the resulting pkg. */ name: string | null; - /** - * If a name is something like @org/module then the scope field will be set to @org. If it doesn't have a scoped name, then scope is null. - */ + + /** If a name is something like @org/module then the scope field will be set to @org. If it doesn't have a scoped name, then scope is null. */ scope: string | null; - /** - * A version of name escaped to match the npm scoped packages specification. Mostly used when making requests against a registry. When name is null, escapedName will also be null. - */ + + /** A version of name escaped to match the npm scoped packages specification. Mostly used when making requests against a registry. When name is null, escapedName will also be null. */ escapedName: string | null; - /** - * The specifier part that was parsed out in calls to npa(arg), or the value of spec in calls to `npa.resolve(name, spec). - */ + + /** The specifier part that was parsed out in calls to npa(arg), or the value of spec in calls to `npa.resolve(name, spec). */ rawSpec: string; - /** - * The normalized specifier, for saving to package.json files. null for registry dependencies. - */ + + /** The normalized specifier, for saving to package.json files. null for registry dependencies. */ saveSpec: string | null; - /** - * The version of the specifier to be used to fetch this resource. null for shortcuts to hosted git dependencies as there isn't just one URL to try with them. - */ + + /** The version of the specifier to be used to fetch this resource. null for shortcuts to hosted git dependencies as there isn't just one URL to try with them. */ fetchSpec: string | null; - /** - * If set, this is a semver specifier to match against git tags with - */ + + /** If set, this is a semver specifier to match against git tags with */ gitRange?: string; - /** - * If set, this is the specific committish to use with a git dependency. - */ + + /** If set, this is the specific committish to use with a git dependency. */ gitCommittish?: string; - /** - * If from === 'hosted' then this will be a hosted-git-info object. This property is not included when serializing the object as JSON. - */ - hosted?: any; - /** - * The original un-modified string that was provided. If called as npa.resolve(name, spec) then this will be name + '@' + spec. - */ + + /** If from === 'hosted' then this will be a hosted-git-info object. This property is not included when serializing the object as JSON. */ + hosted?: HostedGit; + + /** The original un-modified string that was provided. If called as npa.resolve(name, spec) then this will be name + '@' + spec. */ raw: string; } + + interface FileResult extends Result { + type: "file" | "directory"; + where: string; + saveSpec: string; + fetchSpec: null | string; + } + + interface HostedGitResult extends Result { + type: "git"; + hosted: HostedGit; + saveSpec: string; + fetchSpec: null | string; + gitRange: undefined | string; + gitCommittish: undefined | string; + } + + interface URLResult extends Result { + saveSpec: string; + type: "git" | "remote"; + fetchSpec: string; + gitCommittish: string | undefined; + gitRange: string | undefined; + } + + interface AliasResult extends Result { + subSpec: Result; + registry: true; + type: "alias"; + saveSpec: null; + fetchSpec: null; + } + + interface RegistryResult extends Result { + registry: true; + type: "version" | "range" | "tag"; + saveSpec: null; + fetchSpec: string; + } + + interface HostedGit { + type: string; + domain: string; + user: string; + project: string; + } } export = npa; diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 0f2d005973..26631c8c1d 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1035,6 +1035,10 @@ declare namespace Office { * 12007 * A dialog box is already opened from the task pane. A task pane add-in can only have one dialog box open at a time. * + * + * 12009 + * The user chose to ignore the dialog box. This error can occur in online versions of Office, where users may choose not to allow an add-in to present a dialog. + * * * * In the callback function passed to the displayDialogAsync method, you can use the properties of the AsyncResult object to return the @@ -1070,9 +1074,9 @@ declare namespace Office { displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; /** * Delivers a message from the dialog box to its parent/opener page. The page calling this API must be on the same domain as the parent. - * @param messageObject Accepts a message from the dialog to deliver to the add-in. + * @param message Accepts a message from the dialog to deliver to the add-in. In addition to a boolean, anything that can serialized to a string including JSON and XML can be sent. */ - messageParent(messageObject: any): void; + messageParent(message: boolean | string): void; /** * Closes the UI container where the JavaScript is executing. * @@ -1212,7 +1216,7 @@ declare namespace Office { * * Example: `[{cells: Office.Table.Data, format: {fontColor: "yellow"}}, {cells: {row: 3, column: 4}, format: {borderColor: "white", fontStyle: "bold"}}]` */ - cellFormat?: Array + cellFormat?: RangeFormatConfiguration[] /** * Explicitly sets the shape of the data object. If not supplied is inferred from the data type. */ @@ -1220,7 +1224,7 @@ declare namespace Office { /** * Only for table bindings in content add-ins for Access. Array of strings. Specifies the column names. */ - columns?: Array + columns?: string[] /** * Only for table bindings in content add-ins for Access. Specifies the pre-defined string "thisRow" to get data in the currently selected row. */ @@ -1334,7 +1338,7 @@ declare namespace Office { /** * The names of the columns involved in the binding. */ - columns?: Array + columns?: string[] /** * A user-defined item of any type that is returned, unchanged, in the asyncContext property of the AsyncResult object that is passed to a callback. */ @@ -1407,7 +1411,7 @@ declare namespace Office { * * Example: `[\{cells: Office.Table.Data, format: \{fontColor: "yellow"\}\}, \{cells: \{row: 3, column: 4\}, format: \{borderColor: "white", fontStyle: "bold"\}\}]` */ - cellFormat?: Array + cellFormat?: RangeFormatConfiguration[] /** * Explicitly sets the shape of the data object. If not supplied is inferred from the data type. */ @@ -1822,6 +1826,14 @@ declare namespace Office { * [Api set: Mailbox 1.7] */ AppointmentTimeChanged, + /** + * Triggers when an attachment is added to or removed from an item. + * + * [Api set: Mailbox Preview] + * + * @beta + */ + AttachmentsChanged, /** * Occurs when data within the binding is changed. * To add an event handler for the BindingDataChanged event of a binding, use the addHandlerAsync method of the Binding object. @@ -1918,6 +1930,8 @@ declare namespace Office { * Triggers when the OfficeTheme is changed in Outlook. * * [Api set: Mailbox Preview] + * + * @beta */ OfficeThemeChanged, /** @@ -7340,6 +7354,57 @@ declare namespace Office { declare namespace Office { namespace MailboxEnums { + /** + * Specifies the formatting that applies to an attachment's content. + * + * [Api set: Mailbox Preview] + * + * @remarks + *
+ * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} + * Compose or read
+ * + * @beta + */ + enum AttachmentContentFormat { + /** + * The content of the attachment is returned as a base64-encoded string. + */ + Base64 = "base64", + + /** + * The content of the attachment is returned as a string representing a URL. + */ + Url = "url", + + /** + * The content of the attachment is returned as a string representing an .eml formatted file. + */ + Eml = "eml" + } + /** + * Specifies whether an attachment was added to or removed from an item. + * + * [Api set: Mailbox Preview] + * + * @remarks + *
+ * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} + * Compose or read
+ * + * @beta + */ + enum AttachmentStatus { + /** + * An attachment was added to the item. + */ + Added = "added", + + /** + * An attachment was removed from the item. + */ + Removed = "removed" + } /** * Specifies an attachment's type. * @@ -8494,6 +8559,31 @@ declare namespace Office { */ subject: string; } + /** + * Represents the content of an attachment on a message or appointment item. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
+ * + * @beta + */ + interface AttachmentContent { + /** + * The content of an attachment as a string. + */ + content: string; + /** + * The string format to use for an attachment's content. + * For file attachments, the formatting is a base64-encoded string. + * For item attachments that represent messages, the formatting is a string representing an .eml formatted file. + * For cloud attachments, the formatting is a URL string. + */ + format: Office.MailboxEnums.AttachmentContentFormat; + } /** * Represents an attachment on an item from the server. Read mode only. * @@ -8562,7 +8652,7 @@ declare namespace Office { * * In addition to this signature, this method also has the following signature: * - * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` + * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` * * @param coercionType The format for the returned body. * @param options Optional. An object literal that contains one or more of the following properties: @@ -8570,7 +8660,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Returns the current body in a specified format. * @@ -8591,7 +8681,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Gets a value that indicates whether the content is in HTML or text format. @@ -8615,7 +8705,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (
) to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8649,7 +8739,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8673,7 +8763,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8694,7 +8784,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8714,7 +8804,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8749,7 +8839,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8774,7 +8864,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8798,7 +8888,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8821,7 +8911,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8856,7 +8946,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8881,7 +8971,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8905,7 +8995,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8938,7 +9028,7 @@ declare namespace Office { /** * An array of strings containing the mailing and street addresses associated with the contact. Nullable. */ - addresses: Array; + addresses: string[]; /** * A string containing the name of the business associated with the contact. Nullable. */ @@ -8946,7 +9036,7 @@ declare namespace Office { /** * An array of strings containing the SMTP email addresses associated with the contact. Nullable, */ - emailAddresses: Array; + emailAddresses: string[]; /** * A string containing the name of the person associated with the contact. Nullable. */ @@ -8954,11 +9044,11 @@ declare namespace Office { /** * An array containing a PhoneNumber object for each phone number associated with the contact. Nullable. */ - phoneNumbers: Array; + phoneNumbers: PhoneNumber[]; /** * An array of strings containing the Internet URLs associated with the contact. Nullable. */ - urls: Array; + urls: string[]; } /** * The CustomProperties object represents custom properties that are specific to a particular item and specific to a mail add-in for Outlook. @@ -9279,6 +9369,154 @@ declare namespace Office { getAsync(callback?: (result: AsyncResult) => void): void; } + /** + * The InternetHeaders object represents properties that are preserved after the item leaves Exchange and converted to a MIME message. + * These properties are stored as x-headers in the MIME message. + * + * InternetHeaders are stored as key/value pairs on a per-item basis. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
+ * + * @beta + */ + export interface InternetHeaders { + /** + * Given an array of internet header names, this method returns a dictionary containing those internet headers and their values. + * If the add-in requests an x-header that is not available, that x-header will not be returned in the results. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
+ * + * In addition to this signature, this method also has the following signature: + * + * `getAsync(names: string[], callback: (result: AsyncResult) => void): void;` + * + * @param names The names of the internet headers to be returned. + * @param options Optional. An object literal that contains one or more of the following properties: + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + getAsync(names: string[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Given an array of internet header names, this method returns a dictionary containing those internet headers and their values. + * If the add-in requests an x-header that is not available, that x-header will not be returned in the results. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
+ * + * @param names The names of the internet headers to be returned. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + getAsync(names: string[], callback?: (result: AsyncResult) => void): void; + /** + * Given an array of internet header names, this method removes the specified headers from the internet header collection. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
+ * + * In addition to this signature, this method also has the following signature: + * + * `removeAsync(names: string[], callback: (result: AsyncResult) => void): void;` + * + * @param names The names of the internet headers to be removed. + * @param options Optional. An object literal that contains one or more of the following properties: + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + removeAsync(names: string[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Given an array of internet header names, this method removes the specified headers from the internet header collection. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
+ * + * @param names The names of the internet headers to be removed. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + removeAsync(names: string[], callback?: (result: AsyncResult) => void): void; + /** + * Sets the specified internet headers to the specified values. + * + * The setAsync method creates a new header if the specified header does not already exist; otherwise, the existing value is replaced with + * the new value. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * In addition to this signature, this method also has the following signatures: + * + * `setAsync(headers: string, callback: (result: AsyncResult) => void): void;` + * + * @param headers The names and corresponding values of the headers to be set. Should be a dictionary object with keys being the names of the + * internet headers and values being the values of the internet headers. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. + * Any errors encountered will be provided in the asyncResult.error property. + * + * @beta + */ + setAsync(headers: Object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets the specified internet headers to the specified values. + * + * The setAsync method creates a new header if the specified header does not already exist; otherwise, the existing value is replaced with + * the new value. + * + * [Api set: Mailbox Preview] + * + * @remarks + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
+ * + * + * + * @param headers The names and corresponding values of the headers to be set. Should be a dictionary object with keys being the names of the + * internet headers and values being the values of the internet headers. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. + * Any errors encountered will be provided in the asyncResult.error property. + * + * @beta + */ + setAsync(headers: Object, callback?: (result: AsyncResult) => void): void; + } + /** * Represents the appointment organizer, even if an alias or a delegate was used to create the appointment. * This object provides a method to get the organizer value of an appointment in an Outlook add-in. @@ -9669,7 +9907,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -9696,7 +9935,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -9855,6 +10094,26 @@ declare namespace Office { *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
*/ close(): void; + /** + * Gets the item's attachments as an array. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
+ * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. If the call fails, the asyncResult.error property will contain and error code with the reason for + * the failure. + * + * @beta + */ + getAttachmentsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is activated by an actionable message. * @@ -9963,8 +10222,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -9997,8 +10256,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -10019,8 +10278,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -10044,8 +10303,8 @@ declare namespace Office { * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. * In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -10067,7 +10326,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -10081,7 +10340,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -10093,7 +10352,8 @@ declare namespace Office { /** * Removes an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -10103,7 +10363,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -10147,13 +10407,13 @@ declare namespace Office { * * `saveAsync(options: Office.AsyncContextOptions): void;` * - * `saveAsync(callback: (result: AsyncResult) => void): void;` + * `saveAsync(callback: (result: AsyncResult) => void): void;` * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. */ - saveAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + saveAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Asynchronously saves an item. * @@ -10254,7 +10514,7 @@ declare namespace Office { * * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. */ - saveAsync(callback: (result: AsyncResult) => void): void; + saveAsync(callback: (result: AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -10378,7 +10638,7 @@ declare namespace Office { */ interface AppointmentRead extends Appointment, ItemRead { /** - * Gets an array of attachments for the item. + * Gets the item's attachments as an array. * * [Api set: Mailbox 1.0] * @@ -10682,7 +10942,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -10710,7 +10970,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11063,7 +11323,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11077,7 +11337,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -11090,7 +11350,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11100,7 +11360,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -11237,7 +11497,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11264,7 +11525,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11281,6 +11543,36 @@ declare namespace Office { * asyncResult, which is an Office.AsyncResult object. */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; + + /** + * Gets an attachment from a message or appointment and returns it as an `Office.AttachmentContent` object. + * + * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use + * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or + * `item.attachments` call. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
ErrorsInvalidAttachmentId - The attachment identifier does not exist.
+ * + * @param attachmentId The identifier of the attachment you want to get. The maximum length of the string is 100 characters. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. If the call fails, the asyncResult.error property will contain and error code + * with the reason for the failure. + * + * @beta + */ + getAttachmentContentAsync(attachmentId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. @@ -11384,7 +11676,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11398,7 +11690,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -11412,7 +11704,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11422,7 +11714,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -11732,6 +12024,26 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose */ close(): void; + /** + * Gets the item's attachments as an array. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
+ * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. If the call fails, the asyncResult.error property will contain and error code with the reason for + * the failure. + * + * @beta + */ + getAttachmentsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is activated by an actionable message. * @@ -11818,8 +12130,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -11853,8 +12165,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -11875,8 +12187,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -11899,8 +12211,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -12192,7 +12504,7 @@ declare namespace Office { */ interface ItemRead extends Item { /** - * Gets an array of attachments for the item. + * Gets the item's attachments as an array. * * [Api set: Mailbox 1.0] * @@ -12740,6 +13052,22 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ from: Office.From; + /** + * Sets the internet headers of a message. + * + * The internetHeaders property returns an InternetHeaders object that provides methods to manage the internet headers on the message. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
+ * + * @beta + */ + internetHeaders: Office.InternetHeaders; /** * Gets the type of item that an instance represents. * @@ -12978,7 +13306,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13005,7 +13334,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13166,6 +13495,26 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ close(): void; + /** + * Gets the item's attachments as an array. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
+ * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. If the call fails, the asyncResult.error property will contain and error code with the reason for + * the failure. + * + * @beta + */ + getAttachmentsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is activated by an actionable message. * @@ -13278,8 +13627,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13313,8 +13662,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13335,8 +13684,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13359,8 +13708,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13382,7 +13731,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13396,7 +13745,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -13409,7 +13758,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13419,7 +13768,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -13694,7 +14043,7 @@ declare namespace Office { */ interface MessageRead extends Message, ItemRead { /** - * Gets an array of attachments for the item. + * Gets the item's attachments as an array. * * [Api set: Mailbox 1.0] * @@ -13802,6 +14151,22 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read */ from: EmailAddressDetails; + /** + * Gets the internet headers of a message. + * + * The internetHeaders property returns an InternetHeaders object that provides methods to manage the internet headers on the message. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read
+ * + * @beta + */ + internetHeaders: Office.InternetHeaders; /** * Gets the Internet message identifier for an email message. * @@ -14014,7 +14379,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14042,7 +14407,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14399,7 +14764,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14413,7 +14778,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -14426,7 +14791,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14436,7 +14801,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -14725,7 +15090,7 @@ declare namespace Office { */ restUrl: string; /** - * Information about the user associated with the mailbox. This includes their account type, display name, email adddress, and time zone. + * Information about the user associated with the mailbox. This includes their account type, display name, email address, and time zone. * * More information is under {@link Office.UserProfile} */ @@ -14733,7 +15098,7 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently, the supported event types are `Office.EventType.ItemChanged` and `Office.EventType.OfficeThemeChanged`. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -15139,6 +15504,27 @@ declare namespace Office { * @param userContext Optional. Any state data that is passed to the asynchronous method. */ makeEwsRequestAsync(data: any, callback: (result: AsyncResult) => void, userContext?: any): void; + /** + * Removes an event handler for a supported event. + * + * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * + * [Api set: Mailbox 1.5] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
+ * + * @param eventType The event that should revoke the handler. + * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. + * The type property on the parameter will match the eventType parameter passed to addHandlerAsync. + * @param options Optional. Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. + */ + removeHandlerAsync(eventType: Office.EventType, handler: (type: EventType) => void, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } /** @@ -16444,7 +16830,7 @@ declare namespace Office { */ owner: String; /** - * The remote REST url related to the owner’s mailbox. + * The remote REST URL related to the owner’s mailbox. */ restUrl: String; /** @@ -16768,7 +17154,7 @@ declare namespace Office { } /** - * Information about the user associated with the mailbox. This includes their account type, display name, email adddress, and time zone. + * Information about the user associated with the mailbox. This includes their account type, display name, email address, and time zone. * * [Api set: Mailbox 1.0] * @@ -17104,7 +17490,7 @@ declare namespace OfficeExtension { * If there was an error, this contains all trace messages that were executed before the error occurred. * These messages can help you monitor the program execution sequence and detect the case of the error. */ - traceMessages: Array; + traceMessages: string[]; /** Debug info (useful for detailed logging of the error, i.e., via `JSON.stringify(...)`). */ debugInfo: DebugInfo; /** Inner error, if applicable. */ @@ -19891,7 +20277,7 @@ declare namespace Excel { * @param key The Key of the new setting. * @param value The Value for the new setting. */ - add(key: string, value: string | number | boolean | Date | Array | any): Excel.Setting; + add(key: string, value: string | number | boolean | Date | any[] | any): Excel.Setting; /** * * Gets the number of Settings in the collection. @@ -21397,12 +21783,11 @@ declare namespace Excel { inCellDropDown: boolean; /** * - * Source of the list for data validation - When setting the value, it can be passed in as a Excel Range object, or a string that contains comma separated number, boolean or date. + * The source of the list for data validation. The value is a string, which can either be a range reference (e.g. `"=Names!$A$1:$A$3"`) or a comma-separated list of the values themselves. * * [Api set: ExcelApi 1.8] */ - source: string | Range; + source: string; } /** * diff --git a/types/on-wake-up/index.d.ts b/types/on-wake-up/index.d.ts new file mode 100644 index 0000000000..c9568404b8 --- /dev/null +++ b/types/on-wake-up/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for on-wake-up 1.0 +// Project: https://github.com/mafintosh/on-wake-up +// Definitions by: Klaus Meinhardt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Register a callback when the device presumably wakes up from sleep. + * @param cb The callback to execute + * @returns Function to unregister the callback + */ +declare function onWakeUp(cb: () => void): () => void; + +export = onWakeUp; diff --git a/types/on-wake-up/on-wake-up-tests.ts b/types/on-wake-up/on-wake-up-tests.ts new file mode 100644 index 0000000000..985d415063 --- /dev/null +++ b/types/on-wake-up/on-wake-up-tests.ts @@ -0,0 +1,4 @@ +import onWakeUp = require('on-wake-up'); + +const unregister = onWakeUp(() => void 0); +unregister(); diff --git a/types/on-wake-up/tsconfig.json b/types/on-wake-up/tsconfig.json new file mode 100644 index 0000000000..691fba15c1 --- /dev/null +++ b/types/on-wake-up/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "on-wake-up-tests.ts" + ] +} diff --git a/types/on-wake-up/tslint.json b/types/on-wake-up/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/on-wake-up/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/onoff/index.d.ts b/types/onoff/index.d.ts index 55701976a9..f4eba3ffb6 100644 --- a/types/onoff/index.d.ts +++ b/types/onoff/index.d.ts @@ -28,6 +28,8 @@ declare namespace __ONOFF { options?: GpioOptions ); + static accessible: boolean; + gpio: number; gpioPath: string; opts: GpioOptions; diff --git a/types/onoff/onoff-tests.ts b/types/onoff/onoff-tests.ts index 21b47e7f99..776b577348 100644 --- a/types/onoff/onoff-tests.ts +++ b/types/onoff/onoff-tests.ts @@ -14,3 +14,5 @@ setTimeout(function() { led.writeSync(0); led.unexport(); }, 2000); + +var accessible:boolean = onoff.Gpio.accessible; diff --git a/types/opossum/index.d.ts b/types/opossum/index.d.ts index f1e14a939b..b955f940e3 100644 --- a/types/opossum/index.d.ts +++ b/types/opossum/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for opossum 1.8 -// Project: https://github.com/bucharest-gold/opossum +// Type definitions for opossum 1.9 +// Project: https://github.com/nodeshift/opossum // Definitions by: Quinn Langille +// Lance Ball // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -31,6 +32,7 @@ export class CircuitBreaker { static readonly hystrixStats: symbol; static readonly enabled: symbol; static readonly warmUp: symbol; + static readonly volumeThreshold: symbol; } export interface CircuitBreakerOptions { @@ -45,6 +47,7 @@ export interface CircuitBreakerOptions { errorThresholdPercentage?: number; enabled?: boolean; allowWarmUp?: boolean; + volumeThreshold?: number; } export default function circuitBreaker( diff --git a/types/opossum/opossum-tests.ts b/types/opossum/opossum-tests.ts index 3f020eff52..9ec5425416 100644 --- a/types/opossum/opossum-tests.ts +++ b/types/opossum/opossum-tests.ts @@ -17,7 +17,8 @@ const options: CircuitBreakerOptions = { capacity: 1, errorThresholdPercentage: 1, enabled: true, - allowWarmUp: true + allowWarmUp: true, + volumeThreshold: 1 }; const testWithOptions: CircuitBreaker = circuitBreaker(_blank, options); @@ -44,3 +45,4 @@ const shouldBeSymbol7: symbol = CircuitBreaker.hystrixStats; const shouldBeSymbol8: symbol = CircuitBreaker.status; const shouldBeSymbol9: symbol = CircuitBreaker.enabled; const shouldBeSymbol10: symbol = CircuitBreaker.warmUp; +const shouldBeSymbol11: symbol = CircuitBreaker.volumeThreshold; diff --git a/types/p-wait-for/index.d.ts b/types/p-wait-for/index.d.ts index 5e8f88d413..d7fa76e016 100644 --- a/types/p-wait-for/index.d.ts +++ b/types/p-wait-for/index.d.ts @@ -1,8 +1,15 @@ -// Type definitions for p-wait-for 1.0 +// Type definitions for p-wait-for 2.0 // Project: https://github.com/sindresorhus/p-wait-for#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = pWaitFor; -declare function pWaitFor(condition: () => PromiseLike | boolean, interval?: number): Promise; +declare function pWaitFor(condition: () => PromiseLike | boolean, options?: pWaitFor.Options): Promise; + +declare namespace pWaitFor { + interface Options { + interval?: number; + timeout?: number; + } +} diff --git a/types/p-wait-for/p-wait-for-tests.ts b/types/p-wait-for/p-wait-for-tests.ts index 587d08d5a5..ef23ef6526 100644 --- a/types/p-wait-for/p-wait-for-tests.ts +++ b/types/p-wait-for/p-wait-for-tests.ts @@ -1,6 +1,8 @@ import pWaitFor = require('p-wait-for'); pWaitFor(() => Promise.resolve(false)).then(() => {}); -pWaitFor(() => Promise.resolve(true), 1).then(() => {}); +pWaitFor(() => Promise.resolve(true), { interval: 1 }).then(() => {}); +pWaitFor(() => Promise.resolve(true), { timeout: 1 }).then(() => {}); pWaitFor(() => false).then(() => {}); -pWaitFor(() => true, 1).then(() => {}); +pWaitFor(() => true, { interval: 1 }).then(() => {}); +pWaitFor(() => true, { timeout: 1 }).then(() => {}); diff --git a/types/p5/lib/addons/p5.sound.d.ts b/types/p5/lib/addons/p5.sound.d.ts index 6a057b6289..faa16f7e1b 100644 --- a/types/p5/lib/addons/p5.sound.d.ts +++ b/types/p5/lib/addons/p5.sound.d.ts @@ -1990,7 +1990,7 @@ declare module "../../index" { * Reverb adds depth to a sound through a large * number of decaying echoes. It creates the * perception that sound is occurring in a physical - * space. The p5.Reverb has paramters for Time (how + * space. The p5.Reverb has parameters for Time (how * long does the reverb last) and decayRate (how much * the sound decays with each echo) that can be set * with the .set() or .process() methods. The @@ -2511,7 +2511,7 @@ declare module "../../index" { maxIterations: number; /** - * Getters and Setters, setting any paramter will + * Getters and Setters, setting any parameter will * result in a change in the clock's frequency, that * will be reflected after the next callback beats * per minute (defaults to 60) @@ -2588,7 +2588,7 @@ declare module "../../index" { ): void; /** - * Set the paramters of a compressor. + * Set the parameters of a compressor. * @param attack The amount of time (in seconds) to * reduce the gain by 10dB, default = .003, range 0 - * 1 diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index 4e52dd66a4..c7246ecb1f 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -7,6 +7,7 @@ // Alberto Restifo // Behind The Math // 3af +// Janne Liuhtonen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,7 +24,7 @@ export function parse(file: File, config?: ParseConfig): ParseResult; export function parse(stream: NodeJS.ReadableStream, config?: ParseConfig): ParseResult; -export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadableStream; +export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadWriteStream; /** * Unparses javascript data objects and returns a csv string diff --git a/types/papaparse/papaparse-tests.ts b/types/papaparse/papaparse-tests.ts index 5db22091ca..57115dc0d5 100644 --- a/types/papaparse/papaparse-tests.ts +++ b/types/papaparse/papaparse-tests.ts @@ -9,6 +9,7 @@ import { ParseMeta, ParseResult } from "papaparse"; +import { Readable } from "stream"; /** * Parsing @@ -40,8 +41,19 @@ Papa.parse(file, { } }); +const readable = new Readable() +const rows = [ + "1,2,3", + "4,5,6" +] -Papa.parse(Papa.NODE_STREAM_INPUT); +rows.forEach(r => { + readable.push(r); +}); + +const papaStream: NodeJS.ReadWriteStream = Papa.parse(Papa.NODE_STREAM_INPUT); + +readable.pipe(papaStream); /** * Unparsing diff --git a/types/passport-github2/index.d.ts b/types/passport-github2/index.d.ts index 91adbb6567..0b2c1f6a5d 100644 --- a/types/passport-github2/index.d.ts +++ b/types/passport-github2/index.d.ts @@ -21,7 +21,6 @@ export interface StrategyOption extends passport.AuthenticateOptions { scope?: string[]; userAgent?: string; - state?: boolean; authorizationURL?: string; tokenURL?: string; @@ -42,7 +41,7 @@ export interface _StrategyOptionsBase extends OAuth2StrategyOptionsWithoutRequir scope?: string[]; userAgent?: string; - state?: boolean; + state?: string; authorizationURL?: string; tokenURL?: string; diff --git a/types/passport/index.d.ts b/types/passport/index.d.ts index fe0c26c775..1a8afed691 100644 --- a/types/passport/index.d.ts +++ b/types/passport/index.d.ts @@ -45,6 +45,7 @@ declare namespace passport { successMessage?: boolean | string; successRedirect?: string; successReturnToOrRedirect?: string; + state?: string; pauseStream?: boolean; userProperty?: string; passReqToCallback?: boolean; diff --git a/types/paypal-rest-sdk/index.d.ts b/types/paypal-rest-sdk/index.d.ts index 414c3fa0f5..d6457fc981 100644 --- a/types/paypal-rest-sdk/index.d.ts +++ b/types/paypal-rest-sdk/index.d.ts @@ -162,7 +162,7 @@ export interface Transaction { }; notify_url?: string; order_url?: string; - readonly related_resources?: RelatedResources; + readonly related_resources?: RelatedResources[]; } export interface Payee { 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/pdfmake/index.d.ts b/types/pdfmake/index.d.ts index fdc0a9de05..a812611400 100644 --- a/types/pdfmake/index.d.ts +++ b/types/pdfmake/index.d.ts @@ -2,7 +2,9 @@ // Project: http://pdfmake.org // Definitions by: Milen Stefanov // Rajab Shakirov +// Enzo Volkmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 declare module 'pdfmake/build/vfs_fonts' { let pdfMake: { @@ -16,15 +18,61 @@ declare module 'pdfmake/build/pdfmake' { let fonts: { [name: string]: TFontFamilyTypes }; function createPdf(documentDefinitions: TDocumentDefinitions): TCreatedPdf; - type pageSizeType = - '4A0' | '2A0' | 'A0' | 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6' | 'A7' | 'A8' | 'A9' | 'A10' | - 'B0' | 'B1' | 'B2' | 'B3' | 'B4' | 'B5' | 'B6' | 'B7' | 'B8' | 'B9' | 'B10' | - 'C0' | 'C1' | 'C2' | 'C3' | 'C4' | 'C5' | 'C6' | 'C7' | 'C8' | 'C9' | 'C10' | - 'RA0' | 'RA1' | 'RA2' | 'RA3' | 'RA4' | - 'SRA0' | 'SRA1' | 'SRA2' | 'SRA3' | 'SRA4' | - 'EXECUTIVE' | 'FOLIO' | 'LEGAL' | 'LETTER' | 'TABLOID'; + enum PageSize { + A0_x_4 = '4A0', + A0_x_2 = '2A0', + AO = 'A0', + A1 = 'A1', + A2 = 'A2', + A3 = 'A3', + A4 = 'A4', + A5 = 'A5', + A6 = 'A6', + A7 = 'A7', + A8 = 'A8', + A9 = 'A9', + A1O = 'A10', + BO = 'B0', + B1 = 'B1', + B2 = 'B2', + B3 = 'B3', + B4 = 'B4', + B5 = 'B5', + B6 = 'B6', + B7 = 'B7', + B8 = 'B8', + B9 = 'B9', + B1O = 'B10', + CO = 'C0', + C1 = 'C1', + C2 = 'C2', + C3 = 'C3', + C4 = 'C4', + C5 = 'C5', + C6 = 'C6', + C7 = 'C7', + C8 = 'C8', + C9 = 'C9', + C1O = 'C10', + RA1 = 'RA1', + RA2 = 'RA2', + RA3 = 'RA3', + RA4 = 'RA4', + SRA1 = 'SRA1', + SRA2 = 'SRA2', + SRA3 = 'SRA3', + SRA4 = 'SRA4', + EXECUTIVE = 'EXECUTIVE', + FOLIO = 'FOLIO', + LEGAL = 'LEGAL', + LETTER = 'LETTER', + TABLOID = 'TABLOID' + } - type pageOrientationType = "portrait" | "landscape"; + enum PageOrientation { + PORTRAIT = 'PORTRAIT', + LANDSCAPE = 'LANDSCAPE' + } let pdfMake: pdfMakeStatic; @@ -48,18 +96,90 @@ declare module 'pdfmake/build/pdfmake' { type TDocumentHeaderFooterFunction = (currentPage: number, pageCount: number) => any; + type Margins = number | [number, number] | [number, number, number, number]; + + type Alignment = 'left' | 'right' | 'justify' | 'center' | string; + + interface Style { + font?: any; + fontSize?: number; + fontFeatures?: any; + bold?: boolean; + italics?: boolean; + alignment?: Alignment; + color?: string; + columnGap?: any; + fillColor?: string; + decoration?: any; + decorationany?: any; + decorationColor?: string; + background?: any; + lineHeight?: number; + characterSpacing?: number; + noWrap?: boolean; + markerColor?: string; + leadingIndent?: any; + [additionalProperty: string]: any; + } + + type TableRowFunction = (row: number) => number; + + interface TableLayoutFunctions { + hLineWidth?: (i: number, node: any) => number; + vLineWidth?: (i: number, node: any) => number; + hLineColor?: (i: number, node: any) => string; + vLineColor?: (i: number, node: any) => string; + fillColor?: (i: number, node: any) => string; + paddingLeft?: (i: number, node: any) => number; + paddingRight?: (i: number, node: any) => number; + paddingTop?: (i: number, node: any) => number; + paddingBottom?: (i: number, node: any) => number; + } + + interface TableCell { + text: string; + rowSpan?: number; + colSpan?: number; + fillColor?: string; + border?: [boolean, boolean, boolean, boolean]; + } + + interface Table { + widths?: Array<(string | number)>; + heights?: Array<(string | number)> | TableRowFunction; + headerRows?: number; + body: Content[][] | TableCell[][]; + layout?: string | TableLayoutFunctions; + } + + interface Content { + style?: 'string'; + margin?: Margins; + text?: string | string[] | Content[]; + columns?: Content[]; + stack?: Content[]; + image?: string; + width?: string | number; + height?: string | number; + fit?: [number, number]; + pageBreak?: 'before' | 'after'; + alignment?: Alignment; + table?: Table; + ul?: Content[]; + ol?: Content[]; + [additionalProperty: string]: any; + } + interface TDocumentDefinitions { info?: TDocumentInformation; - header?: any; - footer?: any; - content: any; - styles?: any; - pageSize?: pageSizeType; - pageOrientation?: pageOrientationType; - pageMargins?: [number, number, number, number]; - defaultStyle?: { - font?: string; - }; + header?: TDocumentHeaderFooterFunction; + footer?: TDocumentHeaderFooterFunction; + content: string | Content; + styles?: Style; + pageSize?: PageSize; + pageOrientation?: PageOrientation; + pageMargins?: Margins; + defaultStyle?: Style; } type CreatedPdfParams = ( diff --git a/types/pdfmake/pdfmake-tests.ts b/types/pdfmake/pdfmake-tests.ts index 0f23e5c5d5..1913e3fe8a 100644 --- a/types/pdfmake/pdfmake-tests.ts +++ b/types/pdfmake/pdfmake-tests.ts @@ -1,10 +1,1330 @@ import * as pdfMake from 'pdfmake/build/pdfmake'; import * as pdfFonts from 'pdfmake/build/vfs_fonts'; -const docDefinition = { content: 'This is an sample PDF printed with pdfMake' }; +const definitions = [ + { + content: [ + 'First paragraph', + 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines' + ] + }, + { + content: [ + { + text: 'This is a header, using header style', + style: 'header' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'Subheader 1 - using subheader style', + style: 'subheader' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'Subheader 2 - using subheader style', + style: 'subheader' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'It is possible to apply multiple styles, ', + style: ['quote', 'small'] + } + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + subheader: { + fontSize: 15, + bold: true + }, + quote: { + italics: true + }, + small: { + fontSize: 8 + } + } + }, + { + content: [ + { + text: 'This is a header (whole paragraph uses the same header style)\n\n', + style: 'header' + }, + { + text: [ + 'It is however possible to provide an array of texts ', + 'to the paragraph (instead of a single string) and have ', + { text: 'a better ', fontSize: 15, bold: true }, + 'control over it. \nEach inline can be ', + { text: 'styled ', fontSize: 20 }, + { text: 'independently ', italics: true, fontSize: 40 }, + 'then.\n\n' + ] + }, + { text: 'Mixing named styles and style-overrides', style: 'header' }, + { + style: 'bigger', + italics: false, + text: [ + 'We can also mix named-styles and style-overrides at both paragraph and inline level. ', + 'For example, this paragraph uses the "bigger" style, which changes fontSize to 15 and sets italics to true. ', + 'Texts are not italics though. It\'s because we\'ve overriden italics back to false at ', + 'the paragraph level. \n\n', + 'We can also change the style of a single inline. Let\'s use a named style called header: ', + { text: 'like here.\n', style: 'header' }, + 'It got bigger and bold.\n\n', + 'OK, now we\'re going to mix named styles and style-overrides at the inline level. ', + 'We\'ll use header style (it makes texts bigger and bold), but we\'ll override ', + 'bold back to false: ', + { text: 'wow! it works!', style: 'header', bold: false }, + '\n\nMake sure to take a look into the sources to understand what\'s going on here.' + ] + } + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + bigger: { + fontSize: 15, + italics: true + } + } + }, + { + content: [ + { + text: 'This paragraph uses header style and extends the alignment property', + style: 'header', + alignment: 'center' + }, + { + text: [ + 'This paragraph uses header style and overrides bold value setting it back to false.\n', + 'Header style in this example sets alignment to justify, so this paragraph should be rendered \n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Malit profecta versatur nomine ocurreret ' + ], + style: 'header', + bold: false + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + alignment: 'justify' + } + } + }, + { + content: [ + 'By default paragraphs are stacked one on top of (or actually - below) another. ', + 'It\'s possible however to split any paragraph (or even the whole document) into columns.\n\n', + 'Here we go with 2 star-sized columns, with justified text and gap set to 20:\n\n', + { + alignment: 'justify', + columns: [ + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nStar-sized columns have always equal widths, so if we define 3 of those, ', + 'it\'ll look like this (make sure to scroll to the next page, as we have a couple of more examples):\n\n', + { + columns: [ + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nYou can also specify accurate widths for some (or all columns)', + { + columns: [ + { + width: 90, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: '*', + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: '*', + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: 90, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nWe also support auto columns. They set their widths based on the content:\n\n', + { + columns: [ + { + width: 'auto', + text: 'auto column' + }, + { + width: '*', + text: 'This is a star-sized column. It should get the remaining' + + ' space divided by the number of all star-sized columns.' + }, + { + width: 50, + text: 'this one has specific width set to 50' + }, + { + width: 'auto', + text: 'another auto column' + }, + { + width: '*', + text: 'This is a star-sized column. It should get the remaining space ' + + 'divided by the number of all star-sized columns.' + }, + ] + }, + '\nIf all auto columns fit within available width, the table does not occupy whole space:\n\n', + { + columns: [ + { + width: 'auto', + text: 'val1' + }, + { + width: 'auto', + text: 'val2' + }, + { + width: 'auto', + text: 'value3' + }, + { + width: 'auto', + text: 'value 4' + }, + ] + }, + '\nAnother cool feature of pdfmake is the ability to have nested elements.', + { + columns: [ + { + width: 100, + fontSize: 9, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ' + }, + [ + 'As you can see in the document definition - this column is not defined with ', + 'an object, but an array, which means it\'s treated as an array of paragraphs rendered one below another.', + 'Just like on the top-level of the document. Let\'s try to divide the remaing space into 3 star-sized columns:\n\n', + { + columns: [ + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + ] + } + ] + ] + }, + '\n\nOh, don\'t forget, we can use everything from styling examples (named styles, custom overrides) here as well.\n\n', + 'For instance - our next paragraph will use the \'bigger\' style (with fontSize set to 15 and italics - true).', + ' We\'ll split it into three columns and make sure they inherit the style:\n\n', + { + style: 'bigger', + columns: [ + 'First column (BTW - it\'s defined as a single string value. pdfmake will turn it into appropriate structure ', + 'automatically and make sure it inherits the styles', + { + fontSize: 20, + text: 'In this column, we\'ve overriden fontSize to 20. It means the content should have italics=true' + + ' (inherited from the style) and be a little bit bigger' + }, + { + style: 'header', + text: 'Last column does not override any styling properties, but applies a new style (header) to itself.' + + ' Eventually - texts here have italics=true (from bigger) and derive fontSize from the style.' + + ' OK, but which one? Both styles define it. As we already know from our styling examples, multiple' + + ' styles can be applied to the element and their order is important. Because \'header\' style has been' + + ' set after \'bigger\' its fontSize takes precedence over the fontSize from \'bigger\'. This is how it works. ' + + 'You will find more examples in the unit tests.' + } + ] + }, + '\n\nWow, you\'ve read the whole document! Congratulations :D' + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + bigger: { + fontSize: 15, + italics: true + } + }, + defaultStyle: { + columnGap: 20 + } + }, + { + content: [ + { text: 'Tables', style: 'header' }, + 'Official documentation is in progress, this document is just', + ' a glimpse of what is possible with pdfmake and its layout engine.', + { text: 'A simple table (no headers, no width specified, no spans, no styling)', + style: 'subheader' }, + 'The following table has nothing more than a body array', + { + style: 'tableExample', + table: { + body: [ + ['Column 1', 'Column 2', 'Column 3'], + ['One value goes here', 'Another one here', 'OK?'] + ] + } + }, + { text: 'A simple table with nested elements', style: 'subheader' }, + 'It is of course possible to nest any other type of nodes available in ', + 'pdfmake inside table cells', + { + style: 'tableExample', + table: { + body: [ + ['Column 1', 'Column 2', 'Column 3'], + [ + { + stack: [ + 'Let\'s try an unordered list', + { + ul: [ + 'item 1', + 'item 2' + ] + } + ] + }, + [ + 'or a nested table', + { + table: { + body: [ + ['Col1', 'Col2', 'Col3'], + ['1', '2', '3'], + ['1', '2', '3'] + ] + }, + } + ], + { + text: [ + 'Inlines can be ', + { text: 'styled\n', italics: true }, + { text: 'easily as everywhere else', fontSize: 10 }] + } + ] + ] + } + }, + { text: 'Defining column widths', style: 'subheader' }, + 'Tables support the same width definitions as standard columns:', + { + bold: true, + ul: [ + 'auto', + 'star', + 'fixed value' + ] + }, + { + style: 'tableExample', + table: { + widths: [100, '*', 200, '*'], + body: [ + ['width=100', 'star-sized', 'width=200', 'star-sized'], + ['fixed-width cells have exactly the specified width', + { text: 'nothing interesting here', italics: true, color: 'gray' }, + { text: 'nothing interesting here', italics: true, color: 'gray' }, + { text: 'nothing interesting here', italics: true, color: 'gray' }] + ] + } + }, + { + style: 'tableExample', + table: { + widths: ['*', 'auto'], + body: [ + ['This is a star-sized column. The next column over, an auto-sized column, will wrap to accomodate all the text in this cell.', 'I am auto sized.'], + ] + } + }, + { + style: 'tableExample', + table: { + widths: ['*', 'auto'], + body: [ + ['This is a star-sized column. The next column over, an auto-sized column', + { text: 'I am auto sized.', noWrap: true }], + ] + } + }, + { text: 'Defining row heights', style: 'subheader' }, + { + style: 'tableExample', + table: { + heights: [20, 50, 70], + body: [ + ['row 1 with height 20', 'column B'], + ['row 2 with height 50', 'column B'], + ['row 3 with height 70', 'column B'] + ] + } + }, + 'With same height:', + { + style: 'tableExample', + table: { + heights: 40, + body: [ + ['row 1', 'column B'], + ['row 2', 'column B'], + ['row 3', 'column B'] + ] + } + }, + 'With height from function:', + { + style: 'tableExample', + table: { + heights: (row: number) => { + return (row + 1) * 25; + }, + body: [ + ['row 1', 'column B'], + ['row 2', 'column B'], + ['row 3', 'column B'] + ] + } + }, + { text: 'Column/row spans', pageBreak: 'before', style: 'subheader' }, + 'Each cell-element can set a rowSpan or colSpan', + { + style: 'tableExample', + color: '#444', + table: { + widths: [200, 'auto', 'auto'], + headerRows: 2, + // keepWithHeaderRows: 1, + body: [ + [{ text: 'Header with Colspan = 2', style: 'tableHeader', colSpan: 2, alignment: 'center' }, + {}, { text: 'Header 3', style: 'tableHeader', alignment: 'center' }], + [{ text: 'Header 1', style: 'tableHeader', alignment: 'center' }, + { text: 'Header 2', style: 'tableHeader', alignment: 'center' }, + { text: 'Header 3', style: 'tableHeader', alignment: 'center' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + [{ rowSpan: 3, text: 'rowSpan set to 3\nLorem ipsum dolor sit amet' }, + 'Sample value 2', 'Sample value 3'], + ['', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', { colSpan: 2, rowSpan: 2, text: 'Both:\nrowSpan and colSpan\ncan be defined at the same time' }, ''], + ['Sample value 1', '', ''], + ] + } + }, + { text: 'Headers', pageBreak: 'before', style: 'subheader' }, + 'You can declare how many rows should be treated as a header. Headers are', + ' automatically repeated on the following pages', + { text: ['It is also possible to set keepWithHeaderRows to make sure there will be no page-break' + + 'between the header and these rows. Take a look at the document-definition and play with it. ' + + 'If you set it to one, the following table will automatically start on the next page, ' + + 'since there\'s not enough space for the first row to be rendered here'], color: 'gray', italics: true }, + { + style: 'tableExample', + table: { + headerRows: 1, + // dontBreakRows: true, + // keepWithHeaderRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + [ + 'Lorem ipsum dolor sit amet, ', + 'Lorem ipsum dolor sit amet, ', + 'Lorem ipsum dolor sit amet, ', + ] + ] + } + }, + { text: 'Styling tables', style: 'subheader' }, + 'You can provide a custom styler for the table. Currently it supports:', + { + ul: [ + 'line widths', + 'line colors', + 'cell paddings', + ] + }, + 'with more options coming soon...\n\npdfmake currently has a few predefined styles (see them on the next page)', + { text: 'noBorders:', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'noBorders' + }, + { text: 'headerLineOnly:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'headerLineOnly' + }, + { text: 'lightHorizontalLines:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'lightHorizontalLines' + }, + { text: 'but you can provide a custom styler as well', margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: { + hLineWidth: (i: number, node: any) => { + return (i === 0 || i === node.table.body.length) ? 2 : 1; + }, + vLineWidth: (i: number, node: any) => { + return (i === 0 || i === node.table.widths.length) ? 2 : 1; + }, + hLineColor: (i: number, node: any) => { + return (i === 0 || i === node.table.body.length) ? 'black' : 'gray'; + }, + vLineColor: (i: number, node: any) => { + return (i === 0 || i === node.table.widths.length) ? 'black' : 'gray'; + }, + // paddingLeft: function(i, node) { return 4; }, + // paddingRight: function(i, node) { return 4; }, + // paddingTop: function(i, node) { return 2; }, + // paddingBottom: function(i, node) { return 2; }, + // fillColor: (i: number, node: any) => { return null; } + } + }, + { text: 'zebra style', margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + body: [ + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: { + fillColor: (i: number, node: any) => { + return (i % 2 === 0) ? '#CCCCCC' : null; + } + } + }, + { text: 'Optional border', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] }, + 'Each cell contains an optional border property: an array of 4 booleans for left border, top border, right border, bottom border.', + { + style: 'tableExample', + table: { + body: [ + [ + { + border: [false, true, false, false], + fillColor: '#eeeeee', + text: 'border:\n[false, true, false, false]' + }, + { + border: [false, false, false, false], + fillColor: '#dddddd', + text: 'border:\n[false, false, false, false]' + }, + { + border: [true, true, true, true], + fillColor: '#eeeeee', + text: 'border:\n[true, true, true, true]' + } + ], + [ + { + rowSpan: 3, + border: [true, true, true, true], + fillColor: '#eeeeff', + text: 'rowSpan: 3\n\nborder:\n[true, true, true, true]' + }, + { + border: undefined, + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [true, false, false, false], + fillColor: '#dddddd', + text: 'border:\n[true, false, false, false]' + } + ], + [ + '', + { + colSpan: 2, + border: [true, true, true, true], + fillColor: '#eeffee', + text: 'colSpan: 2\n\nborder:\n[true, true, true, true]' + }, + '' + ], + [ + '', + { + border: undefined, + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [false, false, true, true], + fillColor: '#dddddd', + text: 'border:\n[false, false, true, true]' + } + ] + ] + }, + layout: { + defaultBorder: false, + } + }, + 'For every cell without a border property, whether it has all borders or not is determined by ', + 'layout.defaultBorder, which is false in the table above and true (by default) in the table below.', + { + style: 'tableExample', + table: { + body: [ + [ + { + border: [false, false, false, false], + fillColor: '#eeeeee', + text: 'border:\n[false, false, false, false]' + }, + { + fillColor: '#dddddd', + text: 'border:\nundefined' + }, + { + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + ], + [ + { + fillColor: '#dddddd', + text: 'border:\nundefined' + }, + { + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [true, true, false, false], + fillColor: '#dddddd', + text: 'border:\n[true, true, false, false]' + }, + ] + ] + } + }, + 'And some other examples with rowSpan/colSpan...', + { + style: 'tableExample', + table: { + body: [ + [ + '', + 'column 1', + 'column 2', + 'column 3' + ], + [ + 'row 1', + { + rowSpan: 3, + colSpan: 3, + border: [true, true, true, true], + fillColor: '#cccccc', + text: 'rowSpan: 3\ncolSpan: 3\n\nborder:\n[true, true, true, true]' + }, + '', + '' + ], + [ + 'row 2', + '', + '', + '' + ], + [ + 'row 3', + '', + '', + '' + ] + ] + }, + layout: { + defaultBorder: false, + } + }, + { + style: 'tableExample', + table: { + body: [ + [ + { + colSpan: 3, + text: 'colSpan: 3\n\nborder:\n[false, false, false, false]', + fillColor: '#eeeeee', + border: [false, false, false, false] + }, + '', + '' + ], + [ + 'border:\nundefined', + 'border:\nundefined', + 'border:\nundefined' + ] + ] + } + }, + { + style: 'tableExample', + table: { + body: [ + [ + { rowSpan: 3, text: 'rowSpan: 3\n\nborder:\n[false, false, false, false]', fillColor: '#eeeeee', border: [false, false, false, false] }, + 'border:\nundefined', + 'border:\nundefined' + ], + [ + '', + 'border:\nundefined', + 'border:\nundefined' + ], + [ + '', + 'border:\nundefined', + 'border:\nundefined' + ] + ] + } + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + margin: [0, 0, 0, 10] + }, + subheader: { + fontSize: 16, + bold: true, + margin: [0, 10, 0, 5] + }, + tableExample: { + margin: [0, 5, 0, 15] + }, + tableHeader: { + bold: true, + fontSize: 13, + color: 'black' + } + }, + defaultStyle: { + // alignment: 'justify' + } + }, + { + content: [ + { text: 'Unordered list', style: 'header' }, + { + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list with longer lines', style: 'header' }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + 'item 3' + ] + }, + { text: '\n\nOrdered list', style: 'header' }, + { + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with longer lines', style: 'header' }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + 'item 3' + ] + }, + { text: '\n\nOrdered list should be descending', style: 'header' }, + { + reversed: true, + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with start value', style: 'header' }, + { + start: 50, + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own values', style: 'header' }, + { + ol: [ + { text: 'item 1', counter: 10 }, + { text: 'item 2', counter: 20 }, + { text: 'item 3', counter: 30 }, + { text: 'item 4 without own value' } + ] + }, + { text: '\n\nNested lists (ordered)', style: 'header' }, + { + ol: [ + 'item 1', + [ + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + { + ol: [ + 'subitem 1', + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + } + ], + 'item 3\nsecond line of item3' + ] + }, + { text: '\n\nNested lists (unordered)', style: 'header' }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + { + ul: [ + 'subitem 1', + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + }, + 'item 3\nsecond line of item3', + ] + }, + { text: '\n\nUnordered lists inside columns', style: 'header' }, + { + columns: [ + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + } + ] + }, + { text: '\n\nOrdered lists inside columns', style: 'header' }, + { + columns: [ + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + } + ] + }, + { text: '\n\nNested lists width columns', style: 'header' }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + { + ol: [ + [ + { + columns: [ + 'column 1', + { + stack: [ + 'column 2', + { + ul: [ + 'item 1', + 'item 2', + { + ul: [ + 'item', + 'item', + 'item', + ] + }, + 'item 4', + ] + } + ] + }, + 'column 3', + 'column 4', + ] + }, + 'subitem 1 in a vertical container', + 'subitem 2 in a vertical container', + ], + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + }, + 'item 3\nsecond line of item3', + ] + }, + { text: '\n\nUnordered list with square marker type', style: 'header' }, + { + type: 'square', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list with circle marker type', style: 'header' }, + { + type: 'circle', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored unordered list', style: 'header' }, + { + color: 'blue', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored unordered list with own marker color', style: 'header' }, + { + color: 'blue', + markerColor: 'red', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored ordered list', style: 'header' }, + { + color: 'blue', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored ordered list with own marker color', style: 'header' }, + { + color: 'blue', + markerColor: 'red', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list - type: lower-alpha', style: 'header' }, + { + type: 'lower-alpha', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list - type: upper-alpha', style: 'header' }, + { + type: 'upper-alpha', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + + { text: '\n\nOrdered list - type: upper-roman', style: 'header' }, + { + type: 'upper-roman', + ol: [ + 'item 1', + 'item 2', + 'item 3', + 'item 4', + 'item 5' + ] + }, + { text: '\n\nOrdered list - type: lower-roman', style: 'header' }, + { + type: 'lower-roman', + ol: [ + 'item 1', + 'item 2', + 'item 3', + 'item 4', + 'item 5' + ] + }, + { text: '\n\nOrdered list - type: none', style: 'header' }, + { + type: 'none', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list - type: none', style: 'header' }, + { + type: 'none', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own separator', style: 'header' }, + { + separator: ')', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own complex separator', style: 'header' }, + { + separator: ['(', ')'], + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own items type', style: 'header' }, + { + ol: [ + 'item 1', + { text: 'item 2', listType: 'none' }, + { text: 'item 3', listType: 'upper-roman' } + ] + }, + { text: '\n\nUnordered list with own items type', style: 'header' }, + { + ul: [ + 'item 1', + { text: 'item 2', listType: 'none' }, + { text: 'item 3', listType: 'circle' } + ] + }, + ], + styles: { + header: { + bold: true, + fontSize: 15 + } + }, + defaultStyle: { + fontSize: 12 + } + }, + { + content: [ + { + stack: [ + 'This header has both top and bottom margins defined', + { text: 'This is a subheader', style: 'subheader' }, + ], + style: 'header' + }, + { + text: [ + 'Margins have slightly different behavior than other layout properties. ', + 'They are not inherited, unlike anything else. They\'re applied only to those nodes which explicitly ', + 'set margin or style property.\n', + ] + }, + { + text: 'This paragraph (consisting of a single line) directly sets top and bottom margin to 20', + margin: [0, 20], + }, + { + stack: [ + { + text: [ + 'This line begins a stack of paragraphs. The whole stack uses a ', + { text: 'superMargin', italics: true }, + ' style (with margin and fontSize properties).', + ] + }, + { text: ['When you look at the', { text: ' document definition', italics: true }, + ', you will notice that fontSize is inherited by all paragraphs inside the stack.'] }, + 'Margin however is only applied once (to the whole stack).' + ], + style: 'superMargin' + }, + { + stack: [ + 'I\'m not sure yet if this is the desired behavior. I find it a better approach however.', + ' One thing to be considered in the future is an explicit layout property called inheritMargin which could opt-in the inheritance.\n\n', + { + fontSize: 15, + text: [ + 'Currently margins for ', + /* the following margin definition doesn't change anything */ + { text: 'inlines', margin: 20 }, + ' are ignored\n\n' + ], + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + ], + margin: [0, 20, 0, 0], + alignment: 'justify' + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + alignment: 'right', + margin: [0, 190, 0, 80] + }, + subheader: { + fontSize: 14 + }, + superMargin: { + margin: [20, 0, 40, 0], + fontSize: 15 + } + } + }, + { + content: [ + 'pdfmake (since it\'s based on pdfkit) supports JPEG and PNG format', + 'If no width/height/fit is provided, image original size will be used', + { + image: 'sampleImage.jpg', + }, + 'If you specify width, image will scale proportionally', + { + image: 'sampleImage.jpg', + width: 150 + }, + 'If you specify both width and height - image will be stretched', + { + image: 'sampleImage.jpg', + width: 150, + height: 150, + }, + 'You can also fit the image inside a rectangle', + { + image: 'sampleImage.jpg', + fit: [100, 100], + pageBreak: 'after' + }, + // Warning! Make sure to copy this definition and paste it to an + // external text editor, as the online AceEditor has some troubles + // with long dataUrl lines and the following image values look like + // they're empty. + 'Images can be also provided in dataURL format...', + { + image: 'data:image/gif;base64,...', + width: 200 + }, + 'or be declared in an "images" dictionary and referenced by name', + { + image: 'building', + width: 200 + }, + ], + images: { + building: 'data:image/gif;base64,...' + } + } +]; const createPdf = () => { const pdf = pdfMake; pdf.vfs = pdfFonts.pdfMake.vfs; - pdfMake.createPdf(docDefinition).download(); + + for (const definition of definitions) { + const typedDefinition: pdfMake.TDocumentDefinitions = definition; + pdfMake.createPdf(typedDefinition).download(); + } }; diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 75f045af01..fed6c45253 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -1,17 +1,19 @@ -// Type definitions for pino 5.6 +// Type definitions for pino 5.8 // Project: https://github.com/pinojs/pino.git // Definitions by: Peter Snider // BendingBender // Christian Rackerseder // GP +// Alex Ferrando // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import * as stream from 'stream'; -import * as http from 'http'; -import { EventEmitter } from 'events'; +import stream = require('stream'); +import http = require('http'); +import EventEmitter = require('events'); +import SonicBoom = require('sonic-boom'); export = P; @@ -20,7 +22,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream | SonicBoom): P.Logger; /** * @param [options]: an options object @@ -28,7 +30,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream | SonicBoom): P.Logger; declare namespace P { /** @@ -75,11 +77,6 @@ declare namespace P { * The default time function for Pino. Returns a string like `,"time":1493426328206`. */ epochTime: TimeFn; - /** - * Returns an ISO formatted string like `,"time":"2017-04-29T004749.354Z"`. It is highly recommended that you avoid this function. - * It incurs a significant performance penalty. - */ - slowTime: TimeFn; /** * Returns an empty string. This function is used when the `timestamp` option is set to `false`. */ @@ -87,12 +84,36 @@ declare namespace P { }; /** - * Provides access to the CLI log prettifier as an API. - * This can also be enabled via the constructor by setting the `prettyPrint` option to either `true` or a configuration object described in this section. - * @param [options]: an options object - * @returns A transform stream to be used as input for the constructor. + * Create a Pino Destination instance: a stream-like object with significantly more throughput (over 30%) than a standard Node.js stream. + * @param [fileDescriptor]: File path or numerical file descriptor, by default 1 + * @returns A Sonic-Boom stream to be used as destination for the pino function */ - function pretty(options?: PrettyOptions): stream.Transform; + function destination(fileDescriptor?: string | number): SonicBoom; + + /** + * Create an extreme mode destination. This yields an additional 60% performance boost. + * There are trade-offs that should be understood before usage. + * @param [fileDescriptor]: File path or numerical file descriptor, by default 1 + * @returns A Sonic-Boom stream to be used as destination for the pino function + */ + function extreme(fileDescriptor?: string | number): SonicBoom; + + /** + * The pino.final method can be used to create an exit listener function. + * This listener function can be supplied to process exit events. + * The exit listener function will cal the handler with + * @param [logger]: pino logger that serves as reference for the final logger + * @param [handler]: Function that will be called by the handler returned from this function + * @returns Exit listener function that can be supplied to process exit events and will call the supplied handler function + */ + function final(logger: Logger, handler: (error: Error, finalLogger: Logger, ...args: any[]) => void): (error: Error | null, ...args: any[]) => void; + + /** + * The pino.final method can be used to acquire a final logger instance that synchronously flushes on every write. + * @param [logger]: pino logger that serves as reference for the final logger + * @returns Final, synchronous logger + */ + function final(logger: Logger): Logger; interface LevelMapping { /** @@ -128,19 +149,6 @@ declare namespace P { * Caution: any sort of formatted time will significantly slow down Pino's performance. */ timestamp?: TimeFn | false; - /** - * @deprecated - * This option is scheduled to be removed in Pino 5.0.0. Use `timestamp: pino.stdTimeFunctions.slowTime` instead. - * Outputs ISO time stamps ('2016-03-09T15:18:53.889Z') instead of Epoch time stamps (1457536759176). - * WARNING: This option carries a 25% performance drop, we recommend using default Epoch timestamps and transforming logs after if required. - * The pino -t command will do this for you (see CLI). Default: `false`. - */ - slowtime?: boolean; - /** - * Enables extreme mode, yields an additional 60% performance (from 250ms down to 100ms per 10000 ops). - * There are trade-off's should be understood before usage. See Extreme mode explained. Default: `false`. - */ - extreme?: boolean; /** * One of the supported levels or `silent` to disable logging. Any other value defines a custom level and * requires supplying a level value via `levelVal`. Default: 'info'. diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index cec8f658fb..c85f2f6873 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -7,9 +7,9 @@ const error = log.error; info('hello world'); error('this is at error level'); info('the answer is %d', 42); -info({obj: 42}, 'hello world'); -info({obj: 42, b: 2}, 'hello world'); -info({obj: {aa: 'bbb'}}, 'another'); +info({ obj: 42 }, 'hello world'); +info({ obj: 42, b: 2 }, 'hello world'); +info({ obj: { aa: 'bbb' } }, 'another'); setImmediate(info, 'after setImmediate'); error(new Error('an error')); @@ -22,15 +22,6 @@ const log2: pino.Logger = pino({ } }); -const pretty = pino.pretty(); -pretty.pipe(process.stdout); -const log3 = pino({ - name: 'app', - safe: true -}, pretty); -log3.child({widget: 'foo'}).info('hello'); -log3.child({widget: 'bar'}).warn('hello 2'); - pino({ browser: { write(o) { @@ -50,27 +41,27 @@ pino({ }); pino({ base: null }); -pino({ base: { foo: 'bar' } , changeLevelName: 'severity' }); +pino({ base: { foo: 'bar' }, changeLevelName: 'severity' }); if ('pino' in log) console.log(`pino version: ${log.pino}`); -log.child({a: 'property'}).info('hello child!'); +log.child({ a: 'property' }).info('hello child!'); log.level = 'error'; log.info('nope'); -const child = log.child({foo: 'bar'}); +const child = log.child({ foo: 'bar' }); child.info('nope again'); child.level = 'info'; child.info('hooray'); log.info('nope nope nope'); -log.child({foo: 'bar', level: 'debug'}).debug('debug!'); +log.child({ foo: 'bar', level: 'debug' }).debug('debug!'); const customSerializers = { test() { return 'this is my serializer'; } }; -pino().child({serializers: customSerializers}).info({test: 'should not show up'}); -const child2 = log.child({father: true}); -const childChild = child2.child({baby: true}); +pino().child({ serializers: customSerializers }).info({ test: 'should not show up' }); +const child2 = log.child({ father: true }); +const childChild = child2.child({ baby: true }); log.level = 'info'; if (log.levelVal === 30) { @@ -100,3 +91,14 @@ logstderr.error('on stderr instead of stdout'); log.useLevelLabels = true; log.info('lol'); log.level === 'info'; + +const extremeDest = pino.extreme(); +const logExtreme = pino(extremeDest); + +const handler = pino.final(logExtreme, (err: Error, finalLogger: pino.BaseLogger) => { + if (err) { + finalLogger.error(err, 'error caused exit'); + } +}); + +handler(new Error('error')); diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 985e1a77c0..7c05701e75 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -377,9 +377,7 @@ declare namespace PIXI { | PIXI.HitArea; buttonMode: boolean; cursor: string; - trackedPointers(): { - [key: number]: interaction.InteractionTrackingData; - }; + trackedPointers: { [key: number]: interaction.InteractionTrackingData; }; // Deprecated defaultCursor: string; // end interactive target @@ -2811,7 +2809,7 @@ declare namespace PIXI { | PIXI.HitArea; buttonMode: boolean; cursor: string; - trackedPointers(): { [key: number]: InteractionTrackingData }; + trackedPointers: { [key: number]: InteractionTrackingData }; // Deprecated defaultCursor: string; diff --git a/types/plist/index.d.ts b/types/plist/index.d.ts index b7064e55a3..f97b267df4 100644 --- a/types/plist/index.d.ts +++ b/types/plist/index.d.ts @@ -20,9 +20,9 @@ export type PlistValue = string | number | boolean | Date | Buffer | PlistObject | PlistArray; export interface PlistObject { - [x: string]: PlistValue; + readonly [x: string]: PlistValue; } -export interface PlistArray extends Array { } +export interface PlistArray extends ReadonlyArray { } // PlistBuildOptions // The instance of this type is passed to 'xmlbuilder' module as it is. diff --git a/types/plist/plist-tests.ts b/types/plist/plist-tests.ts index a94cb4cf71..00dc33b56c 100644 --- a/types/plist/plist-tests.ts +++ b/types/plist/plist-tests.ts @@ -79,3 +79,10 @@ console.log(plistString1); const plistString2 = plist.build(plistValue2, {pretty: false}); console.log(plistString2); + +function f(a: ReadonlyArray) { + plist.build(a); +} + +// $ExpectError +plist.build(() => 0); diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index adf853af72..d0d3fb1be7 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -479,7 +479,7 @@ export type DataTransform = Partial; export type ScatterData = PlotData; // Bar Scatter export interface PlotData { - type: 'bar' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' | 'surface'; + type: 'bar' | 'box' | 'heatmap' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' | 'surface'; x: Datum[] | Datum[][] | TypedArray; y: Datum[] | Datum[][] | TypedArray; z: Datum[] | Datum[][] | Datum[][][] | TypedArray; @@ -530,6 +530,18 @@ export interface PlotData { visible: boolean | 'legendonly'; transforms: DataTransform[]; orientation: 'v' | 'h'; + boxmean: boolean | 'sd'; + colorscale: string | Array<[number, string]>; + zsmooth: 'fast' | 'best' | false; + ygap: number; + xgap: number; + transpose: boolean; + autobinx: boolean; + xbins: { + start: number | string; + end: number | string; + size: number | string; + }; } /** diff --git a/types/postcss-calc/index.d.ts b/types/postcss-calc/index.d.ts new file mode 100644 index 0000000000..c9ac8e30bb --- /dev/null +++ b/types/postcss-calc/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for postcss-calc 7.0 +// Project: https://github.com/postcss/postcss-calc +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace calc { + interface Options { + precision?: number; + preserve?: boolean; + warnWhenCannotResolve?: boolean; + mediaQueries?: boolean; + selectors?: boolean; + } + + type Calc = Plugin; +} + +declare const calc: calc.Calc; +export = calc; diff --git a/types/postcss-calc/package.json b/types/postcss-calc/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-calc/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-calc/postcss-calc-tests.ts b/types/postcss-calc/postcss-calc-tests.ts new file mode 100644 index 0000000000..937741a1f3 --- /dev/null +++ b/types/postcss-calc/postcss-calc-tests.ts @@ -0,0 +1,12 @@ +import calc = require("postcss-calc"); +import { Transformer } from 'postcss'; + +const ap1: Transformer = calc(); + +const ap2: Transformer = calc({ + precision: 5, + preserve: false, + warnWhenCannotResolve: false, + mediaQueries: false, + selectors: false +}); diff --git a/types/postcss-calc/tsconfig.json b/types/postcss-calc/tsconfig.json new file mode 100644 index 0000000000..d21d8b4969 --- /dev/null +++ b/types/postcss-calc/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", + "postcss-calc-tests.ts" + ] +} diff --git a/types/postcss-calc/tslint.json b/types/postcss-calc/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-calc/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-icss-values/index.d.ts b/types/postcss-icss-values/index.d.ts new file mode 100644 index 0000000000..f7133420e8 --- /dev/null +++ b/types/postcss-icss-values/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for postcss-icss-values 2.0 +// Project: https://github.com/css-modules/postcss-icss-values +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare const values: Plugin<{}>; +export = values; diff --git a/types/postcss-icss-values/package.json b/types/postcss-icss-values/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-icss-values/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-icss-values/postcss-icss-values-tests.ts b/types/postcss-icss-values/postcss-icss-values-tests.ts new file mode 100644 index 0000000000..ac63f19aa0 --- /dev/null +++ b/types/postcss-icss-values/postcss-icss-values-tests.ts @@ -0,0 +1,4 @@ +import values = require("postcss-icss-values"); +import { Transformer } from "postcss"; + +const ap1: Transformer = values(); diff --git a/types/postcss-icss-values/tsconfig.json b/types/postcss-icss-values/tsconfig.json new file mode 100644 index 0000000000..354ce66470 --- /dev/null +++ b/types/postcss-icss-values/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", + "postcss-icss-values-tests.ts" + ] +} diff --git a/types/postcss-icss-values/tslint.json b/types/postcss-icss-values/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-icss-values/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-modules-resolve-imports/index.d.ts b/types/postcss-modules-resolve-imports/index.d.ts new file mode 100644 index 0000000000..698ce430ff --- /dev/null +++ b/types/postcss-modules-resolve-imports/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for postcss-modules-resolve-imports 1.3 +// Project: https://github.com/css-modules/postcss-modules-resolve-imports +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace resolveImports { + interface Resolve { + alias?: { [alias: string]: string }; + extensions?: string[]; + modules?: string[]; + mainFile?: string; + preserveSymlinks?: boolean; + } + + interface Options { + icssExports?: boolean; + resolve?: Resolve; + } + + type ResolveImports = Plugin; +} + +declare const resolveImports: resolveImports.ResolveImports; +export = resolveImports; diff --git a/types/postcss-modules-resolve-imports/package.json b/types/postcss-modules-resolve-imports/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-modules-resolve-imports/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts b/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts new file mode 100644 index 0000000000..cb46a28ddc --- /dev/null +++ b/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts @@ -0,0 +1,20 @@ +/// + +import path = require("path"); +import resolveImports = require("postcss-modules-resolve-imports"); +import { Transformer } from "postcss"; + +const ap1: Transformer = resolveImports(); + +const ap2: Transformer = resolveImports({ + icssExports: false, + resolve: { + alias: { + lib: path.resolve(__dirname, "lib"), + }, + extensions: [".css"], + modules: [path.resolve(__dirname, "lib")], + mainFile: "index.css", + preserveSymlinks: false + } +}); diff --git a/types/postcss-modules-resolve-imports/tsconfig.json b/types/postcss-modules-resolve-imports/tsconfig.json new file mode 100644 index 0000000000..a1b942ae1c --- /dev/null +++ b/types/postcss-modules-resolve-imports/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", + "postcss-modules-resolve-imports-tests.ts" + ] +} diff --git a/types/postcss-modules-resolve-imports/tslint.json b/types/postcss-modules-resolve-imports/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-modules-resolve-imports/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pouchdb-core/index.d.ts b/types/pouchdb-core/index.d.ts index 63f03a6832..221b5984b6 100644 --- a/types/pouchdb-core/index.d.ts +++ b/types/pouchdb-core/index.d.ts @@ -1,13 +1,15 @@ -// Type definitions for pouchdb-core 6.4 +// Type definitions for pouchdb-core 7.0 // Project: https://pouchdb.com/ // Definitions by: Simon Paulger , Jakub Navratil , // Brian Geppert , Frederico Galvão , -// Tobias Bales , Sebastián Ramírez +// Tobias Bales , Sebastián Ramírez , +// Katy Moe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// /// +/// interface Blob { readonly size: number; @@ -87,6 +89,11 @@ interface EventEmitter { eventNames(): Array; } +type Fetch = ( + url: string | Request, + opts?: RequestInit +) => Promise; + declare namespace PouchDB { namespace Core { interface Error { @@ -110,7 +117,7 @@ declare namespace PouchDB { type AttachmentData = string | Blob | Buffer; interface Options { - ajax?: Configuration.RemoteRequesterConfiguration; + fetch?: Fetch; } interface BasicResponse { @@ -568,33 +575,8 @@ declare namespace PouchDB { size?: number; } - interface RemoteRequesterConfiguration { - /** - * Time before HTTP requests time out (in ms). - */ - timeout?: number; - /** - * Appends a random string to the end of all HTTP GET requests to avoid - * them being cached on IE. Set this to true to prevent this happening. - */ - cache?: boolean; - /** - * HTTP headers to add to requests. - */ - headers?: { - [name: string]: string; - }; - - /** - * Enables transferring cookies and HTTP Authorization information. - * - * Defaults to true. - */ - withCredentials?: boolean; - } - interface RemoteDatabaseConfiguration extends CommonDatabaseConfiguration { - ajax?: RemoteRequesterConfiguration; + fetch?: Fetch; auth?: { username?: string; @@ -615,6 +597,8 @@ declare namespace PouchDB { version: string; + fetch: Fetch; + on(event: 'created' | 'destroyed', listener: (dbName: string) => any): this; debug: debug.IDebug; diff --git a/types/pouchdb-core/pouchdb-core-tests.ts b/types/pouchdb-core/pouchdb-core-tests.ts index f8accd1c3a..c4c1e0e408 100644 --- a/types/pouchdb-core/pouchdb-core-tests.ts +++ b/types/pouchdb-core/pouchdb-core-tests.ts @@ -233,12 +233,8 @@ function testChanges() { function testRemoteOptions() { const db = new PouchDB('http://example.com/dbname', { - ajax: { - cache: false, - timeout: 10000, - headers: { - 'X-Some-Special-Header': 'foo' - }, + fetch(url, opts) { + return PouchDB.fetch(url, opts); }, auth: { username: 'mysecretusername', 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/prosemirror-markdown/index.d.ts b/types/prosemirror-markdown/index.d.ts index 7af366c04e..91b37ea51e 100644 --- a/types/prosemirror-markdown/index.d.ts +++ b/types/prosemirror-markdown/index.d.ts @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); import { Node as ProsemirrorNode, Schema } from 'prosemirror-model'; /** 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/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 3ff4efbe4b..f1669473a6 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1169,6 +1169,15 @@ export interface FrameBase extends Evalable { */ hover(selector: string): Promise; + /** + * Triggers a `change` and `input` event once all the provided options have been selected. + * If there's no `` has the `multiple` attribute, + * all values are considered, otherwise only the first one is taken into account. + */ + select(selector: string, ...values: string[]): Promise; + /** * Sets the page content. * @param html HTML markup to assign to the page. @@ -1472,15 +1481,6 @@ export interface Page extends EventEmitter, FrameBase { screenshot(options?: BinaryScreenShotOptions): Promise; screenshot(options?: ScreenshotOptions): Promise; - /** - * Triggers a `change` and `input` event once all the provided options have been selected. - * If there's no `` has the `multiple` attribute, - * all values are considered, otherwise only the first one is taken into account. - */ - select(selector: string, ...values: string[]): Promise; - /** * Toggles bypassing page's Content-Security-Policy. * NOTE CSP bypassing happens at the moment of CSP initialization rather then evaluation. diff --git a/types/ramda/es/F.d.ts b/types/ramda/es/F.d.ts new file mode 100644 index 0000000000..bdc0d570d9 --- /dev/null +++ b/types/ramda/es/F.d.ts @@ -0,0 +1,2 @@ +import { F } from '../index'; +export default F; diff --git a/types/ramda/es/T.d.ts b/types/ramda/es/T.d.ts new file mode 100644 index 0000000000..634808e684 --- /dev/null +++ b/types/ramda/es/T.d.ts @@ -0,0 +1,2 @@ +import { T } from '../index'; +export default T; diff --git a/types/ramda/es/add.d.ts b/types/ramda/es/add.d.ts new file mode 100644 index 0000000000..b7b3ee887c --- /dev/null +++ b/types/ramda/es/add.d.ts @@ -0,0 +1,2 @@ +import { add } from '../index'; +export default add; diff --git a/types/ramda/es/addIndex.d.ts b/types/ramda/es/addIndex.d.ts new file mode 100644 index 0000000000..9f27967dcb --- /dev/null +++ b/types/ramda/es/addIndex.d.ts @@ -0,0 +1,2 @@ +import { addIndex } from '../index'; +export default addIndex; diff --git a/types/ramda/es/adjust.d.ts b/types/ramda/es/adjust.d.ts new file mode 100644 index 0000000000..22b65ec38e --- /dev/null +++ b/types/ramda/es/adjust.d.ts @@ -0,0 +1,2 @@ +import { adjust } from '../index'; +export default adjust; diff --git a/types/ramda/es/all.d.ts b/types/ramda/es/all.d.ts new file mode 100644 index 0000000000..a2f6d934f9 --- /dev/null +++ b/types/ramda/es/all.d.ts @@ -0,0 +1,2 @@ +import { all } from '../index'; +export default all; diff --git a/types/ramda/es/allPass.d.ts b/types/ramda/es/allPass.d.ts new file mode 100644 index 0000000000..d44ac20e9d --- /dev/null +++ b/types/ramda/es/allPass.d.ts @@ -0,0 +1,2 @@ +import { allPass } from '../index'; +export default allPass; diff --git a/types/ramda/es/always.d.ts b/types/ramda/es/always.d.ts new file mode 100644 index 0000000000..aadc94983b --- /dev/null +++ b/types/ramda/es/always.d.ts @@ -0,0 +1,2 @@ +import { always } from '../index'; +export default always; diff --git a/types/ramda/es/and.d.ts b/types/ramda/es/and.d.ts new file mode 100644 index 0000000000..3d505f6ec3 --- /dev/null +++ b/types/ramda/es/and.d.ts @@ -0,0 +1,2 @@ +import { and } from '../index'; +export default and; diff --git a/types/ramda/es/any.d.ts b/types/ramda/es/any.d.ts new file mode 100644 index 0000000000..1e77e505e9 --- /dev/null +++ b/types/ramda/es/any.d.ts @@ -0,0 +1,2 @@ +import { any } from '../index'; +export default any; diff --git a/types/ramda/es/anyPass.d.ts b/types/ramda/es/anyPass.d.ts new file mode 100644 index 0000000000..d8e7fc8f0d --- /dev/null +++ b/types/ramda/es/anyPass.d.ts @@ -0,0 +1,2 @@ +import { anyPass } from '../index'; +export default anyPass; diff --git a/types/ramda/es/ap.d.ts b/types/ramda/es/ap.d.ts new file mode 100644 index 0000000000..5bf98d7fbd --- /dev/null +++ b/types/ramda/es/ap.d.ts @@ -0,0 +1,2 @@ +import { ap } from '../index'; +export default ap; diff --git a/types/ramda/es/aperture.d.ts b/types/ramda/es/aperture.d.ts new file mode 100644 index 0000000000..7536b091b8 --- /dev/null +++ b/types/ramda/es/aperture.d.ts @@ -0,0 +1,2 @@ +import { aperture } from '../index'; +export default aperture; diff --git a/types/ramda/es/append.d.ts b/types/ramda/es/append.d.ts new file mode 100644 index 0000000000..88a4e7cde2 --- /dev/null +++ b/types/ramda/es/append.d.ts @@ -0,0 +1,2 @@ +import { append } from '../index'; +export default append; diff --git a/types/ramda/es/apply.d.ts b/types/ramda/es/apply.d.ts new file mode 100644 index 0000000000..53d90689ed --- /dev/null +++ b/types/ramda/es/apply.d.ts @@ -0,0 +1,2 @@ +import { apply } from '../index'; +export default apply; diff --git a/types/ramda/es/applySpec.d.ts b/types/ramda/es/applySpec.d.ts new file mode 100644 index 0000000000..57e5b8018c --- /dev/null +++ b/types/ramda/es/applySpec.d.ts @@ -0,0 +1,2 @@ +import { applySpec } from '../index'; +export default applySpec; diff --git a/types/ramda/es/applyTo.d.ts b/types/ramda/es/applyTo.d.ts new file mode 100644 index 0000000000..30869542db --- /dev/null +++ b/types/ramda/es/applyTo.d.ts @@ -0,0 +1,2 @@ +import { applyTo } from '../index'; +export default applyTo; diff --git a/types/ramda/es/ascend.d.ts b/types/ramda/es/ascend.d.ts new file mode 100644 index 0000000000..e4c4e1199b --- /dev/null +++ b/types/ramda/es/ascend.d.ts @@ -0,0 +1,2 @@ +import { ascend } from '../index'; +export default ascend; diff --git a/types/ramda/es/assoc.d.ts b/types/ramda/es/assoc.d.ts new file mode 100644 index 0000000000..5acc97a0aa --- /dev/null +++ b/types/ramda/es/assoc.d.ts @@ -0,0 +1,2 @@ +import { assoc } from '../index'; +export default assoc; diff --git a/types/ramda/es/assocPath.d.ts b/types/ramda/es/assocPath.d.ts new file mode 100644 index 0000000000..040671bf38 --- /dev/null +++ b/types/ramda/es/assocPath.d.ts @@ -0,0 +1,2 @@ +import { assocPath } from '../index'; +export default assocPath; diff --git a/types/ramda/es/binary.d.ts b/types/ramda/es/binary.d.ts new file mode 100644 index 0000000000..259cb96e82 --- /dev/null +++ b/types/ramda/es/binary.d.ts @@ -0,0 +1,2 @@ +import { binary } from '../index'; +export default binary; diff --git a/types/ramda/es/bind.d.ts b/types/ramda/es/bind.d.ts new file mode 100644 index 0000000000..fe108f09a7 --- /dev/null +++ b/types/ramda/es/bind.d.ts @@ -0,0 +1,2 @@ +import { bind } from '../index'; +export default bind; diff --git a/types/ramda/es/both.d.ts b/types/ramda/es/both.d.ts new file mode 100644 index 0000000000..8061154cdd --- /dev/null +++ b/types/ramda/es/both.d.ts @@ -0,0 +1,2 @@ +import { both } from '../index'; +export default both; diff --git a/types/ramda/es/call.d.ts b/types/ramda/es/call.d.ts new file mode 100644 index 0000000000..35b6fda88c --- /dev/null +++ b/types/ramda/es/call.d.ts @@ -0,0 +1,2 @@ +import { call } from '../index'; +export default call; diff --git a/types/ramda/es/chain.d.ts b/types/ramda/es/chain.d.ts new file mode 100644 index 0000000000..53aafe210a --- /dev/null +++ b/types/ramda/es/chain.d.ts @@ -0,0 +1,2 @@ +import { chain } from '../index'; +export default chain; diff --git a/types/ramda/es/clamp.d.ts b/types/ramda/es/clamp.d.ts new file mode 100644 index 0000000000..1376643cbf --- /dev/null +++ b/types/ramda/es/clamp.d.ts @@ -0,0 +1,2 @@ +import { clamp } from '../index'; +export default clamp; diff --git a/types/ramda/es/clone.d.ts b/types/ramda/es/clone.d.ts new file mode 100644 index 0000000000..b95f842554 --- /dev/null +++ b/types/ramda/es/clone.d.ts @@ -0,0 +1,2 @@ +import { clone } from '../index'; +export default clone; diff --git a/types/ramda/es/comparator.d.ts b/types/ramda/es/comparator.d.ts new file mode 100644 index 0000000000..34023dea00 --- /dev/null +++ b/types/ramda/es/comparator.d.ts @@ -0,0 +1,2 @@ +import { comparator } from '../index'; +export default comparator; diff --git a/types/ramda/es/complement.d.ts b/types/ramda/es/complement.d.ts new file mode 100644 index 0000000000..b5d31fee50 --- /dev/null +++ b/types/ramda/es/complement.d.ts @@ -0,0 +1,2 @@ +import { complement } from '../index'; +export default complement; diff --git a/types/ramda/es/compose.d.ts b/types/ramda/es/compose.d.ts new file mode 100644 index 0000000000..dca4578840 --- /dev/null +++ b/types/ramda/es/compose.d.ts @@ -0,0 +1,2 @@ +import { compose } from '../index'; +export default compose; diff --git a/types/ramda/es/composeK.d.ts b/types/ramda/es/composeK.d.ts new file mode 100644 index 0000000000..646005a0b6 --- /dev/null +++ b/types/ramda/es/composeK.d.ts @@ -0,0 +1,2 @@ +import { composeK } from '../index'; +export default composeK; diff --git a/types/ramda/es/composeP.d.ts b/types/ramda/es/composeP.d.ts new file mode 100644 index 0000000000..ca0a96fb25 --- /dev/null +++ b/types/ramda/es/composeP.d.ts @@ -0,0 +1,2 @@ +import { composeP } from '../index'; +export default composeP; diff --git a/types/ramda/es/concat.d.ts b/types/ramda/es/concat.d.ts new file mode 100644 index 0000000000..9ae333cf95 --- /dev/null +++ b/types/ramda/es/concat.d.ts @@ -0,0 +1,2 @@ +import { concat } from '../index'; +export default concat; diff --git a/types/ramda/es/cond.d.ts b/types/ramda/es/cond.d.ts new file mode 100644 index 0000000000..0ab4930b0e --- /dev/null +++ b/types/ramda/es/cond.d.ts @@ -0,0 +1,2 @@ +import { cond } from '../index'; +export default cond; diff --git a/types/ramda/es/construct.d.ts b/types/ramda/es/construct.d.ts new file mode 100644 index 0000000000..736871cb61 --- /dev/null +++ b/types/ramda/es/construct.d.ts @@ -0,0 +1,2 @@ +import { construct } from '../index'; +export default construct; diff --git a/types/ramda/es/constructN.d.ts b/types/ramda/es/constructN.d.ts new file mode 100644 index 0000000000..d9efc76cf3 --- /dev/null +++ b/types/ramda/es/constructN.d.ts @@ -0,0 +1,2 @@ +import { constructN } from '../index'; +export default constructN; diff --git a/types/ramda/es/contains.d.ts b/types/ramda/es/contains.d.ts new file mode 100644 index 0000000000..d193bc6109 --- /dev/null +++ b/types/ramda/es/contains.d.ts @@ -0,0 +1,2 @@ +import { contains } from '../index'; +export default contains; diff --git a/types/ramda/es/converge.d.ts b/types/ramda/es/converge.d.ts new file mode 100644 index 0000000000..181c0bd7e9 --- /dev/null +++ b/types/ramda/es/converge.d.ts @@ -0,0 +1,2 @@ +import { converge } from '../index'; +export default converge; diff --git a/types/ramda/es/countBy.d.ts b/types/ramda/es/countBy.d.ts new file mode 100644 index 0000000000..03d46e23f0 --- /dev/null +++ b/types/ramda/es/countBy.d.ts @@ -0,0 +1,2 @@ +import { countBy } from '../index'; +export default countBy; diff --git a/types/ramda/es/curry.d.ts b/types/ramda/es/curry.d.ts new file mode 100644 index 0000000000..0d94abf560 --- /dev/null +++ b/types/ramda/es/curry.d.ts @@ -0,0 +1,2 @@ +import { curry } from '../index'; +export default curry; diff --git a/types/ramda/es/curryN.d.ts b/types/ramda/es/curryN.d.ts new file mode 100644 index 0000000000..dca634c3b8 --- /dev/null +++ b/types/ramda/es/curryN.d.ts @@ -0,0 +1,2 @@ +import { curryN } from '../index'; +export default curryN; diff --git a/types/ramda/es/dec.d.ts b/types/ramda/es/dec.d.ts new file mode 100644 index 0000000000..605681f0d8 --- /dev/null +++ b/types/ramda/es/dec.d.ts @@ -0,0 +1,2 @@ +import { dec } from '../index'; +export default dec; diff --git a/types/ramda/es/defaultTo.d.ts b/types/ramda/es/defaultTo.d.ts new file mode 100644 index 0000000000..9c61199544 --- /dev/null +++ b/types/ramda/es/defaultTo.d.ts @@ -0,0 +1,2 @@ +import { defaultTo } from '../index'; +export default defaultTo; diff --git a/types/ramda/es/descend.d.ts b/types/ramda/es/descend.d.ts new file mode 100644 index 0000000000..d0ff2b6d54 --- /dev/null +++ b/types/ramda/es/descend.d.ts @@ -0,0 +1,2 @@ +import { descend } from '../index'; +export default descend; diff --git a/types/ramda/es/difference.d.ts b/types/ramda/es/difference.d.ts new file mode 100644 index 0000000000..1ef0096735 --- /dev/null +++ b/types/ramda/es/difference.d.ts @@ -0,0 +1,2 @@ +import { difference } from '../index'; +export default difference; diff --git a/types/ramda/es/differenceWith.d.ts b/types/ramda/es/differenceWith.d.ts new file mode 100644 index 0000000000..5a2366f6e0 --- /dev/null +++ b/types/ramda/es/differenceWith.d.ts @@ -0,0 +1,2 @@ +import { differenceWith } from '../index'; +export default differenceWith; diff --git a/types/ramda/es/dissoc.d.ts b/types/ramda/es/dissoc.d.ts new file mode 100644 index 0000000000..0ed3e2def9 --- /dev/null +++ b/types/ramda/es/dissoc.d.ts @@ -0,0 +1,2 @@ +import { dissoc } from '../index'; +export default dissoc; diff --git a/types/ramda/es/dissocPath.d.ts b/types/ramda/es/dissocPath.d.ts new file mode 100644 index 0000000000..83c705d80f --- /dev/null +++ b/types/ramda/es/dissocPath.d.ts @@ -0,0 +1,2 @@ +import { dissocPath } from '../index'; +export default dissocPath; diff --git a/types/ramda/es/divide.d.ts b/types/ramda/es/divide.d.ts new file mode 100644 index 0000000000..45c27a4d21 --- /dev/null +++ b/types/ramda/es/divide.d.ts @@ -0,0 +1,2 @@ +import { divide } from '../index'; +export default divide; diff --git a/types/ramda/es/drop.d.ts b/types/ramda/es/drop.d.ts new file mode 100644 index 0000000000..fb89bef7f0 --- /dev/null +++ b/types/ramda/es/drop.d.ts @@ -0,0 +1,2 @@ +import { drop } from '../index'; +export default drop; diff --git a/types/ramda/es/dropLast.d.ts b/types/ramda/es/dropLast.d.ts new file mode 100644 index 0000000000..2402f890f1 --- /dev/null +++ b/types/ramda/es/dropLast.d.ts @@ -0,0 +1,2 @@ +import { dropLast } from '../index'; +export default dropLast; diff --git a/types/ramda/es/dropLastWhile.d.ts b/types/ramda/es/dropLastWhile.d.ts new file mode 100644 index 0000000000..82950dd98b --- /dev/null +++ b/types/ramda/es/dropLastWhile.d.ts @@ -0,0 +1,2 @@ +import { dropLastWhile } from '../index'; +export default dropLastWhile; diff --git a/types/ramda/es/either.d.ts b/types/ramda/es/either.d.ts new file mode 100644 index 0000000000..130f0c4e7f --- /dev/null +++ b/types/ramda/es/either.d.ts @@ -0,0 +1,2 @@ +import { either } from '../index'; +export default either; diff --git a/types/ramda/es/empty.d.ts b/types/ramda/es/empty.d.ts new file mode 100644 index 0000000000..2cb6e8fade --- /dev/null +++ b/types/ramda/es/empty.d.ts @@ -0,0 +1,2 @@ +import { empty } from '../index'; +export default empty; diff --git a/types/ramda/es/endsWith.d.ts b/types/ramda/es/endsWith.d.ts new file mode 100644 index 0000000000..f23a961bbc --- /dev/null +++ b/types/ramda/es/endsWith.d.ts @@ -0,0 +1,2 @@ +import { endsWith } from '../index'; +export default endsWith; diff --git a/types/ramda/es/eqBy.d.ts b/types/ramda/es/eqBy.d.ts new file mode 100644 index 0000000000..3ed508587a --- /dev/null +++ b/types/ramda/es/eqBy.d.ts @@ -0,0 +1,2 @@ +import { eqBy } from '../index'; +export default eqBy; diff --git a/types/ramda/es/eqProps.d.ts b/types/ramda/es/eqProps.d.ts new file mode 100644 index 0000000000..e33b163311 --- /dev/null +++ b/types/ramda/es/eqProps.d.ts @@ -0,0 +1,2 @@ +import { eqProps } from '../index'; +export default eqProps; diff --git a/types/ramda/es/equals.d.ts b/types/ramda/es/equals.d.ts new file mode 100644 index 0000000000..6d4c8050e1 --- /dev/null +++ b/types/ramda/es/equals.d.ts @@ -0,0 +1,2 @@ +import { equals } from '../index'; +export default equals; diff --git a/types/ramda/es/evolve.d.ts b/types/ramda/es/evolve.d.ts new file mode 100644 index 0000000000..21ec9896a3 --- /dev/null +++ b/types/ramda/es/evolve.d.ts @@ -0,0 +1,2 @@ +import { evolve } from '../index'; +export default evolve; diff --git a/types/ramda/es/filter.d.ts b/types/ramda/es/filter.d.ts new file mode 100644 index 0000000000..a4f7133638 --- /dev/null +++ b/types/ramda/es/filter.d.ts @@ -0,0 +1,2 @@ +import { filter } from '../index'; +export default filter; diff --git a/types/ramda/es/find.d.ts b/types/ramda/es/find.d.ts new file mode 100644 index 0000000000..a8c2905bed --- /dev/null +++ b/types/ramda/es/find.d.ts @@ -0,0 +1,2 @@ +import { find } from '../index'; +export default find; diff --git a/types/ramda/es/findIndex.d.ts b/types/ramda/es/findIndex.d.ts new file mode 100644 index 0000000000..88c14e28fc --- /dev/null +++ b/types/ramda/es/findIndex.d.ts @@ -0,0 +1,2 @@ +import { findIndex } from '../index'; +export default findIndex; diff --git a/types/ramda/es/findLast.d.ts b/types/ramda/es/findLast.d.ts new file mode 100644 index 0000000000..3d8ad5c7fa --- /dev/null +++ b/types/ramda/es/findLast.d.ts @@ -0,0 +1,2 @@ +import { findLast } from '../index'; +export default findLast; diff --git a/types/ramda/es/findLastIndex.d.ts b/types/ramda/es/findLastIndex.d.ts new file mode 100644 index 0000000000..ae1edaeb14 --- /dev/null +++ b/types/ramda/es/findLastIndex.d.ts @@ -0,0 +1,2 @@ +import { findLastIndex } from '../index'; +export default findLastIndex; diff --git a/types/ramda/es/flatten.d.ts b/types/ramda/es/flatten.d.ts new file mode 100644 index 0000000000..75a19402dc --- /dev/null +++ b/types/ramda/es/flatten.d.ts @@ -0,0 +1,2 @@ +import { flatten } from '../index'; +export default flatten; diff --git a/types/ramda/es/flip.d.ts b/types/ramda/es/flip.d.ts new file mode 100644 index 0000000000..164e607f33 --- /dev/null +++ b/types/ramda/es/flip.d.ts @@ -0,0 +1,2 @@ +import { flip } from '../index'; +export default flip; diff --git a/types/ramda/es/forEach.d.ts b/types/ramda/es/forEach.d.ts new file mode 100644 index 0000000000..c5f7a57837 --- /dev/null +++ b/types/ramda/es/forEach.d.ts @@ -0,0 +1,2 @@ +import { forEach } from '../index'; +export default forEach; diff --git a/types/ramda/es/forEachObjIndexed.d.ts b/types/ramda/es/forEachObjIndexed.d.ts new file mode 100644 index 0000000000..a098026381 --- /dev/null +++ b/types/ramda/es/forEachObjIndexed.d.ts @@ -0,0 +1,2 @@ +import { forEachObjIndexed } from '../index'; +export default forEachObjIndexed; diff --git a/types/ramda/es/fromPairs.d.ts b/types/ramda/es/fromPairs.d.ts new file mode 100644 index 0000000000..0cb1778350 --- /dev/null +++ b/types/ramda/es/fromPairs.d.ts @@ -0,0 +1,2 @@ +import { fromPairs } from '../index'; +export default fromPairs; diff --git a/types/ramda/es/groupBy.d.ts b/types/ramda/es/groupBy.d.ts new file mode 100644 index 0000000000..af2b32083b --- /dev/null +++ b/types/ramda/es/groupBy.d.ts @@ -0,0 +1,2 @@ +import { groupBy } from '../index'; +export default groupBy; diff --git a/types/ramda/es/groupWith.d.ts b/types/ramda/es/groupWith.d.ts new file mode 100644 index 0000000000..f9dca6c16b --- /dev/null +++ b/types/ramda/es/groupWith.d.ts @@ -0,0 +1,2 @@ +import { groupWith } from '../index'; +export default groupWith; diff --git a/types/ramda/es/gt.d.ts b/types/ramda/es/gt.d.ts new file mode 100644 index 0000000000..4cdb70d336 --- /dev/null +++ b/types/ramda/es/gt.d.ts @@ -0,0 +1,2 @@ +import { gt } from '../index'; +export default gt; diff --git a/types/ramda/es/gte.d.ts b/types/ramda/es/gte.d.ts new file mode 100644 index 0000000000..2b878eabc6 --- /dev/null +++ b/types/ramda/es/gte.d.ts @@ -0,0 +1,2 @@ +import { gte } from '../index'; +export default gte; diff --git a/types/ramda/es/has.d.ts b/types/ramda/es/has.d.ts new file mode 100644 index 0000000000..88c79bfdb0 --- /dev/null +++ b/types/ramda/es/has.d.ts @@ -0,0 +1,2 @@ +import { has } from '../index'; +export default has; diff --git a/types/ramda/es/hasIn.d.ts b/types/ramda/es/hasIn.d.ts new file mode 100644 index 0000000000..4cad709e64 --- /dev/null +++ b/types/ramda/es/hasIn.d.ts @@ -0,0 +1,2 @@ +import { hasIn } from '../index'; +export default hasIn; diff --git a/types/ramda/es/head.d.ts b/types/ramda/es/head.d.ts new file mode 100644 index 0000000000..bb1f3dd7b9 --- /dev/null +++ b/types/ramda/es/head.d.ts @@ -0,0 +1,2 @@ +import { head } from '../index'; +export default head; diff --git a/types/ramda/es/identical.d.ts b/types/ramda/es/identical.d.ts new file mode 100644 index 0000000000..6f2ccf4f94 --- /dev/null +++ b/types/ramda/es/identical.d.ts @@ -0,0 +1,2 @@ +import { identical } from '../index'; +export default identical; diff --git a/types/ramda/es/identity.d.ts b/types/ramda/es/identity.d.ts new file mode 100644 index 0000000000..ba0936116e --- /dev/null +++ b/types/ramda/es/identity.d.ts @@ -0,0 +1,2 @@ +import { identity } from '../index'; +export default identity; diff --git a/types/ramda/es/ifElse.d.ts b/types/ramda/es/ifElse.d.ts new file mode 100644 index 0000000000..46674829d7 --- /dev/null +++ b/types/ramda/es/ifElse.d.ts @@ -0,0 +1,2 @@ +import { ifElse } from '../index'; +export default ifElse; diff --git a/types/ramda/es/inc.d.ts b/types/ramda/es/inc.d.ts new file mode 100644 index 0000000000..c173b2dd8e --- /dev/null +++ b/types/ramda/es/inc.d.ts @@ -0,0 +1,2 @@ +import { inc } from '../index'; +export default inc; diff --git a/types/ramda/es/indexBy.d.ts b/types/ramda/es/indexBy.d.ts new file mode 100644 index 0000000000..93b29ec7cd --- /dev/null +++ b/types/ramda/es/indexBy.d.ts @@ -0,0 +1,2 @@ +import { indexBy } from '../index'; +export default indexBy; diff --git a/types/ramda/es/indexOf.d.ts b/types/ramda/es/indexOf.d.ts new file mode 100644 index 0000000000..22aa4b44db --- /dev/null +++ b/types/ramda/es/indexOf.d.ts @@ -0,0 +1,2 @@ +import { indexOf } from '../index'; +export default indexOf; diff --git a/types/ramda/es/init.d.ts b/types/ramda/es/init.d.ts new file mode 100644 index 0000000000..03849db7b0 --- /dev/null +++ b/types/ramda/es/init.d.ts @@ -0,0 +1,2 @@ +import { init } from '../index'; +export default init; diff --git a/types/ramda/es/insert.d.ts b/types/ramda/es/insert.d.ts new file mode 100644 index 0000000000..3fdde857fa --- /dev/null +++ b/types/ramda/es/insert.d.ts @@ -0,0 +1,2 @@ +import { insert } from '../index'; +export default insert; diff --git a/types/ramda/es/insertAll.d.ts b/types/ramda/es/insertAll.d.ts new file mode 100644 index 0000000000..a9fd784995 --- /dev/null +++ b/types/ramda/es/insertAll.d.ts @@ -0,0 +1,2 @@ +import { insertAll } from '../index'; +export default insertAll; diff --git a/types/ramda/es/intersection.d.ts b/types/ramda/es/intersection.d.ts new file mode 100644 index 0000000000..1ec1aadbe4 --- /dev/null +++ b/types/ramda/es/intersection.d.ts @@ -0,0 +1,2 @@ +import { intersection } from '../index'; +export default intersection; diff --git a/types/ramda/es/intersectionWith.d.ts b/types/ramda/es/intersectionWith.d.ts new file mode 100644 index 0000000000..773c36acbe --- /dev/null +++ b/types/ramda/es/intersectionWith.d.ts @@ -0,0 +1,2 @@ +import { intersectionWith } from '../index'; +export default intersectionWith; diff --git a/types/ramda/es/intersperse.d.ts b/types/ramda/es/intersperse.d.ts new file mode 100644 index 0000000000..b4420de34a --- /dev/null +++ b/types/ramda/es/intersperse.d.ts @@ -0,0 +1,2 @@ +import { intersperse } from '../index'; +export default intersperse; diff --git a/types/ramda/es/into.d.ts b/types/ramda/es/into.d.ts new file mode 100644 index 0000000000..3daa53afdd --- /dev/null +++ b/types/ramda/es/into.d.ts @@ -0,0 +1,2 @@ +import { into } from '../index'; +export default into; diff --git a/types/ramda/es/invert.d.ts b/types/ramda/es/invert.d.ts new file mode 100644 index 0000000000..825773f5dc --- /dev/null +++ b/types/ramda/es/invert.d.ts @@ -0,0 +1,2 @@ +import { invert } from '../index'; +export default invert; diff --git a/types/ramda/es/invertObj.d.ts b/types/ramda/es/invertObj.d.ts new file mode 100644 index 0000000000..8fd0f1fe7d --- /dev/null +++ b/types/ramda/es/invertObj.d.ts @@ -0,0 +1,2 @@ +import { invertObj } from '../index'; +export default invertObj; diff --git a/types/ramda/es/invoker.d.ts b/types/ramda/es/invoker.d.ts new file mode 100644 index 0000000000..1930a78917 --- /dev/null +++ b/types/ramda/es/invoker.d.ts @@ -0,0 +1,2 @@ +import { invoker } from '../index'; +export default invoker; diff --git a/types/ramda/es/is.d.ts b/types/ramda/es/is.d.ts new file mode 100644 index 0000000000..262d14160d --- /dev/null +++ b/types/ramda/es/is.d.ts @@ -0,0 +1,2 @@ +import { is } from '../index'; +export default is; diff --git a/types/ramda/es/isArrayLike.d.ts b/types/ramda/es/isArrayLike.d.ts new file mode 100644 index 0000000000..04aa464805 --- /dev/null +++ b/types/ramda/es/isArrayLike.d.ts @@ -0,0 +1,2 @@ +import { isArrayLike } from '../index'; +export default isArrayLike; diff --git a/types/ramda/es/isEmpty.d.ts b/types/ramda/es/isEmpty.d.ts new file mode 100644 index 0000000000..bea7bb8d08 --- /dev/null +++ b/types/ramda/es/isEmpty.d.ts @@ -0,0 +1,2 @@ +import { isEmpty } from '../index'; +export default isEmpty; diff --git a/types/ramda/es/isNaN.d.ts b/types/ramda/es/isNaN.d.ts new file mode 100644 index 0000000000..5dbe28177a --- /dev/null +++ b/types/ramda/es/isNaN.d.ts @@ -0,0 +1,2 @@ +import { isNaN } from '../index'; +export default isNaN; diff --git a/types/ramda/es/isNil.d.ts b/types/ramda/es/isNil.d.ts new file mode 100644 index 0000000000..bce78e7c70 --- /dev/null +++ b/types/ramda/es/isNil.d.ts @@ -0,0 +1,2 @@ +import { isNil } from '../index'; +export default isNil; diff --git a/types/ramda/es/join.d.ts b/types/ramda/es/join.d.ts new file mode 100644 index 0000000000..7505b7e769 --- /dev/null +++ b/types/ramda/es/join.d.ts @@ -0,0 +1,2 @@ +import { join } from '../index'; +export default join; diff --git a/types/ramda/es/juxt.d.ts b/types/ramda/es/juxt.d.ts new file mode 100644 index 0000000000..23e342f53d --- /dev/null +++ b/types/ramda/es/juxt.d.ts @@ -0,0 +1,2 @@ +import { juxt } from '../index'; +export default juxt; diff --git a/types/ramda/es/keys.d.ts b/types/ramda/es/keys.d.ts new file mode 100644 index 0000000000..b44e894b7a --- /dev/null +++ b/types/ramda/es/keys.d.ts @@ -0,0 +1,2 @@ +import { keys } from '../index'; +export default keys; diff --git a/types/ramda/es/keysIn.d.ts b/types/ramda/es/keysIn.d.ts new file mode 100644 index 0000000000..a54fb92a6d --- /dev/null +++ b/types/ramda/es/keysIn.d.ts @@ -0,0 +1,2 @@ +import { keysIn } from '../index'; +export default keysIn; diff --git a/types/ramda/es/last.d.ts b/types/ramda/es/last.d.ts new file mode 100644 index 0000000000..f8ea740735 --- /dev/null +++ b/types/ramda/es/last.d.ts @@ -0,0 +1,2 @@ +import { last } from '../index'; +export default last; diff --git a/types/ramda/es/lastIndexOf.d.ts b/types/ramda/es/lastIndexOf.d.ts new file mode 100644 index 0000000000..c34fe55a03 --- /dev/null +++ b/types/ramda/es/lastIndexOf.d.ts @@ -0,0 +1,2 @@ +import { lastIndexOf } from '../index'; +export default lastIndexOf; diff --git a/types/ramda/es/length.d.ts b/types/ramda/es/length.d.ts new file mode 100644 index 0000000000..7ef1d90dd5 --- /dev/null +++ b/types/ramda/es/length.d.ts @@ -0,0 +1,2 @@ +import { length } from '../index'; +export default length; diff --git a/types/ramda/es/lens.d.ts b/types/ramda/es/lens.d.ts new file mode 100644 index 0000000000..03688e0c4f --- /dev/null +++ b/types/ramda/es/lens.d.ts @@ -0,0 +1,2 @@ +import { lens } from '../index'; +export default lens; diff --git a/types/ramda/es/lensIndex.d.ts b/types/ramda/es/lensIndex.d.ts new file mode 100644 index 0000000000..d85cd88c2f --- /dev/null +++ b/types/ramda/es/lensIndex.d.ts @@ -0,0 +1,2 @@ +import { lensIndex } from '../index'; +export default lensIndex; diff --git a/types/ramda/es/lensPath.d.ts b/types/ramda/es/lensPath.d.ts new file mode 100644 index 0000000000..67b60fbf3c --- /dev/null +++ b/types/ramda/es/lensPath.d.ts @@ -0,0 +1,2 @@ +import { lensPath } from '../index'; +export default lensPath; diff --git a/types/ramda/es/lensProp.d.ts b/types/ramda/es/lensProp.d.ts new file mode 100644 index 0000000000..fc8db9e32d --- /dev/null +++ b/types/ramda/es/lensProp.d.ts @@ -0,0 +1,2 @@ +import { lensProp } from '../index'; +export default lensProp; diff --git a/types/ramda/es/lift.d.ts b/types/ramda/es/lift.d.ts new file mode 100644 index 0000000000..73e4cba184 --- /dev/null +++ b/types/ramda/es/lift.d.ts @@ -0,0 +1,2 @@ +import { lift } from '../index'; +export default lift; diff --git a/types/ramda/es/lt.d.ts b/types/ramda/es/lt.d.ts new file mode 100644 index 0000000000..71360d1c43 --- /dev/null +++ b/types/ramda/es/lt.d.ts @@ -0,0 +1,2 @@ +import { lt } from '../index'; +export default lt; diff --git a/types/ramda/es/lte.d.ts b/types/ramda/es/lte.d.ts new file mode 100644 index 0000000000..980ef22037 --- /dev/null +++ b/types/ramda/es/lte.d.ts @@ -0,0 +1,2 @@ +import { lte } from '../index'; +export default lte; diff --git a/types/ramda/es/map.d.ts b/types/ramda/es/map.d.ts new file mode 100644 index 0000000000..6883cb62f6 --- /dev/null +++ b/types/ramda/es/map.d.ts @@ -0,0 +1,2 @@ +import { map } from '../index'; +export default map; diff --git a/types/ramda/es/mapAccum.d.ts b/types/ramda/es/mapAccum.d.ts new file mode 100644 index 0000000000..356c715787 --- /dev/null +++ b/types/ramda/es/mapAccum.d.ts @@ -0,0 +1,2 @@ +import { mapAccum } from '../index'; +export default mapAccum; diff --git a/types/ramda/es/mapAccumRight.d.ts b/types/ramda/es/mapAccumRight.d.ts new file mode 100644 index 0000000000..817e73bb97 --- /dev/null +++ b/types/ramda/es/mapAccumRight.d.ts @@ -0,0 +1,2 @@ +import { mapAccumRight } from '../index'; +export default mapAccumRight; diff --git a/types/ramda/es/mapObjIndexed.d.ts b/types/ramda/es/mapObjIndexed.d.ts new file mode 100644 index 0000000000..3ef1eca52d --- /dev/null +++ b/types/ramda/es/mapObjIndexed.d.ts @@ -0,0 +1,2 @@ +import { mapObjIndexed } from '../index'; +export default mapObjIndexed; diff --git a/types/ramda/es/match.d.ts b/types/ramda/es/match.d.ts new file mode 100644 index 0000000000..a24f0bd6d0 --- /dev/null +++ b/types/ramda/es/match.d.ts @@ -0,0 +1,2 @@ +import { match } from '../index'; +export default match; diff --git a/types/ramda/es/mathMod.d.ts b/types/ramda/es/mathMod.d.ts new file mode 100644 index 0000000000..0b0205c822 --- /dev/null +++ b/types/ramda/es/mathMod.d.ts @@ -0,0 +1,2 @@ +import { mathMod } from '../index'; +export default mathMod; diff --git a/types/ramda/es/max.d.ts b/types/ramda/es/max.d.ts new file mode 100644 index 0000000000..fcb09338c0 --- /dev/null +++ b/types/ramda/es/max.d.ts @@ -0,0 +1,2 @@ +import { max } from '../index'; +export default max; diff --git a/types/ramda/es/maxBy.d.ts b/types/ramda/es/maxBy.d.ts new file mode 100644 index 0000000000..4d00e7e572 --- /dev/null +++ b/types/ramda/es/maxBy.d.ts @@ -0,0 +1,2 @@ +import { maxBy } from '../index'; +export default maxBy; diff --git a/types/ramda/es/mean.d.ts b/types/ramda/es/mean.d.ts new file mode 100644 index 0000000000..8babcc3374 --- /dev/null +++ b/types/ramda/es/mean.d.ts @@ -0,0 +1,2 @@ +import { mean } from '../index'; +export default mean; diff --git a/types/ramda/es/median.d.ts b/types/ramda/es/median.d.ts new file mode 100644 index 0000000000..f7386692ff --- /dev/null +++ b/types/ramda/es/median.d.ts @@ -0,0 +1,2 @@ +import { median } from '../index'; +export default median; diff --git a/types/ramda/es/memoize.d.ts b/types/ramda/es/memoize.d.ts new file mode 100644 index 0000000000..a32d4d0016 --- /dev/null +++ b/types/ramda/es/memoize.d.ts @@ -0,0 +1,2 @@ +import { memoize } from '../index'; +export default memoize; diff --git a/types/ramda/es/memoizeWith.d.ts b/types/ramda/es/memoizeWith.d.ts new file mode 100644 index 0000000000..8eb2abd416 --- /dev/null +++ b/types/ramda/es/memoizeWith.d.ts @@ -0,0 +1,2 @@ +import { memoizeWith } from '../index'; +export default memoizeWith; diff --git a/types/ramda/es/merge.d.ts b/types/ramda/es/merge.d.ts new file mode 100644 index 0000000000..9786c2b611 --- /dev/null +++ b/types/ramda/es/merge.d.ts @@ -0,0 +1,2 @@ +import { merge } from '../index'; +export default merge; diff --git a/types/ramda/es/mergeAll.d.ts b/types/ramda/es/mergeAll.d.ts new file mode 100644 index 0000000000..8bb141f82f --- /dev/null +++ b/types/ramda/es/mergeAll.d.ts @@ -0,0 +1,2 @@ +import { mergeAll } from '../index'; +export default mergeAll; diff --git a/types/ramda/es/mergeDeepLeft.d.ts b/types/ramda/es/mergeDeepLeft.d.ts new file mode 100644 index 0000000000..332df578d3 --- /dev/null +++ b/types/ramda/es/mergeDeepLeft.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepLeft } from '../index'; +export default mergeDeepLeft; diff --git a/types/ramda/es/mergeDeepRight.d.ts b/types/ramda/es/mergeDeepRight.d.ts new file mode 100644 index 0000000000..c589924ca5 --- /dev/null +++ b/types/ramda/es/mergeDeepRight.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepRight } from '../index'; +export default mergeDeepRight; diff --git a/types/ramda/es/mergeDeepWith.d.ts b/types/ramda/es/mergeDeepWith.d.ts new file mode 100644 index 0000000000..cd5523b224 --- /dev/null +++ b/types/ramda/es/mergeDeepWith.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepWith } from '../index'; +export default mergeDeepWith; diff --git a/types/ramda/es/mergeDeepWithKey.d.ts b/types/ramda/es/mergeDeepWithKey.d.ts new file mode 100644 index 0000000000..70f6ace1db --- /dev/null +++ b/types/ramda/es/mergeDeepWithKey.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepWithKey } from '../index'; +export default mergeDeepWithKey; diff --git a/types/ramda/es/mergeWith.d.ts b/types/ramda/es/mergeWith.d.ts new file mode 100644 index 0000000000..0270c71977 --- /dev/null +++ b/types/ramda/es/mergeWith.d.ts @@ -0,0 +1,2 @@ +import { mergeWith } from '../index'; +export default mergeWith; diff --git a/types/ramda/es/mergeWithKey.d.ts b/types/ramda/es/mergeWithKey.d.ts new file mode 100644 index 0000000000..b32e625cfc --- /dev/null +++ b/types/ramda/es/mergeWithKey.d.ts @@ -0,0 +1,2 @@ +import { mergeWithKey } from '../index'; +export default mergeWithKey; diff --git a/types/ramda/es/min.d.ts b/types/ramda/es/min.d.ts new file mode 100644 index 0000000000..af0dca8faa --- /dev/null +++ b/types/ramda/es/min.d.ts @@ -0,0 +1,2 @@ +import { min } from '../index'; +export default min; diff --git a/types/ramda/es/minBy.d.ts b/types/ramda/es/minBy.d.ts new file mode 100644 index 0000000000..14377eea93 --- /dev/null +++ b/types/ramda/es/minBy.d.ts @@ -0,0 +1,2 @@ +import { minBy } from '../index'; +export default minBy; diff --git a/types/ramda/es/modulo.d.ts b/types/ramda/es/modulo.d.ts new file mode 100644 index 0000000000..4c32f3ce8f --- /dev/null +++ b/types/ramda/es/modulo.d.ts @@ -0,0 +1,2 @@ +import { modulo } from '../index'; +export default modulo; diff --git a/types/ramda/es/multiply.d.ts b/types/ramda/es/multiply.d.ts new file mode 100644 index 0000000000..56d3a59380 --- /dev/null +++ b/types/ramda/es/multiply.d.ts @@ -0,0 +1,2 @@ +import { multiply } from '../index'; +export default multiply; diff --git a/types/ramda/es/nAry.d.ts b/types/ramda/es/nAry.d.ts new file mode 100644 index 0000000000..a9bce85047 --- /dev/null +++ b/types/ramda/es/nAry.d.ts @@ -0,0 +1,2 @@ +import { nAry } from '../index'; +export default nAry; diff --git a/types/ramda/es/negate.d.ts b/types/ramda/es/negate.d.ts new file mode 100644 index 0000000000..8410d94a22 --- /dev/null +++ b/types/ramda/es/negate.d.ts @@ -0,0 +1,2 @@ +import { negate } from '../index'; +export default negate; diff --git a/types/ramda/es/none.d.ts b/types/ramda/es/none.d.ts new file mode 100644 index 0000000000..6c545e7261 --- /dev/null +++ b/types/ramda/es/none.d.ts @@ -0,0 +1,2 @@ +import { none } from '../index'; +export default none; diff --git a/types/ramda/es/not.d.ts b/types/ramda/es/not.d.ts new file mode 100644 index 0000000000..10c4c56cfc --- /dev/null +++ b/types/ramda/es/not.d.ts @@ -0,0 +1,2 @@ +import { not } from '../index'; +export default not; diff --git a/types/ramda/es/nth.d.ts b/types/ramda/es/nth.d.ts new file mode 100644 index 0000000000..b5cef1993a --- /dev/null +++ b/types/ramda/es/nth.d.ts @@ -0,0 +1,2 @@ +import { nth } from '../index'; +export default nth; diff --git a/types/ramda/es/nthArg.d.ts b/types/ramda/es/nthArg.d.ts new file mode 100644 index 0000000000..5d61bb24f6 --- /dev/null +++ b/types/ramda/es/nthArg.d.ts @@ -0,0 +1,2 @@ +import { nthArg } from '../index'; +export default nthArg; diff --git a/types/ramda/es/objOf.d.ts b/types/ramda/es/objOf.d.ts new file mode 100644 index 0000000000..0a2b7c3075 --- /dev/null +++ b/types/ramda/es/objOf.d.ts @@ -0,0 +1,2 @@ +import { objOf } from '../index'; +export default objOf; diff --git a/types/ramda/es/of.d.ts b/types/ramda/es/of.d.ts new file mode 100644 index 0000000000..252569b5e6 --- /dev/null +++ b/types/ramda/es/of.d.ts @@ -0,0 +1,2 @@ +import { of } from '../index'; +export default of; diff --git a/types/ramda/es/omit.d.ts b/types/ramda/es/omit.d.ts new file mode 100644 index 0000000000..e7e9f796e9 --- /dev/null +++ b/types/ramda/es/omit.d.ts @@ -0,0 +1,2 @@ +import { omit } from '../index'; +export default omit; diff --git a/types/ramda/es/once.d.ts b/types/ramda/es/once.d.ts new file mode 100644 index 0000000000..f49febf008 --- /dev/null +++ b/types/ramda/es/once.d.ts @@ -0,0 +1,2 @@ +import { once } from '../index'; +export default once; diff --git a/types/ramda/es/or.d.ts b/types/ramda/es/or.d.ts new file mode 100644 index 0000000000..933ca7b2d2 --- /dev/null +++ b/types/ramda/es/or.d.ts @@ -0,0 +1,2 @@ +import { or } from '../index'; +export default or; diff --git a/types/ramda/es/over.d.ts b/types/ramda/es/over.d.ts new file mode 100644 index 0000000000..deee3577da --- /dev/null +++ b/types/ramda/es/over.d.ts @@ -0,0 +1,2 @@ +import { over } from '../index'; +export default over; diff --git a/types/ramda/es/pair.d.ts b/types/ramda/es/pair.d.ts new file mode 100644 index 0000000000..2a1cea9de0 --- /dev/null +++ b/types/ramda/es/pair.d.ts @@ -0,0 +1,2 @@ +import { pair } from '../index'; +export default pair; diff --git a/types/ramda/es/partial.d.ts b/types/ramda/es/partial.d.ts new file mode 100644 index 0000000000..acbb16bac3 --- /dev/null +++ b/types/ramda/es/partial.d.ts @@ -0,0 +1,2 @@ +import { partial } from '../index'; +export default partial; diff --git a/types/ramda/es/partialRight.d.ts b/types/ramda/es/partialRight.d.ts new file mode 100644 index 0000000000..5b3bb4b0fa --- /dev/null +++ b/types/ramda/es/partialRight.d.ts @@ -0,0 +1,2 @@ +import { partialRight } from '../index'; +export default partialRight; diff --git a/types/ramda/es/partition.d.ts b/types/ramda/es/partition.d.ts new file mode 100644 index 0000000000..28086418d7 --- /dev/null +++ b/types/ramda/es/partition.d.ts @@ -0,0 +1,2 @@ +import { partition } from '../index'; +export default partition; diff --git a/types/ramda/es/path.d.ts b/types/ramda/es/path.d.ts new file mode 100644 index 0000000000..edf4fa57b0 --- /dev/null +++ b/types/ramda/es/path.d.ts @@ -0,0 +1,2 @@ +import { path } from '../index'; +export default path; diff --git a/types/ramda/es/pathEq.d.ts b/types/ramda/es/pathEq.d.ts new file mode 100644 index 0000000000..27856ca3bc --- /dev/null +++ b/types/ramda/es/pathEq.d.ts @@ -0,0 +1,2 @@ +import { pathEq } from '../index'; +export default pathEq; diff --git a/types/ramda/es/pathOr.d.ts b/types/ramda/es/pathOr.d.ts new file mode 100644 index 0000000000..1af55adc0c --- /dev/null +++ b/types/ramda/es/pathOr.d.ts @@ -0,0 +1,2 @@ +import { pathOr } from '../index'; +export default pathOr; diff --git a/types/ramda/es/pathSatisfies.d.ts b/types/ramda/es/pathSatisfies.d.ts new file mode 100644 index 0000000000..e2493400a2 --- /dev/null +++ b/types/ramda/es/pathSatisfies.d.ts @@ -0,0 +1,2 @@ +import { pathSatisfies } from '../index'; +export default pathSatisfies; diff --git a/types/ramda/es/pick.d.ts b/types/ramda/es/pick.d.ts new file mode 100644 index 0000000000..67b2477a48 --- /dev/null +++ b/types/ramda/es/pick.d.ts @@ -0,0 +1,2 @@ +import { pick } from '../index'; +export default pick; diff --git a/types/ramda/es/pickAll.d.ts b/types/ramda/es/pickAll.d.ts new file mode 100644 index 0000000000..d7e7719077 --- /dev/null +++ b/types/ramda/es/pickAll.d.ts @@ -0,0 +1,2 @@ +import { pickAll } from '../index'; +export default pickAll; diff --git a/types/ramda/es/pickBy.d.ts b/types/ramda/es/pickBy.d.ts new file mode 100644 index 0000000000..4a047dc4ab --- /dev/null +++ b/types/ramda/es/pickBy.d.ts @@ -0,0 +1,2 @@ +import { pickBy } from '../index'; +export default pickBy; diff --git a/types/ramda/es/pipe.d.ts b/types/ramda/es/pipe.d.ts new file mode 100644 index 0000000000..ef1d61098b --- /dev/null +++ b/types/ramda/es/pipe.d.ts @@ -0,0 +1,2 @@ +import { pipe } from '../index'; +export default pipe; diff --git a/types/ramda/es/pipeK.d.ts b/types/ramda/es/pipeK.d.ts new file mode 100644 index 0000000000..bca50e6fff --- /dev/null +++ b/types/ramda/es/pipeK.d.ts @@ -0,0 +1,2 @@ +import { pipeK } from '../index'; +export default pipeK; diff --git a/types/ramda/es/pipeP.d.ts b/types/ramda/es/pipeP.d.ts new file mode 100644 index 0000000000..c69b96d23c --- /dev/null +++ b/types/ramda/es/pipeP.d.ts @@ -0,0 +1,2 @@ +import { pipeP } from '../index'; +export default pipeP; diff --git a/types/ramda/es/pluck.d.ts b/types/ramda/es/pluck.d.ts new file mode 100644 index 0000000000..8bdb4ccbe4 --- /dev/null +++ b/types/ramda/es/pluck.d.ts @@ -0,0 +1,2 @@ +import { pluck } from '../index'; +export default pluck; diff --git a/types/ramda/es/prepend.d.ts b/types/ramda/es/prepend.d.ts new file mode 100644 index 0000000000..9d3fde51b4 --- /dev/null +++ b/types/ramda/es/prepend.d.ts @@ -0,0 +1,2 @@ +import { prepend } from '../index'; +export default prepend; diff --git a/types/ramda/es/product.d.ts b/types/ramda/es/product.d.ts new file mode 100644 index 0000000000..32aed3c0ee --- /dev/null +++ b/types/ramda/es/product.d.ts @@ -0,0 +1,2 @@ +import { product } from '../index'; +export default product; diff --git a/types/ramda/es/project.d.ts b/types/ramda/es/project.d.ts new file mode 100644 index 0000000000..4c1b11c6ed --- /dev/null +++ b/types/ramda/es/project.d.ts @@ -0,0 +1,2 @@ +import { project } from '../index'; +export default project; diff --git a/types/ramda/es/prop.d.ts b/types/ramda/es/prop.d.ts new file mode 100644 index 0000000000..c990b9aca5 --- /dev/null +++ b/types/ramda/es/prop.d.ts @@ -0,0 +1,2 @@ +import { prop } from '../index'; +export default prop; diff --git a/types/ramda/es/propEq.d.ts b/types/ramda/es/propEq.d.ts new file mode 100644 index 0000000000..1e04cb564c --- /dev/null +++ b/types/ramda/es/propEq.d.ts @@ -0,0 +1,2 @@ +import { propEq } from '../index'; +export default propEq; diff --git a/types/ramda/es/propIs.d.ts b/types/ramda/es/propIs.d.ts new file mode 100644 index 0000000000..1be4e6bd04 --- /dev/null +++ b/types/ramda/es/propIs.d.ts @@ -0,0 +1,2 @@ +import { propIs } from '../index'; +export default propIs; diff --git a/types/ramda/es/propOr.d.ts b/types/ramda/es/propOr.d.ts new file mode 100644 index 0000000000..2935d077be --- /dev/null +++ b/types/ramda/es/propOr.d.ts @@ -0,0 +1,2 @@ +import { propOr } from '../index'; +export default propOr; diff --git a/types/ramda/es/propSatisfies.d.ts b/types/ramda/es/propSatisfies.d.ts new file mode 100644 index 0000000000..1b4ff52788 --- /dev/null +++ b/types/ramda/es/propSatisfies.d.ts @@ -0,0 +1,2 @@ +import { propSatisfies } from '../index'; +export default propSatisfies; diff --git a/types/ramda/es/props.d.ts b/types/ramda/es/props.d.ts new file mode 100644 index 0000000000..b856c60b00 --- /dev/null +++ b/types/ramda/es/props.d.ts @@ -0,0 +1,2 @@ +import { props } from '../index'; +export default props; diff --git a/types/ramda/es/range.d.ts b/types/ramda/es/range.d.ts new file mode 100644 index 0000000000..a507ebe4a9 --- /dev/null +++ b/types/ramda/es/range.d.ts @@ -0,0 +1,2 @@ +import { range } from '../index'; +export default range; diff --git a/types/ramda/es/reduce.d.ts b/types/ramda/es/reduce.d.ts new file mode 100644 index 0000000000..eb3b427d00 --- /dev/null +++ b/types/ramda/es/reduce.d.ts @@ -0,0 +1,2 @@ +import { reduce } from '../index'; +export default reduce; diff --git a/types/ramda/es/reduceBy.d.ts b/types/ramda/es/reduceBy.d.ts new file mode 100644 index 0000000000..655c96ef18 --- /dev/null +++ b/types/ramda/es/reduceBy.d.ts @@ -0,0 +1,2 @@ +import { reduceBy } from '../index'; +export default reduceBy; diff --git a/types/ramda/es/reduceRight.d.ts b/types/ramda/es/reduceRight.d.ts new file mode 100644 index 0000000000..3e72f7c309 --- /dev/null +++ b/types/ramda/es/reduceRight.d.ts @@ -0,0 +1,2 @@ +import { reduceRight } from '../index'; +export default reduceRight; diff --git a/types/ramda/es/reduceWhile.d.ts b/types/ramda/es/reduceWhile.d.ts new file mode 100644 index 0000000000..aaa836d38d --- /dev/null +++ b/types/ramda/es/reduceWhile.d.ts @@ -0,0 +1,2 @@ +import { reduceWhile } from '../index'; +export default reduceWhile; diff --git a/types/ramda/es/reduced.d.ts b/types/ramda/es/reduced.d.ts new file mode 100644 index 0000000000..f36739bbe2 --- /dev/null +++ b/types/ramda/es/reduced.d.ts @@ -0,0 +1,2 @@ +import { reduced } from '../index'; +export default reduced; diff --git a/types/ramda/es/reject.d.ts b/types/ramda/es/reject.d.ts new file mode 100644 index 0000000000..600c706f68 --- /dev/null +++ b/types/ramda/es/reject.d.ts @@ -0,0 +1,2 @@ +import { reject } from '../index'; +export default reject; diff --git a/types/ramda/es/remove.d.ts b/types/ramda/es/remove.d.ts new file mode 100644 index 0000000000..023edada47 --- /dev/null +++ b/types/ramda/es/remove.d.ts @@ -0,0 +1,2 @@ +import { remove } from '../index'; +export default remove; diff --git a/types/ramda/es/repeat.d.ts b/types/ramda/es/repeat.d.ts new file mode 100644 index 0000000000..3d8218a1a4 --- /dev/null +++ b/types/ramda/es/repeat.d.ts @@ -0,0 +1,2 @@ +import { repeat } from '../index'; +export default repeat; diff --git a/types/ramda/es/replace.d.ts b/types/ramda/es/replace.d.ts new file mode 100644 index 0000000000..dc735ab2cf --- /dev/null +++ b/types/ramda/es/replace.d.ts @@ -0,0 +1,2 @@ +import { replace } from '../index'; +export default replace; diff --git a/types/ramda/es/reverse.d.ts b/types/ramda/es/reverse.d.ts new file mode 100644 index 0000000000..2d1b2d9390 --- /dev/null +++ b/types/ramda/es/reverse.d.ts @@ -0,0 +1,2 @@ +import { reverse } from '../index'; +export default reverse; diff --git a/types/ramda/es/scan.d.ts b/types/ramda/es/scan.d.ts new file mode 100644 index 0000000000..8971cff9b7 --- /dev/null +++ b/types/ramda/es/scan.d.ts @@ -0,0 +1,2 @@ +import { scan } from '../index'; +export default scan; diff --git a/types/ramda/es/set.d.ts b/types/ramda/es/set.d.ts new file mode 100644 index 0000000000..5023a0b854 --- /dev/null +++ b/types/ramda/es/set.d.ts @@ -0,0 +1,2 @@ +import { set } from '../index'; +export default set; diff --git a/types/ramda/es/slice.d.ts b/types/ramda/es/slice.d.ts new file mode 100644 index 0000000000..6fdc54e59b --- /dev/null +++ b/types/ramda/es/slice.d.ts @@ -0,0 +1,2 @@ +import { slice } from '../index'; +export default slice; diff --git a/types/ramda/es/sort.d.ts b/types/ramda/es/sort.d.ts new file mode 100644 index 0000000000..9f4977e5c5 --- /dev/null +++ b/types/ramda/es/sort.d.ts @@ -0,0 +1,2 @@ +import { sort } from '../index'; +export default sort; diff --git a/types/ramda/es/sortBy.d.ts b/types/ramda/es/sortBy.d.ts new file mode 100644 index 0000000000..ff4eec72f4 --- /dev/null +++ b/types/ramda/es/sortBy.d.ts @@ -0,0 +1,2 @@ +import { sortBy } from '../index'; +export default sortBy; diff --git a/types/ramda/es/sortWith.d.ts b/types/ramda/es/sortWith.d.ts new file mode 100644 index 0000000000..e8e386a2fd --- /dev/null +++ b/types/ramda/es/sortWith.d.ts @@ -0,0 +1,2 @@ +import { sortWith } from '../index'; +export default sortWith; diff --git a/types/ramda/es/split.d.ts b/types/ramda/es/split.d.ts new file mode 100644 index 0000000000..c89a30372b --- /dev/null +++ b/types/ramda/es/split.d.ts @@ -0,0 +1,2 @@ +import { split } from '../index'; +export default split; diff --git a/types/ramda/es/splitAt.d.ts b/types/ramda/es/splitAt.d.ts new file mode 100644 index 0000000000..2f505a21e3 --- /dev/null +++ b/types/ramda/es/splitAt.d.ts @@ -0,0 +1,2 @@ +import { splitAt } from '../index'; +export default splitAt; diff --git a/types/ramda/es/splitEvery.d.ts b/types/ramda/es/splitEvery.d.ts new file mode 100644 index 0000000000..21329e9593 --- /dev/null +++ b/types/ramda/es/splitEvery.d.ts @@ -0,0 +1,2 @@ +import { splitEvery } from '../index'; +export default splitEvery; diff --git a/types/ramda/es/splitWhen.d.ts b/types/ramda/es/splitWhen.d.ts new file mode 100644 index 0000000000..fad94d5bfa --- /dev/null +++ b/types/ramda/es/splitWhen.d.ts @@ -0,0 +1,2 @@ +import { splitWhen } from '../index'; +export default splitWhen; diff --git a/types/ramda/es/startsWith.d.ts b/types/ramda/es/startsWith.d.ts new file mode 100644 index 0000000000..88811ae146 --- /dev/null +++ b/types/ramda/es/startsWith.d.ts @@ -0,0 +1,2 @@ +import { startsWith } from '../index'; +export default startsWith; diff --git a/types/ramda/es/subtract.d.ts b/types/ramda/es/subtract.d.ts new file mode 100644 index 0000000000..2bac6a6c9f --- /dev/null +++ b/types/ramda/es/subtract.d.ts @@ -0,0 +1,2 @@ +import { subtract } from '../index'; +export default subtract; diff --git a/types/ramda/es/sum.d.ts b/types/ramda/es/sum.d.ts new file mode 100644 index 0000000000..5aad66d4e2 --- /dev/null +++ b/types/ramda/es/sum.d.ts @@ -0,0 +1,2 @@ +import { sum } from '../index'; +export default sum; diff --git a/types/ramda/es/symmetricDifference.d.ts b/types/ramda/es/symmetricDifference.d.ts new file mode 100644 index 0000000000..d11802d977 --- /dev/null +++ b/types/ramda/es/symmetricDifference.d.ts @@ -0,0 +1,2 @@ +import { symmetricDifference } from '../index'; +export default symmetricDifference; diff --git a/types/ramda/es/symmetricDifferenceWith.d.ts b/types/ramda/es/symmetricDifferenceWith.d.ts new file mode 100644 index 0000000000..9ee8a2b855 --- /dev/null +++ b/types/ramda/es/symmetricDifferenceWith.d.ts @@ -0,0 +1,2 @@ +import { symmetricDifferenceWith } from '../index'; +export default symmetricDifferenceWith; diff --git a/types/ramda/es/tail.d.ts b/types/ramda/es/tail.d.ts new file mode 100644 index 0000000000..5a949add56 --- /dev/null +++ b/types/ramda/es/tail.d.ts @@ -0,0 +1,2 @@ +import { tail } from '../index'; +export default tail; diff --git a/types/ramda/es/take.d.ts b/types/ramda/es/take.d.ts new file mode 100644 index 0000000000..35806f3171 --- /dev/null +++ b/types/ramda/es/take.d.ts @@ -0,0 +1,2 @@ +import { take } from '../index'; +export default take; diff --git a/types/ramda/es/takeLast.d.ts b/types/ramda/es/takeLast.d.ts new file mode 100644 index 0000000000..145934b186 --- /dev/null +++ b/types/ramda/es/takeLast.d.ts @@ -0,0 +1,2 @@ +import { takeLast } from '../index'; +export default takeLast; diff --git a/types/ramda/es/takeLastWhile.d.ts b/types/ramda/es/takeLastWhile.d.ts new file mode 100644 index 0000000000..0d6f344445 --- /dev/null +++ b/types/ramda/es/takeLastWhile.d.ts @@ -0,0 +1,2 @@ +import { takeLastWhile } from '../index'; +export default takeLastWhile; diff --git a/types/ramda/es/takeWhile.d.ts b/types/ramda/es/takeWhile.d.ts new file mode 100644 index 0000000000..c3f71dd0fd --- /dev/null +++ b/types/ramda/es/takeWhile.d.ts @@ -0,0 +1,2 @@ +import { takeWhile } from '../index'; +export default takeWhile; diff --git a/types/ramda/es/tap.d.ts b/types/ramda/es/tap.d.ts new file mode 100644 index 0000000000..329108173e --- /dev/null +++ b/types/ramda/es/tap.d.ts @@ -0,0 +1,2 @@ +import { tap } from '../index'; +export default tap; diff --git a/types/ramda/es/test.d.ts b/types/ramda/es/test.d.ts new file mode 100644 index 0000000000..64a6289599 --- /dev/null +++ b/types/ramda/es/test.d.ts @@ -0,0 +1,2 @@ +import { test } from '../index'; +export default test; diff --git a/types/ramda/es/times.d.ts b/types/ramda/es/times.d.ts new file mode 100644 index 0000000000..141c101e23 --- /dev/null +++ b/types/ramda/es/times.d.ts @@ -0,0 +1,2 @@ +import { times } from '../index'; +export default times; diff --git a/types/ramda/es/toLower.d.ts b/types/ramda/es/toLower.d.ts new file mode 100644 index 0000000000..4086a90f75 --- /dev/null +++ b/types/ramda/es/toLower.d.ts @@ -0,0 +1,2 @@ +import { toLower } from '../index'; +export default toLower; diff --git a/types/ramda/es/toPairs.d.ts b/types/ramda/es/toPairs.d.ts new file mode 100644 index 0000000000..5a6d3b24c2 --- /dev/null +++ b/types/ramda/es/toPairs.d.ts @@ -0,0 +1,2 @@ +import { toPairs } from '../index'; +export default toPairs; diff --git a/types/ramda/es/toPairsIn.d.ts b/types/ramda/es/toPairsIn.d.ts new file mode 100644 index 0000000000..70a879e200 --- /dev/null +++ b/types/ramda/es/toPairsIn.d.ts @@ -0,0 +1,2 @@ +import { toPairsIn } from '../index'; +export default toPairsIn; diff --git a/types/ramda/es/toString.d.ts b/types/ramda/es/toString.d.ts new file mode 100644 index 0000000000..c731b264be --- /dev/null +++ b/types/ramda/es/toString.d.ts @@ -0,0 +1,2 @@ +import { toString } from '../index'; +export default toString; diff --git a/types/ramda/es/toUpper.d.ts b/types/ramda/es/toUpper.d.ts new file mode 100644 index 0000000000..0a91bccfed --- /dev/null +++ b/types/ramda/es/toUpper.d.ts @@ -0,0 +1,2 @@ +import { toUpper } from '../index'; +export default toUpper; diff --git a/types/ramda/es/transduce.d.ts b/types/ramda/es/transduce.d.ts new file mode 100644 index 0000000000..de33a7380c --- /dev/null +++ b/types/ramda/es/transduce.d.ts @@ -0,0 +1,2 @@ +import { transduce } from '../index'; +export default transduce; diff --git a/types/ramda/es/transpose.d.ts b/types/ramda/es/transpose.d.ts new file mode 100644 index 0000000000..8ed6535fb2 --- /dev/null +++ b/types/ramda/es/transpose.d.ts @@ -0,0 +1,2 @@ +import { transpose } from '../index'; +export default transpose; diff --git a/types/ramda/es/traverse.d.ts b/types/ramda/es/traverse.d.ts new file mode 100644 index 0000000000..cb4fdc0b1e --- /dev/null +++ b/types/ramda/es/traverse.d.ts @@ -0,0 +1,2 @@ +import { traverse } from '../index'; +export default traverse; diff --git a/types/ramda/es/trim.d.ts b/types/ramda/es/trim.d.ts new file mode 100644 index 0000000000..f0000b80bb --- /dev/null +++ b/types/ramda/es/trim.d.ts @@ -0,0 +1,2 @@ +import { trim } from '../index'; +export default trim; diff --git a/types/ramda/es/tryCatch.d.ts b/types/ramda/es/tryCatch.d.ts new file mode 100644 index 0000000000..3c9edd9f79 --- /dev/null +++ b/types/ramda/es/tryCatch.d.ts @@ -0,0 +1,2 @@ +import { tryCatch } from '../index'; +export default tryCatch; diff --git a/types/ramda/es/type.d.ts b/types/ramda/es/type.d.ts new file mode 100644 index 0000000000..de115bb279 --- /dev/null +++ b/types/ramda/es/type.d.ts @@ -0,0 +1,2 @@ +import { type } from '../index'; +export default type; diff --git a/types/ramda/es/unapply.d.ts b/types/ramda/es/unapply.d.ts new file mode 100644 index 0000000000..7ad4b767e0 --- /dev/null +++ b/types/ramda/es/unapply.d.ts @@ -0,0 +1,2 @@ +import { unapply } from '../index'; +export default unapply; diff --git a/types/ramda/es/unary.d.ts b/types/ramda/es/unary.d.ts new file mode 100644 index 0000000000..c022aec354 --- /dev/null +++ b/types/ramda/es/unary.d.ts @@ -0,0 +1,2 @@ +import { unary } from '../index'; +export default unary; diff --git a/types/ramda/es/uncurryN.d.ts b/types/ramda/es/uncurryN.d.ts new file mode 100644 index 0000000000..b6962cc979 --- /dev/null +++ b/types/ramda/es/uncurryN.d.ts @@ -0,0 +1,2 @@ +import { uncurryN } from '../index'; +export default uncurryN; diff --git a/types/ramda/es/unfold.d.ts b/types/ramda/es/unfold.d.ts new file mode 100644 index 0000000000..2ebaff6fe5 --- /dev/null +++ b/types/ramda/es/unfold.d.ts @@ -0,0 +1,2 @@ +import { unfold } from '../index'; +export default unfold; diff --git a/types/ramda/es/union.d.ts b/types/ramda/es/union.d.ts new file mode 100644 index 0000000000..9fac243b43 --- /dev/null +++ b/types/ramda/es/union.d.ts @@ -0,0 +1,2 @@ +import { union } from '../index'; +export default union; diff --git a/types/ramda/es/unionWith.d.ts b/types/ramda/es/unionWith.d.ts new file mode 100644 index 0000000000..8bf20a51b7 --- /dev/null +++ b/types/ramda/es/unionWith.d.ts @@ -0,0 +1,2 @@ +import { unionWith } from '../index'; +export default unionWith; diff --git a/types/ramda/es/uniq.d.ts b/types/ramda/es/uniq.d.ts new file mode 100644 index 0000000000..be0a00aef0 --- /dev/null +++ b/types/ramda/es/uniq.d.ts @@ -0,0 +1,2 @@ +import { uniq } from '../index'; +export default uniq; diff --git a/types/ramda/es/uniqBy.d.ts b/types/ramda/es/uniqBy.d.ts new file mode 100644 index 0000000000..f85de9e4e0 --- /dev/null +++ b/types/ramda/es/uniqBy.d.ts @@ -0,0 +1,2 @@ +import { uniqBy } from '../index'; +export default uniqBy; diff --git a/types/ramda/es/uniqWith.d.ts b/types/ramda/es/uniqWith.d.ts new file mode 100644 index 0000000000..42442bffc3 --- /dev/null +++ b/types/ramda/es/uniqWith.d.ts @@ -0,0 +1,2 @@ +import { uniqWith } from '../index'; +export default uniqWith; diff --git a/types/ramda/es/unless.d.ts b/types/ramda/es/unless.d.ts new file mode 100644 index 0000000000..3727700625 --- /dev/null +++ b/types/ramda/es/unless.d.ts @@ -0,0 +1,2 @@ +import { unless } from '../index'; +export default unless; diff --git a/types/ramda/es/unnest.d.ts b/types/ramda/es/unnest.d.ts new file mode 100644 index 0000000000..ccbb4be0e8 --- /dev/null +++ b/types/ramda/es/unnest.d.ts @@ -0,0 +1,2 @@ +import { unnest } from '../index'; +export default unnest; diff --git a/types/ramda/es/until.d.ts b/types/ramda/es/until.d.ts new file mode 100644 index 0000000000..ab26247fea --- /dev/null +++ b/types/ramda/es/until.d.ts @@ -0,0 +1,2 @@ +import { until } from '../index'; +export default until; diff --git a/types/ramda/es/update.d.ts b/types/ramda/es/update.d.ts new file mode 100644 index 0000000000..c3eba99c72 --- /dev/null +++ b/types/ramda/es/update.d.ts @@ -0,0 +1,2 @@ +import { update } from '../index'; +export default update; diff --git a/types/ramda/es/useWith.d.ts b/types/ramda/es/useWith.d.ts new file mode 100644 index 0000000000..0d1f54e80f --- /dev/null +++ b/types/ramda/es/useWith.d.ts @@ -0,0 +1,2 @@ +import { useWith } from '../index'; +export default useWith; diff --git a/types/ramda/es/values.d.ts b/types/ramda/es/values.d.ts new file mode 100644 index 0000000000..8664d8cc67 --- /dev/null +++ b/types/ramda/es/values.d.ts @@ -0,0 +1,2 @@ +import { values } from '../index'; +export default values; diff --git a/types/ramda/es/valuesIn.d.ts b/types/ramda/es/valuesIn.d.ts new file mode 100644 index 0000000000..d80b32fc67 --- /dev/null +++ b/types/ramda/es/valuesIn.d.ts @@ -0,0 +1,2 @@ +import { valuesIn } from '../index'; +export default valuesIn; diff --git a/types/ramda/es/view.d.ts b/types/ramda/es/view.d.ts new file mode 100644 index 0000000000..3c11fa0ae9 --- /dev/null +++ b/types/ramda/es/view.d.ts @@ -0,0 +1,2 @@ +import { view } from '../index'; +export default view; diff --git a/types/ramda/es/when.d.ts b/types/ramda/es/when.d.ts new file mode 100644 index 0000000000..57de7e19a7 --- /dev/null +++ b/types/ramda/es/when.d.ts @@ -0,0 +1,2 @@ +import { when } from '../index'; +export default when; diff --git a/types/ramda/es/where.d.ts b/types/ramda/es/where.d.ts new file mode 100644 index 0000000000..4c49c2dc25 --- /dev/null +++ b/types/ramda/es/where.d.ts @@ -0,0 +1,2 @@ +import { where } from '../index'; +export default where; diff --git a/types/ramda/es/whereEq.d.ts b/types/ramda/es/whereEq.d.ts new file mode 100644 index 0000000000..4bdffa1d24 --- /dev/null +++ b/types/ramda/es/whereEq.d.ts @@ -0,0 +1,2 @@ +import { whereEq } from '../index'; +export default whereEq; diff --git a/types/ramda/es/without.d.ts b/types/ramda/es/without.d.ts new file mode 100644 index 0000000000..be9b8584ed --- /dev/null +++ b/types/ramda/es/without.d.ts @@ -0,0 +1,2 @@ +import { without } from '../index'; +export default without; diff --git a/types/ramda/es/wrap.d.ts b/types/ramda/es/wrap.d.ts new file mode 100644 index 0000000000..a855106989 --- /dev/null +++ b/types/ramda/es/wrap.d.ts @@ -0,0 +1,2 @@ +import { wrap } from '../index'; +export default wrap; diff --git a/types/ramda/es/xprod.d.ts b/types/ramda/es/xprod.d.ts new file mode 100644 index 0000000000..2e3fd865ea --- /dev/null +++ b/types/ramda/es/xprod.d.ts @@ -0,0 +1,2 @@ +import { xprod } from '../index'; +export default xprod; diff --git a/types/ramda/es/zip.d.ts b/types/ramda/es/zip.d.ts new file mode 100644 index 0000000000..609fe7bb29 --- /dev/null +++ b/types/ramda/es/zip.d.ts @@ -0,0 +1,2 @@ +import { zip } from '../index'; +export default zip; diff --git a/types/ramda/es/zipObj.d.ts b/types/ramda/es/zipObj.d.ts new file mode 100644 index 0000000000..dcc28311bc --- /dev/null +++ b/types/ramda/es/zipObj.d.ts @@ -0,0 +1,2 @@ +import { zipObj } from '../index'; +export default zipObj; diff --git a/types/ramda/es/zipWith.d.ts b/types/ramda/es/zipWith.d.ts new file mode 100644 index 0000000000..df6890c369 --- /dev/null +++ b/types/ramda/es/zipWith.d.ts @@ -0,0 +1,2 @@ +import { zipWith } from '../index'; +export default zipWith; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 9623aa8865..851a778827 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -23,9 +23,253 @@ // Marcin Biernat // Rayhaneh Banyassady // Ryan McCuaig +// Drew Wyatt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + declare let R: R.Static; declare namespace R { @@ -187,12 +431,20 @@ declare namespace R { (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; } + interface Placeholder { __isRamdaPlaceholder__: true; } + interface Reduced { '@@transducer/value': T; '@@transducer/reduced': true; } interface Static { + /** + * Placeholder. When used with functions like curry, or op, the second argument is applied to the second + * position, and it returns a function waiting for its first argument. + */ + __: Placeholder; /* This is used in examples throughout the docs, but I it only seems to be directly explained here: https://ramdajs.com/0.9/docs/#op */ + /** * Adds two numbers (or strings). Equivalent to a + b but curried. */ @@ -511,6 +763,8 @@ declare namespace R { * Returns a new list consisting of the elements of the first list followed by the elements * of the second. */ + concat(placeholder: Placeholder): (list2: ReadonlyArray, list1: ReadonlyArray) => T[]; + concat(placeholder: Placeholder, list2: ReadonlyArray): (list1: ReadonlyArray) => T[]; concat(list1: ReadonlyArray, list2: ReadonlyArray): T[]; concat(list1: ReadonlyArray): (list2: ReadonlyArray) => T[]; concat(list1: string, list2: string): string; @@ -539,6 +793,10 @@ declare namespace R { * Returns `true` if the specified item is somewhere in the list, `false` otherwise. * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. */ + contains(__: Placeholder, list: string): (a: string) => boolean; + contains(__: Placeholder, list: T[]): (a: T) => boolean; + contains(__: Placeholder): (list: string, a: string) => boolean; + contains(__: Placeholder): (list: T[], a: T) => boolean; contains(a: string, list: string): boolean; contains(a: T, list: ReadonlyArray): boolean; contains(a: string): (list: string) => boolean; @@ -633,6 +891,8 @@ declare namespace R { /** * Divides two numbers. Equivalent to a / b. */ + divide(__: Placeholder, b: number): (a: number) => number; + divide(__: Placeholder): (b: number, a: number) => number; divide(a: number, b: number): number; divide(a: number): (b: number) => number; @@ -810,18 +1070,24 @@ declare namespace R { /** * Returns true if the first parameter is greater than the second. */ + gt(__: Placeholder, b: number): (a: number) => boolean; + gt(__: Placeholder): (b: number, a: number) => boolean; gt(a: number, b: number): boolean; gt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is greater than or equal to the second. */ + gte(__: Placeholder, b: number): (a: number) => boolean; + gte(__: Placeholder): (b: number, a: number) => boolean; gte(a: number, b: number): boolean; gte(a: number): (b: number) => boolean; /** * Returns whether or not an object has an own property with the specified name. */ + has(__: Placeholder, obj: T): (s: string) => boolean; + has(__: Placeholder): (obj: T, s: string) => boolean; has(s: string, obj: T): boolean; has(s: string): (obj: T) => boolean; @@ -1057,12 +1323,16 @@ declare namespace R { /** * Returns true if the first parameter is less than the second. */ + lt(__: Placeholder, b: number): (a: number) => boolean; + lt(__: Placeholder): (b: number, a: number) => boolean; lt(a: number, b: number): boolean; lt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is less than or equal to the second. */ + lte(__: Placeholder, b: number): (a: number) => boolean; + lte(__: Placeholder): (b: number, a: number) => boolean; lte(a: number, b: number): boolean; lte(a: number): (b: number) => boolean; @@ -1118,6 +1388,8 @@ declare namespace R { * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN * when the modulus is zero or negative. */ + mathMod(__: Placeholder, b: number): (a: number) => number; + mathMod(__: Placeholder): (b: number, a: number) => number; mathMod(a: number, b: number): number; mathMod(a: number): (b: number) => number; @@ -1166,6 +1438,8 @@ declare namespace R { * merged with the own properties of object b. * This function will *not* mutate passed-in objects. */ + merge(__: Placeholder, b: T2): (a: T1) => T1 & T2; + merge(__: Placeholder): (b: T2, a: T1) => T1 & T2; merge(a: T1, b: T2): T1 & T2; merge(a: T1): (b: T2) => T1 & T2; @@ -1253,6 +1527,8 @@ declare namespace R { * Note that this functions preserves the JavaScript-style behavior for * modulo. For mathematical modulo see `mathMod` */ + modulo(__: Placeholder, b: number): (a: number) => number; + modulo(__: Placeholder): (b: number, a: number) => number; modulo(a: number, b: number): number; modulo(a: number): (b: number) => number; @@ -2039,6 +2315,8 @@ declare namespace R { /** * Subtracts two numbers. Equivalent to `a - b` but curried. */ + subtract(__: Placeholder, b: number): (a: number) => number; + subtract(__: Placeholder): (b: number, a: number) => number; subtract(a: number, b: number): number; subtract(a: number): (b: number) => number; diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 951c11ba02..749ebdaf8b 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -124,6 +124,45 @@ class F2 { } }; +/** R.__ */ +() => { + R.concat(R.__, [4, 5, 6])([1, 2, 3]); // [1, 2, 3, 4, 5, 6] + R.concat(R.__)([4, 5, 6], [1, 2, 3]); // [1, 2, 3, 4, 5, 6] + + R.contains(R.__, [1, 2, 3])(3); // true + R.contains(R.__)([1, 2, 3], 3); // true + + R.divide(R.__)(2, 42); // 21 + R.divide(R.__, 2)(42); // 21 + + R.gt(R.__, 2)(10); // true + R.gt(R.__)(2, 10); // true + + R.gte(R.__, 6)(2); // false + R.gte(R.__)(6, 2); // false + + R.has(R.__, {x: 0, y: 0})('x'); // true; + R.has(R.__)({x: 0, y: 0}, 'x'); // true; + + R.lt(R.__, 5)(10); // false + R.lt(R.__)(5, 10); // false + + R.lte(R.__, 2)(1); // true + R.lte(R.__)(2, 1); // true + + R.mathMod(R.__, 12)(15); // 3 + R.mathMod(R.__)(12, 15); // 3 + + R.modulo(R.__, 2)(42); // 0 + R.modulo(R.__)(2, 42); // 0 + + R.merge(R.__, {x: 0})({x: 5, y: 2}); // {x: 0, y: 2} + R.merge(R.__)({x: 0}, {x: 5, y: 2}); // {x: 0, y: 2} + + R.subtract(R.__, 5)(17); // 12 + R.subtract(R.__)(5, 17); // 12 +}; + () => { const addFour = (a: number) => (b: number) => (c: number) => (d: number) => a + b + c + d; const uncurriedAddFour = R.uncurryN(4, addFour); diff --git a/types/raygun/index.d.ts b/types/raygun/index.d.ts new file mode 100644 index 0000000000..9315161a33 --- /dev/null +++ b/types/raygun/index.d.ts @@ -0,0 +1,146 @@ +// Type definitions for raygun 0.10 +// Project: https://github.com/MindscapeHQ/raygun4node +// Definitions by: Taylor Lodge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare namespace raygun { + interface KeyValueObject { + [key: string]: string | number | boolean | KeyValueObject; + } + interface StackFrame { + lineNumber: number; + className: string; + fileName: string; + methodName: string; + columnNumber?: number; + } + interface RaygunErrorObject { + message: string; + className: string; + stackTrace: StackFrame[]; + innerError?: RaygunErrorObject; + } + interface RaygunRequest { + hostname?: string; + host?: string; + path?: string; + method?: string; + ip?: string; + queryString?: KeyValueObject; + headers?: KeyValueObject; + form?: KeyValueObject; + } + interface RaygunUser { + identifier: string; + email?: string; + fullName?: string; + firstName?: string; + uuid?: string; + } + interface RaygunPayload { + occurredOn: Date; + details: { + client: { + name: "raygun-node"; + version: string; + }; + groupingKey?: string; + error: RaygunErrorObject; + environment: { + osVersion: string; + architecture: string; + totalPhysicalMemory: number; + availablePhysicalMemory: number; + utcOffset: number; + processorCount?: number; + cpu: { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + }; + }; + machineName: string; + userCustomData?: KeyValueObject; + tags: string[]; + request?: RaygunRequest; + user?: RaygunUser | { identifier: string }; + version?: string; + }; + } + + interface RaygunOfflineStorageProvider< + TTransportItem = RaygunPayload, + TStorageItem = string + > { + init(options: any): RaygunOfflineStorageProvider; + save(item: TTransportItem, callback: (error?: Error) => void): void; + retrieve( + callback: ( + error: Error, + storageItems: ReadonlyArray + ) => void + ): void; + send( + callback: ( + error: Error, + sendItems: ReadonlyArray + ) => void + ): void; + } + + type OnBeforeSend = ( + payload: RaygunPayload, + exception: Error, + customData: KeyValueObject, + request: RaygunRequest, + tags: ReadonlyArray + ) => boolean | RaygunPayload; + interface RaygunOptions { + apiKey: string; + filters?: ReadonlyArray; + port?: number; + host?: string; + useSSL?: boolean; + onBeforeSend?: OnBeforeSend; + offlineStorage?: RaygunOfflineStorageProvider; + offlineStorageOptions?: any; + isOffline?: boolean; + groupingKey?: string; + tags?: ReadonlyArray; + userHumanStringForObject?: boolean; + reportColumnNumbers?: boolean; + innerErrorFieldName?: string; + } +} + +declare class Client { + init(options: raygun.RaygunOptions): Client; + setUser(user: raygun.RaygunUser): Client; + setVersion(version: string): Client; + onBeforeSend(callback: raygun.OnBeforeSend): Client; + groupingKey(groupingKey: string): Client; + offline(): Client; + online(): Client; + send( + exception: Error | string | object, + customData?: raygun.KeyValueObject, + offlineStorageCallback?: (error?: Error) => void, + request?: raygun.RaygunRequest, + tags?: ReadonlyArray + ): raygun.RaygunPayload; + expressHandler( + error: Error, + request: raygun.RaygunRequest, + res: any, + next: any + ): void; +} + +export = Client; diff --git a/types/raygun/raygun-tests.ts b/types/raygun/raygun-tests.ts new file mode 100644 index 0000000000..76328b01c5 --- /dev/null +++ b/types/raygun/raygun-tests.ts @@ -0,0 +1,59 @@ +import Client = require('raygun'); + +const client = new Client(); // $ExpectType Client +client.init({apiKey: '1'}); // $ExpectType Client + +client.init(); // $ExpectError +client.init({}); // $ExpectError +client.init({apiKey: 123}); // $ExpectError +// +// $ExpectType Client +client.setUser({ + identifier: '123' +}); +// $ExpectType Client +client.setUser({ + identifier: '123', + email: '123', + fullName: '123', + firstName: '123', + uuid: '123' +}); + +client.setUser(); // $ExpectError +client.setUser({}); // $ExpectError +client.setUser({identifier: 1}); // $ExpectError + +client.setVersion('123'); // $ExpectType Client + +client.setVersion(); // $ExpectError +client.setVersion({}); // $ExpectError + +client.onBeforeSend(payload => payload); // $ExpectType Client +// $ExpectType Client +client.onBeforeSend(payload => { + payload.details; + + return payload; +}); + +client.onBeforeSend(); // $ExpectError + +client.groupingKey('123'); // $ExpectType Client + +client.groupingKey(); // $ExpectError +client.groupingKey({}); // $ExpectError + +client.offline(); // $ExpectType Client + +client.online(); // $ExpectType Client + +client.send(new Error()); // $ExpectType RaygunPayload +client.send({foo: 'bar'}); // $ExpectType RaygunPayload +client.send('error message'); // $ExpectType RaygunPayload +client.send(new Error(), {foo: 'bar'}); // $ExpectType RaygunPayload +client.send(new Error(), {}, undefined, undefined, ['1', '2']); // $ExpectType RaygunPayload + +client.send(); // $ExpectError +client.send(null); // $ExpectError +client.send(undefined); // $ExpectError diff --git a/types/raygun/tsconfig.json b/types/raygun/tsconfig.json new file mode 100644 index 0000000000..f85de6fb88 --- /dev/null +++ b/types/raygun/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", + "raygun-tests.ts" + ] +} diff --git a/types/raygun/tslint.json b/types/raygun/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/raygun/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/raygun4js/index.d.ts b/types/raygun4js/index.d.ts index 66a7ce8ee9..d5faa0028b 100644 --- a/types/raygun4js/index.d.ts +++ b/types/raygun4js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for raygun4js 2.6.0 +// Type definitions for raygun4js 2.13 // Project: https://github.com/MindscapeHQ/raygun4js -// Definitions by: Brian Surowiec , Benjamin Harding +// Definitions by: Brian Surowiec , Benjamin Harding , Taylor Lodge // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 interface TracekitStackTrace { message: string; @@ -20,7 +21,6 @@ interface TracekitStack { url: string; } - interface RaygunStackTrace { LineNumber: number; ColumnNumber: number; @@ -61,14 +61,17 @@ interface RaygunOptions { disablePulse?: boolean; /** - * Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested. + * Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). + * Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested. */ - excludedHostnames?: (string|RegExp)[]; + excludedHostnames?: ReadonlyArray; /** - * Prevents errors from being sent from certain user agents by providing an array of strings. This is very helpful to exclude errors reported by certain browsers or test automation with CasperJS, PhantomJS or any other testing utility that sends a custom user agent. If a part of the client's navigator.userAgent matches one of the given strings in the array, then the client will be excluded from error reporting. + * Prevents errors from being sent from certain user agents by providing an array of strings. + * This is very helpful to exclude errors reported by certain browsers or test automation with CasperJS, PhantomJS or any other testing utility that sends a custom user agent. + * If a part of the client's navigator.userAgent matches one of the given strings in the array, then the client will be excluded from error reporting. */ - excludedUserAgents?: (string|RegExp)[]; + excludedUserAgents?: ReadonlyArray; /** * The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes). @@ -80,11 +83,6 @@ interface RaygunOptions { */ pulseIgnoreUrlCasing?: boolean; - /** - * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. - */ - apiUrl?: string; - /** * If false, async callback functions triggered by setTimeout/setInterval will not be wrapped when attach() is called. Defaults to true */ @@ -95,20 +93,25 @@ interface RaygunOptions { */ debugMode?: boolean; + captureUnhandledRejections?: boolean; + setCookieAsSecure?: boolean; + /** - * Ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. + * Ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - + * if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. */ ignore3rdPartyErrors?: boolean; /** - * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. + * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. + * This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. */ apiEndpoint?: string; /** * String which can be optionally set "onLoad" which will then boot the RealUserMonitoring side instead of waiting for the `load` event. */ - from?: string|"onLoad"; + from?: string | "onLoad"; } interface RaygunPayload { @@ -121,16 +124,16 @@ interface RaygunPayload { }; Environment: { UtcOffset: number; - 'User-Language': string; - 'Document-Mode': number; - 'Browser-Width': number; - 'Browser-Height': number; - 'Screen-Width': number; - 'Screen-Height': number; - 'Color-Depth': number; + "User-Language": string; + "Document-Mode": number; + "Browser-Width": number; + "Browser-Height": number; + "Screen-Width": number; + "Screen-Height": number; + "Color-Depth": number; Browser: string; - 'Browser-Name': string; - 'Browser-Version': string; + "Browser-Name": string; + "Browser-Version": string; Platform: string; }; Client: { @@ -143,7 +146,7 @@ interface RaygunPayload { Url: string; QueryString: string; Headers: { - 'User-Agent': string; + "User-Agent": string; Referer: string; Host: string; }; @@ -162,7 +165,6 @@ interface RaygunPayload { } interface RaygunStatic { - /** * Prevents Raygun from overwriting anything bound to `window.Raygun`. */ @@ -176,7 +178,11 @@ interface RaygunStatic { /** * Configures the Raygun provider. */ - init(apiKey: string, options?: RaygunOptions, customdata?: any): RaygunStatic; + init( + apiKey: string, + options?: RaygunOptions, + customdata?: any + ): RaygunStatic; /** * Attaches custom data to any errors sent to Raygun. @@ -206,7 +212,14 @@ interface RaygunStatic { /** * Provides additional information about the current user. */ - setUser(user: string, isAnonymous?: boolean, email?: string, fullName?: string, firstName?: string, uuid?: string): RaygunStatic; + setUser( + user: string, + isAnonymous?: boolean, + email?: string, + fullName?: string, + firstName?: string, + uuid?: string + ): RaygunStatic; /** * Resets the information about the current user. @@ -226,12 +239,14 @@ interface RaygunStatic { /** * Blacklist keys to prevent their values from being sent to Raygun. */ - filterSensitiveData(filteredKeys: (string|RegExp)[]): RaygunStatic; + filterSensitiveData( + filteredKeys: ReadonlyArray + ): RaygunStatic; /** * Change the scope at which filters are applied. Defaults to `customData` by default. */ - setFilterScope(scope: "all"|"customData"): RaygunStatic; + setFilterScope(scope: "all" | "customData"): RaygunStatic; /** * Whitelist damains which should transmit errors to Raygun. @@ -241,12 +256,20 @@ interface RaygunStatic { /** * Executed before the payload is sent. If a truthy object is returned, Raygun will attempt to use that as the payload. Raygun will abort the send if `false` is returned. */ - onBeforeSend(callback: (payload: RaygunPayload) => RaygunPayload|boolean): RaygunStatic; + onBeforeSend( + callback: (payload: RaygunPayload) => RaygunPayload | boolean + ): RaygunStatic; /** * Overrides the default automatic grouping and instead group errors together by the string returned by the callback. */ - groupingKey(callback: (payload: RaygunPayload, stackTrace: TracekitStackTrace, options: any) => string|void): RaygunStatic; + groupingKey( + callback: ( + payload: RaygunPayload, + stackTrace: TracekitStackTrace, + options: any + ) => string | void + ): RaygunStatic; onBeforeXHR(callback: (xhr: XMLHttpRequest) => void): RaygunStatic; onAfterSend(callback: (response: XMLHttpRequest) => void): RaygunStatic; endSession(): void; @@ -259,22 +282,29 @@ interface RaygunStatic { /** * Records a manual breadcrumb with the given message and metadata passed. */ - recordBreadcrumb(message:string,metadata?:any): void; + recordBreadcrumb(message: string, metadata?: any): void; /** * Enables all breadcrumbs level or a type can be passed which will enable only that passed one. */ - enableAutoBreadcrumbs(type?:"XHR"|"Clicks"|"Console"|"Navigation"): void; + enableAutoBreadcrumbs( + type?: "XHR" | "Clicks" | "Console" | "Navigation" + ): void; /** * Disables all breadcrumbs or a type can be passed to disable only that one. */ - disableAutoBreadcrumbs(type?:"XHR"|"Clicks"|"Console"|"Navigation"): void; + disableAutoBreadcrumbs( + type?: "XHR" | "Clicks" | "Console" | "Navigation" + ): void; /** * Pass "breadcrumbsLevel" alongside a valid breadcrumbs level to set the current level. Passing options other than "breadcrumbsLevel" will set xhr hosts to ignore being */ - setBreadcrumbOption(option?:string|"breadcrumbsLevel", value?:string|"debug"|"info"|"warning"|"error"): void; + setBreadcrumbOption( + option?: string | "breadcrumbsLevel", + value?: string | "debug" | "info" | "warning" | "error" + ): void; } interface RaygunV2UserDetails { @@ -286,7 +316,7 @@ interface RaygunV2UserDetails { /** * Indicates whether the user is anonymous or has a user account. Even if this is set to true, you should still give the user a unique identifier of some kind. */ - isAnonymous?: string; + isAnonymous?: boolean; /** * The user's email address. @@ -309,42 +339,79 @@ interface RaygunV2UserDetails { uuid?: string; } - +type BreadcrumbLevel = "debug" | "error" | "warning" | "info"; interface RaygunV2 { - (key: "options", value:RaygunOptions):void; - (key: "setUser", value: RaygunV2UserDetails):void; - (key: "onBeforeSend", callback: (payload: RaygunPayload) => RaygunPayload|boolean):void; - (key: "onBeforeXHR"|"onAfterSend", callback: (xhr: XMLHttpRequest) => void): void; - (key: "groupingKey", value:(payload: RaygunPayload, stackTrace: TracekitStackTrace, options: any) => string|void):void; - (key: "trackEvent", value: { type: string, path: string }): void; - (key: "apiKey"|"setVersion"|"setFilterScope", value:string):void; - (key: "attach"|"enableCrashReporting"|"enablePulse"|"noConflict"|"saveIfOffline", value: boolean):void; - (key: "filterSensitiveData"|"whitelistCrossOriginDomains"|"withTags", values: string[]): void; - (key: "send"|"withCustomData", value: any): void; - (key: "getRaygunInstance"):RaygunStatic; - (key: "detach"): void; - (key: "disableAutoBreadcrumbs"): void; - (key: "enableAutoBreadcrumbs"): void; - (key: "disableAutoBreadcrumbsConsole"): void; - (key: "enableAutoBreadcrumbsConsole"): void; - (key: "disableAutoBreadcrumbsNavigation"): void; - (key: "enableAutoBreadcrumbsNavigation"): void; - (key: "disableAutoBreadcrumbsClicks"): void; - (key: "enableAutoBreadcrumbsClicks"): void; - (key: "disableAutoBreadcrumbsXHR"): void; - (key: "enableAutoBreadcrumbsXHR"): void; - (key: "setAutoBreadcrumbsXHRIgnoredHosts"): void; - (key: "setBreadcrumbLevel"): void; - (key: "recordBreadcrumb", message:string|{message:string,metadata:any,level:string|"debug"|"info"|"warning"|"error",location:string}, metadata:any): void; - (key: string):void; + (key: "options", value: RaygunOptions): void; + (key: "setUser", value: RaygunV2UserDetails): void; + ( + key: "onBeforeSend", + callback: (payload: RaygunPayload) => RaygunPayload | boolean + ): void; + ( + key: "onBeforeXHR" | "onAfterSend", + callback: (xhr: XMLHttpRequest) => void + ): void; + ( + key: "groupingKey", + value: ( + payload: RaygunPayload, + stackTrace: TracekitStackTrace, + options: any + ) => string | void + ): void; + (key: "trackEvent", value: { type: string; path: string }): void; + (key: "apiKey" | "setVersion" | "setFilterScope", value: string): void; + ( + key: + | "attach" + | "enableCrashReporting" + | "enablePulse" + | "noConflict" + | "saveIfOffline", + value: boolean + ): void; + ( + key: "filterSensitiveData" | "whitelistCrossOriginDomains" | "withTags", + values: string[] + ): void; + (key: "send" | "withCustomData", value: any): void; + (key: "getRaygunInstance"): RaygunStatic; + ( + key: + | "detach" + | "disableAutoBreadcrumbs" + | "enableAutoBreadcrumbs" + | "disableAutoBreadcrumbsConsole" + | "enableAutoBreadcrumbsConsole" + | "disableAutoBreadcrumbsNavigation" + | "enableAutoBreadcrumbsNavigation" + | "disableAutoBreadcrumbsClicks" + | "enableAutoBreadcrumbsClicks" + | "disableAutoBreadcrumbsXHR" + | "enableAutoBreadcrumbsXHR" + | "setAutoBreadcrumbsXHRIgnoredHosts" + ): void; + (key: "setBreadcrumbLevel", level: BreadcrumbLevel): void; + ( + key: "recordBreadcrumb", + message: + | string + | { + message: string; + metadata: any; + level: BreadcrumbLevel; + location: string; + }, + metadata: object + ): void; } +declare const rg4js: RaygunV2; + interface Window { Raygun: RaygunStatic; } -declare var Raygun: RaygunStatic; +export { RaygunStatic, RaygunV2 }; -declare module 'raygun4js' { - export = Raygun; -} +export default rg4js; diff --git a/types/raygun4js/raygun4js-tests.ts b/types/raygun4js/raygun4js-tests.ts index 7fe6fc6496..388c960276 100644 --- a/types/raygun4js/raygun4js-tests.ts +++ b/types/raygun4js/raygun4js-tests.ts @@ -1,8 +1,7 @@ // V2 Api +// Used in CommonJS-like environments -// To use the V2 api you will need to declare a `rg4js` variable -// This is because `rg4js` name is configurable by users -declare var rg4js: RaygunV2; +import rg4js, { RaygunStatic } from 'raygun4js'; rg4js("apiKey", "api-key"); rg4js("enableCrashReporting", true); @@ -13,16 +12,25 @@ rg4js('setUser', { fullName: "Robert Raygun" }); +try { + throw new Error('oops'); +} catch (e) { + rg4js('send', e); +} + // V1 Api -var client: RaygunStatic = Raygun.noConflict(); -var newClient: RaygunStatic = client.constructNewRaygun(); +// Used in non CommonJS enviroments +declare const Raygun: RaygunStatic; + +const client: RaygunStatic = Raygun.noConflict(); +const newClient: RaygunStatic = client.constructNewRaygun(); client.init('api-key'); client.init('api-key', { allowInsecureSubmissions: true, disablePulse: false }); client.init('api-key', { allowInsecureSubmissions: true, disablePulse: false }, { some: 'data' }); client.withCustomData({ some: 'data' }); -client.withCustomData(function() { +client.withCustomData(() => { return { some: 'data' }; }); @@ -36,8 +44,7 @@ client.send(new Error('a error'), { some: 'data' }, ['tag1', 'tag2']); try { throw new Error('oops'); -} -catch (e) { +} catch (e) { client.send(e); } @@ -57,7 +64,7 @@ client.setFilterScope('all'); client.whitelistCrossOriginDomains(['domain1', 'domain2']); -client.onBeforeSend(payload=> { +client.onBeforeSend(payload => { payload.OccurredOn = new Date(); return payload; }); diff --git a/types/raygun4js/tslint.json b/types/raygun4js/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/raygun4js/tslint.json +++ b/types/raygun4js/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/rc-time-picker/index.d.ts b/types/rc-time-picker/index.d.ts new file mode 100644 index 0000000000..62f6a7711a --- /dev/null +++ b/types/rc-time-picker/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for rc-time-picker 3.4 +// Project: http://github.com/react-component/time-picker +// Definitions by: Frithjof Winkelmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as moment from "moment"; +import * as React from 'react'; + +interface TimePickerProps { + prefixCls: string; + clearText: string; + disabled: boolean; + allowEmpty: boolean; + open: boolean; + defaultValue: moment.Moment; + defaultOpenValue: moment.Moment; + value: moment.Moment; + placeholder: string; + className: string; + id: string; + popupClassName: string; + showHour: boolean; + showMinute: boolean; + showSecond: boolean; + format: string; + disabledHours: () => number[]; + disabledMinutes: (hour: number) => number[]; + disabledSeconds: (hour: number, minute: number) => number[]; + use12Hours: boolean; + hideDisabledOptions: boolean; + onChange: (value: moment.Moment) => void; + addon: (timepicker: TimePicker) => JSX.Element; + placement: string; + transitionName: string; + onOpen: (state: { open: boolean }) => void; + onClose: (state: { open: boolean }) => void; + hourStep: number; + minuteStep: number; + secondStep: number; + focusOnOpen: boolean; + inputReadOnly: boolean; + inputIcon: React.ReactNode; + clearIcon: React.ReactNode; +} + +declare class TimePicker extends React.Component> { + constructor(props: Readonly>) + + close(): void; + isAM(): boolean; +} + +export = TimePicker; diff --git a/types/rc-time-picker/rc-time-picker-tests.tsx b/types/rc-time-picker/rc-time-picker-tests.tsx new file mode 100644 index 0000000000..7f0ea63e9c --- /dev/null +++ b/types/rc-time-picker/rc-time-picker-tests.tsx @@ -0,0 +1,10 @@ +import TimePicker from 'rc-time-picker'; +import * as React from 'react'; +import moment from 'moment'; + + {}} + placeholder={'Input time'} + showSecond={false} + onOpen={({open}: { open: boolean }) => {}}/>; diff --git a/types/rc-time-picker/tsconfig.json b/types/rc-time-picker/tsconfig.json new file mode 100644 index 0000000000..adda4c82bb --- /dev/null +++ b/types/rc-time-picker/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "rc-time-picker-tests.tsx" + ] +} diff --git a/types/rc-time-picker/tslint.json b/types/rc-time-picker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rc-time-picker/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/reach__router/index.d.ts b/types/reach__router/index.d.ts index 3a849dd8ee..60b1c6253e 100644 --- a/types/reach__router/index.d.ts +++ b/types/reach__router/index.d.ts @@ -8,16 +8,22 @@ import * as React from "react"; import { Location as HLocation } from "history"; export type WindowLocation = Window["location"] & HLocation; +export type HistoryActionType = "PUSH" | "POP"; +export type HistoryLocation = WindowLocation & { state?: any }; +export interface HistoryListenerParameter { + location: HistoryLocation; + action: HistoryActionType; +} +export type HistoryListener = (parameter: HistoryListenerParameter) => void; +export type HistoryUnsubscribe = () => void; + export interface History { - readonly location: string; + readonly location: HistoryLocation; readonly transitioning: boolean; listen: (listener: HistoryListener) => HistoryUnsubscribe; navigate: NavigateFn; } -export type HistoryListener = () => void; -export type HistoryUnsubscribe = () => void; - export class Router extends React.Component { } export interface RouterProps { @@ -147,3 +153,5 @@ export interface RedirectRequest { export function isRedirect(error: any): error is RedirectRequest; export function redirectTo(uri: string): void; + +export const globalHistory: History; diff --git a/types/react-alert/index.d.ts b/types/react-alert/index.d.ts index 3814b7f29f..6c94da77b0 100644 --- a/types/react-alert/index.d.ts +++ b/types/react-alert/index.d.ts @@ -1,110 +1,97 @@ -// Type definitions for react-alert 2.4 +// Type definitions for react-alert 4.0 // Project: https://github.com/schiehll/react-alert -// Definitions by: Steve Syrell +// Definitions by: Yue Yang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from "react"; +import * as React from 'react'; -export interface AlertContainerProps { - /** - * The offset of the alert from the page border, can be any number. - * - * Default: 14. - */ - offset: number; +export type AlertPosition = + | 'top left' + | 'top right' + | 'top center' + | 'bottom left' + | 'bottom right' + | 'bottom center'; - /** - * The position of the alert. Can be [bottom left, bottom right, top left, top right]. - * - * Default: 'bottom left' - */ - position: string; +export type AlertType = 'info' | 'success' | 'error'; +export type AlertTransition = 'fade' | 'scale'; +export interface ProviderOptions { /** - * The color theme of the alert. Can be [dark, light]. + * The margin of each alert * - * Default: 'dark' + * Default value: '10px' */ - theme: string; - + offset?: string; /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure - * (applies to all alerts). + * The position of the alerts in the page * - * Default: 5000 + * Default value: 'top center' */ - time: number; - + position?: AlertPosition; /** - * The transition animation. Can be [scale, fade]. + * Timeout to alert remove itself, if set to 0 it never removes itself * - * Default: 'scale' + * Default value: 0 */ - transition: string; + timeout?: number; + /** + * The default alert type used when calling this.props.alert.show + * + * Default value: 'info' + */ + type?: AlertType; + /** + * The transition animation + * + * Default value: 'fade' + */ + transition?: AlertTransition; + /** + * The z-index of alerts + * + * Default value: 100 + */ + zIndex?: number; } -export interface AlertShowOptions { - /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure. - */ - time?: number; +export class Provider extends React.Component {} - /** - * The icon to show in the alert. - * - * Default: the icon which matches the type of alert to be shown. - */ - icon?: React.ReactNode; +export const Alert: React.Consumer; +export interface AlertCustomOptions { /** - * A callback function that will be called when the alert is closed. + * Custom timeout just for this one alert */ - onClose?: () => void; - + timeout?: number; /** - * The type of alert to show. This will only be used when calling show(). - * Can be [info, success, error]. - * - * Default: 'info' + * Callback that will be executed after this alert open */ - type?: string; + onOpen?(): undefined; + /** + * Callback that will be executed after this alert is removed + */ + onClose?(): undefined; } -export default class AlertContainer extends React.Component { - /** - * Show a success alert. - * @returns The id of the created alert. - */ - success(message: string, options?: AlertShowOptions): string; - - /** - * Show an error alert. - * @returns The id of the created alert. - */ - error(message: string, options?: AlertShowOptions): string; - - /** - * Show an info alert. - * @returns The id of the created alert. - */ - info(message: string, options?: AlertShowOptions): string; - - /** - * Show an alert. - * @returns The id of the created alert. - */ - show(message: string, options?: AlertShowOptions): string; - - /** - * Remove all alerts from the page. - */ - removeAll(): void; - - /** - * Removes the alert with the specified id from the page. - */ - remove(id: string): void; +export interface AlertCustomOptionsWithType extends AlertCustomOptions { + type?: AlertType; } + +export interface InjectedAlertProp { + show( + message?: string, + options?: AlertCustomOptionsWithType + ): InjectedAlertProp; + remove(alert: InjectedAlertProp): undefined; + success(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + error(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + info(message?: string, options?: AlertCustomOptions): InjectedAlertProp; +} + +export function withAlert

( + c: React.ComponentType

+): React.ComponentType>>; diff --git a/types/react-alert/react-alert-tests.tsx b/types/react-alert/react-alert-tests.tsx index 84686ea73d..c6088a52a8 100644 --- a/types/react-alert/react-alert-tests.tsx +++ b/types/react-alert/react-alert-tests.tsx @@ -1,48 +1,91 @@ -import * as React from "react"; -import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; +import * as React from 'react'; +import { + Provider as AlertProvider, + Alert, + withAlert, + AlertPosition, + AlertTransition, + ProviderOptions, + InjectedAlertProp +} from 'react-alert'; -export class ReactAlertTest extends React.Component { - private _alert: AlertContainer; +class AppWithoutAlert extends React.Component<{ alert: InjectedAlertProp }> { render() { - const props: AlertContainerProps = { - offset: 14, - position: "bottom left", - theme: "dark", - time: 5000, - transition: "scale" - }; + return ( + + ); + } +} + +const App = withAlert(AppWithoutAlert); + +class AppAlert extends React.Component { + render() { + return ( + + {alert => ( + + )} + + ); + } +} + +class AlertTemplate extends React.Component { + render() { + // the style contains only the margin given as offset + // options contains all alert given options + // message is the alert message... + // close is a function that closes the alert + const { style, options, message, close } = this.props; return ( -

- this._alert = a as AlertContainer} {...props} /> +
+ {options.type === 'info' && '!'} + {options.type === 'success' && ':)'} + {options.type === 'error' && ':('} + {message} +
); } +} - private _testMethods(): void { - const options: AlertShowOptions = { - time: 5000, - type: "info", - onClose: this._onAlertClosed, - icon: - }; +const options: ProviderOptions = { + position: 'bottom center' as AlertPosition, + timeout: 5000, + offset: '30px', + transition: 'scale' as AlertTransition +}; - let alertId: string; - alertId = this._alert.show("show without options"); - alertId = this._alert.show("show with options", options); - - alertId = this._alert.error("error without options"); - alertId = this._alert.error("error with options", options); - - alertId = this._alert.info("info without options"); - alertId = this._alert.info("info with options", options); +class Root extends React.Component { + render() { + return ( + + + + ); + } +} - alertId = this._alert.success("success without options"); - alertId = this._alert.success("success with options", options); - - this._alert.remove(alertId); - this._alert.removeAll(); +class RootAlert extends React.Component { + render() { + return ( + + + + ); } - - private _onAlertClosed(): void { } } diff --git a/types/react-alert/v2/index.d.ts b/types/react-alert/v2/index.d.ts new file mode 100644 index 0000000000..3814b7f29f --- /dev/null +++ b/types/react-alert/v2/index.d.ts @@ -0,0 +1,110 @@ +// Type definitions for react-alert 2.4 +// Project: https://github.com/schiehll/react-alert +// Definitions by: Steve Syrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export interface AlertContainerProps { + /** + * The offset of the alert from the page border, can be any number. + * + * Default: 14. + */ + offset: number; + + /** + * The position of the alert. Can be [bottom left, bottom right, top left, top right]. + * + * Default: 'bottom left' + */ + position: string; + + /** + * The color theme of the alert. Can be [dark, light]. + * + * Default: 'dark' + */ + theme: string; + + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure + * (applies to all alerts). + * + * Default: 5000 + */ + time: number; + + /** + * The transition animation. Can be [scale, fade]. + * + * Default: 'scale' + */ + transition: string; +} + +export interface AlertShowOptions { + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure. + */ + time?: number; + + /** + * The icon to show in the alert. + * + * Default: the icon which matches the type of alert to be shown. + */ + icon?: React.ReactNode; + + /** + * A callback function that will be called when the alert is closed. + */ + onClose?: () => void; + + /** + * The type of alert to show. This will only be used when calling show(). + * Can be [info, success, error]. + * + * Default: 'info' + */ + type?: string; +} + +export default class AlertContainer extends React.Component { + /** + * Show a success alert. + * @returns The id of the created alert. + */ + success(message: string, options?: AlertShowOptions): string; + + /** + * Show an error alert. + * @returns The id of the created alert. + */ + error(message: string, options?: AlertShowOptions): string; + + /** + * Show an info alert. + * @returns The id of the created alert. + */ + info(message: string, options?: AlertShowOptions): string; + + /** + * Show an alert. + * @returns The id of the created alert. + */ + show(message: string, options?: AlertShowOptions): string; + + /** + * Remove all alerts from the page. + */ + removeAll(): void; + + /** + * Removes the alert with the specified id from the page. + */ + remove(id: string): void; +} diff --git a/types/react-alert/v2/react-alert-tests.tsx b/types/react-alert/v2/react-alert-tests.tsx new file mode 100644 index 0000000000..84686ea73d --- /dev/null +++ b/types/react-alert/v2/react-alert-tests.tsx @@ -0,0 +1,48 @@ +import * as React from "react"; +import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; + +export class ReactAlertTest extends React.Component { + private _alert: AlertContainer; + render() { + const props: AlertContainerProps = { + offset: 14, + position: "bottom left", + theme: "dark", + time: 5000, + transition: "scale" + }; + + return ( +
+ this._alert = a as AlertContainer} {...props} /> +
+ ); + } + + private _testMethods(): void { + const options: AlertShowOptions = { + time: 5000, + type: "info", + onClose: this._onAlertClosed, + icon: + }; + + let alertId: string; + alertId = this._alert.show("show without options"); + alertId = this._alert.show("show with options", options); + + alertId = this._alert.error("error without options"); + alertId = this._alert.error("error with options", options); + + alertId = this._alert.info("info without options"); + alertId = this._alert.info("info with options", options); + + alertId = this._alert.success("success without options"); + alertId = this._alert.success("success with options", options); + + this._alert.remove(alertId); + this._alert.removeAll(); + } + + private _onAlertClosed(): void { } +} diff --git a/types/react-i18next/v4/tsconfig.json b/types/react-alert/v2/tsconfig.json similarity index 57% rename from types/react-i18next/v4/tsconfig.json rename to types/react-alert/v2/tsconfig.json index b2c29f0bea..47de249c7e 100644 --- a/types/react-i18next/v4/tsconfig.json +++ b/types/react-alert/v2/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, @@ -14,23 +13,15 @@ "../../" ], "paths": { - "react-i18next": [ - "react-i18next/v4" - ] + "react-alert": ["react-alert/v2"] }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react", - "experimentalDecorators": true + "jsx": "react" }, "files": [ "index.d.ts", - "react-i18next-tests.tsx", - "I18nextProvider.d.ts", - "interpolate.d.ts", - "loadNamespaces.d.ts", - "trans.d.ts", - "translate.d.ts" + "react-alert-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-alert/v2/tslint.json b/types/react-alert/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-alert/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-i18next/index.d.ts b/types/react-i18next/index.d.ts deleted file mode 100644 index 979c648f50..0000000000 --- a/types/react-i18next/index.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Type definitions for react-i18next 7.8 -// Project: https://github.com/i18next/react-i18next -// Definitions by: Giedrius Grabauskas -// Simon Baumann -// Benedict Etzel -// Wu Haotian -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import { TranslationFunction } from "i18next"; - -import { - setDefaults, - getDefaults, - setI18n, - getI18n, - ReactI18NextOptions, - reactI18nextModule -} from "./src/context"; -import I18n from "./src/I18n"; -import I18nextProvider from "./src/I18nextProvider"; -import Interpolate from "./src/interpolate"; -import loadNamespaces from "./src/loadNamespaces"; -import Trans from "./src/trans"; -import translate from "./src/translate"; - -export { - setDefaults, - getDefaults, - setI18n, - getI18n, - ReactI18NextOptions, - reactI18nextModule, - I18n, - I18nextProvider, - Interpolate, - loadNamespaces, - Trans, - translate, - TranslationFunction -}; - -export { InjectedI18nProps, InjectedTranslateProps } from "./src/props"; - -export as namespace reactI18Next; diff --git a/types/react-i18next/src/I18n.d.ts b/types/react-i18next/src/I18n.d.ts deleted file mode 100644 index 91de868caf..0000000000 --- a/types/react-i18next/src/I18n.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import * as React from "react"; -import { i18n, TranslationFunction } from "i18next"; - -export interface Options { - i18n: i18n; - t: TranslationFunction; -} - -export interface i18nProps { - wait?: boolean; - ns?: string | string[]; - nsMode?: string; - bindI18n?: string; - bindStore?: string; - i18n?: i18n; - initialI18nStore?: any; - initialLanguage?: string; - children: (t: TranslationFunction, options: Options) => React.ReactNode; -} - -export default class I18n extends React.Component { } diff --git a/types/react-i18next/src/I18nextProvider.d.ts b/types/react-i18next/src/I18nextProvider.d.ts deleted file mode 100644 index 2db5d0361b..0000000000 --- a/types/react-i18next/src/I18nextProvider.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -// tslint:disable-next-line:interface-name -export interface I18nextProviderProps { - i18n: i18n; - initialI18nStore?: any; - initialLanguage?: string; - children: React.ReactNode; -} - -export default class I18nextProvider extends React.Component { } diff --git a/types/react-i18next/src/context.d.ts b/types/react-i18next/src/context.d.ts deleted file mode 100644 index f772e8c1da..0000000000 --- a/types/react-i18next/src/context.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { i18n } from "i18next"; - -export interface ReactI18NextOptions { - wait?: boolean; - withRef?: boolean; - bindI18n?: string; - bindStore?: string; - translateFuncName?: string; - nsMode?: string; -} - -export function setDefaults(options: ReactI18NextOptions): void; - -export function getDefaults(): ReactI18NextOptions; - -export function setI18n(instance: i18n): void; - -export function getI18n(): i18n; - -export interface i18NextModule { - type: string; - - init: (instance: i18n) => void; -} - -export const reactI18nextModule: i18NextModule; diff --git a/types/react-i18next/src/interpolate.d.ts b/types/react-i18next/src/interpolate.d.ts deleted file mode 100644 index d6a4e64420..0000000000 --- a/types/react-i18next/src/interpolate.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from "react"; -import { i18n, InterpolationOptions, TranslationFunction } from "i18next"; - -export type InterpolateValue = string | JSX.Element; - -export interface InterpolatePropsBase { - parent?: string; - regexp?: RegExp; - useDangerouslySetInnerHTML?: boolean; - dangerouslySetInnerHTMLPartElement?: string; - options?: InterpolationOptions; - i18nKey?: string; - className?: string; - style?: React.CSSProperties; - i18n?: i18n; - t?: TranslationFunction; -} - -export interface OtherInterpolateProps { - [regexKey: string]: InterpolateValue | RegExp | InterpolationOptions | boolean | undefined; -} - -export type InterpolateProps = InterpolatePropsBase & OtherInterpolateProps; - -export default class Interpolate extends React.PureComponent { } diff --git a/types/react-i18next/src/loadNamespaces.d.ts b/types/react-i18next/src/loadNamespaces.d.ts deleted file mode 100644 index d0e0b372f5..0000000000 --- a/types/react-i18next/src/loadNamespaces.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -export interface LoadNamespacesArguments { - components: Array | React.StatelessComponent>; - i18n: i18n; -} - -export default function loadNamespaces(args: LoadNamespacesArguments): Promise; diff --git a/types/react-i18next/src/props.d.ts b/types/react-i18next/src/props.d.ts deleted file mode 100644 index 8435a7cc45..0000000000 --- a/types/react-i18next/src/props.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { i18n as I18n, TranslationFunction } from "i18next"; - -/** - * Extend your component's Prop interface with this one to get access to `this.props.t` - * - * Please note that if you use the `translateFuncName` option, you should create - * your own interface just like this one, but with your name of the translation function. - * - * interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} - * - * Then specify the name of the translate function as generic argument - * - * const translated = translate("view", { translateFuncName: "_" })(YourComponent); - */ -export interface InjectedTranslateProps { - t: TranslationFunction; -} - -/** - * Extend your component's Prop interface with this one to get access to `this.props.i18n` - */ -export interface InjectedI18nProps { - i18n: I18n; -} diff --git a/types/react-i18next/src/trans.d.ts b/types/react-i18next/src/trans.d.ts deleted file mode 100644 index 2b0e8e7738..0000000000 --- a/types/react-i18next/src/trans.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from "react"; -import { i18n, TranslationFunction } from "i18next"; - -export interface TOptions { - [key: string]: any; -} - -export interface Values { - [key: string]: any; -} - -export interface TransProps { - i18nKey?: string; - count?: number; - parent?: React.ReactNode | (() => React.ReactNode); - i18n?: i18n; - t?: TranslationFunction; - tOptions?: TOptions; - defaults?: string; - values?: Values; - components?: React.ReactNode[]; - ns?: string; -} - -export default class Trans extends React.Component { } diff --git a/types/react-i18next/src/translate.d.ts b/types/react-i18next/src/translate.d.ts deleted file mode 100644 index 0383ee1ead..0000000000 --- a/types/react-i18next/src/translate.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import * as React from "react"; -import { i18n as I18n, TranslationFunction } from "i18next"; -import { InjectedTranslateProps, InjectedI18nProps } from "./props"; -import { setDefaults, setI18n } from "./context"; - -export interface TranslateOptions { - withRef?: boolean; - bindI18n?: string; - bindStore?: string; - translateFuncName?: TTranslateFuncName; - wait?: boolean; - nsMode?: string; - i18n?: I18n; -} - -export interface TranslateHocProps { - i18n?: I18n; - initialI18nStore?: object; - initialLanguage?: string; -} - -// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 -type Omit = Pick; - -type InjectedProps = InjectedI18nProps & InjectedTranslateProps; - -export interface WrapperComponentClass

extends React.ComponentClass

{ - new (props: P, context?: any): React.Component

& { getWrappedInstance(): React.Component }; -} - -// Injects props and removes them from the prop requirements. -// Adds the new properties t (or whatever the translation function is called) and i18n if needed. -export type InferableComponentEnhancerWithProps = -

(component: React.ComponentClass

| React.StatelessComponent

) => - React.ComponentClass & TranslateHocProps>; - -export type InferableComponentEnhancerWithPropsAndRef = -

(component: React.ComponentClass

| React.StatelessComponent

) => - WrapperComponentClass, P>; - -export interface Translate { - - (namespaces?: TNamespace | TNamespace[], options?: Omit & { withRef?: false }): - InferableComponentEnhancerWithProps<"t">; - - - (namespaces?: TNamespace | TNamespace[], options?: Omit & { withRef: true }): - InferableComponentEnhancerWithPropsAndRef<"t">; - - - (namespaces?: TNamespace | TNamespace[], options?: TranslateOptions & { withRef?: false }): - InferableComponentEnhancerWithProps; - - - (namespaces?: TNamespace | TNamespace[], options?: TranslateOptions & { withRef: true }): - InferableComponentEnhancerWithPropsAndRef; - - setDefaults: typeof setDefaults; - setI18n: typeof setI18n; -} - -declare const translate: Translate; -export default translate; diff --git a/types/react-i18next/test/react-i18next-tests.tsx b/types/react-i18next/test/react-i18next-tests.tsx deleted file mode 100644 index 30b95ece24..0000000000 --- a/types/react-i18next/test/react-i18next-tests.tsx +++ /dev/null @@ -1,201 +0,0 @@ -import * as React from 'react'; -import * as i18n from 'i18next'; -import { - setDefaults, - reactI18nextModule, - translate, - I18nextProvider, - Interpolate, - InjectedTranslateProps, - TranslationFunction, - loadNamespaces, - Trans, - I18n, - ReactI18NextOptions -} from 'react-i18next'; -import { InjectedI18nProps } from 'react-i18next/src/props'; - -interface InnerAnotherComponentProps { - _: TranslationFunction; -} - -class InnerAnotherComponent extends React.Component { - render() { - const _ = this.props._; - return

{_('content.text', {/* options t options */})}

; - } -} - -const AnotherComponent = translate('view', {wait: true, translateFuncName: '_'})(InnerAnotherComponent); -const instanceWithoutRef = new AnotherComponent({}); -instanceWithoutRef.componentWillReceiveProps!({ - i18n, - initialI18nStore: { context: { text: "a message" } }, - initialLanguage: "en" -}, {}); - -translate.setDefaults({ wait: false }); -translate.setI18n(i18n); - -const AnotherComponentWithRef = translate("view" as Key, { translateFuncName: "_", withRef: true })(InnerAnotherComponent); -const instanceWithRef = new AnotherComponentWithRef({}); -const ref = instanceWithRef.getWrappedInstance(); -instanceWithRef.componentWillReceiveProps!({ - i18n, - initialI18nStore: { context: { text: "a message" } }, - initialLanguage: "en" -}, {}); - -class InnerYetAnotherComponent extends React.Component { - render() { - const t = this.props.t; - return

{t('usingDefaultNS', {/* options t options */})}

; - } -} - -const YetAnotherComponent = translate()(InnerYetAnotherComponent); - -const YetAnotherComponentWithRef = translate(undefined, { withRef: true })(InnerYetAnotherComponent); -new YetAnotherComponentWithRef({}).getWrappedInstance(); -class TranslatableView extends React.Component { - render() { - const t = this.props.t; - const interpolateComponent = "a interpolated component"; - const options: i18n.InterpolationOptions = {}; - return ( -
- ); - } -} - -const TranslatedView = translate(["view", "nav"] as Key[], { wait: true })(TranslatableView); - -class App extends React.Component { - render() { - return ( -
-
- -
-
- ); - } -} - - - -; - - - 123 -; - -loadNamespaces({components: [App], i18n}).then(() => { -}).catch(error => { -}); - -; -; -; -}/>; -
}/>; -; -; - - -; -; -placeholder - ]} - values={{ - universe: "World" - }} -/>; - -type Key = "view" | "nav"; - -class GenericsTest extends React.Component { - render() { - return null; - } -} - -const TranslatedGenericsTest = translate(["view", "nav"] as Key[])(GenericsTest); -; - -class GenericsTest2 extends React.Component { - render() { - return null; - } -} - -const TranslatedGenericsTest2 = translate("view" as Key)(GenericsTest2); -; - -class ComponentWithInjectedI18n extends React.Component { - render() { return null; } -} - -const TranslatedComponentWithInjectedI18n = translate()(ComponentWithInjectedI18n); -; - -function StatlessComponent(props: InjectedTranslateProps) { - return

{props.t("hy")}

; -} - -const TranslatedStatlessComponent = translate()(StatlessComponent); -; - -interface CustomTranslateFunctionProps { - _: TranslationFunction; -} - - - { - (t, {i18n}) => ( -
-

{t('keyFromDefault')}

-

{t('anotherNamespace:key.from.another.namespace', {/* options t options */})}

-
- ) - } -
; - - - {t => '123'} -; - -const defaults: ReactI18NextOptions = { - wait: true, - withRef: true, - bindI18n: 'string', - bindStore: 'string' -}; -setDefaults(defaults); - -reactI18nextModule.init(i18n.init()); diff --git a/types/react-i18next/v1/index.d.ts b/types/react-i18next/v1/index.d.ts deleted file mode 100644 index 0296da861c..0000000000 --- a/types/react-i18next/v1/index.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -// Type definitions for react-i18next 1.7.0 -// Project: https://github.com/i18next/react-i18next -// Definitions by: Kostya Esmukov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import * as I18next from "i18next"; -import * as React from "react"; - -export type TranslationFunction = I18next.TranslationFunction; - -// Extend your component's Prop interface with this one to get access to `this.props.t` -// -// Please note that if you use the `translateFuncName` option, you should create -// your own interface just like this one, but with your name of the translation function. -// -// interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} -export interface InjectedTranslateProps { - t?: TranslationFunction; -} - -interface I18nextProviderProps { - i18n: I18next.I18n; - children?: React.ReactElement; -} - -export class I18nextProvider extends React.Component { } - - -type InterpolateValue = string | JSX.Element; - -interface InterpolateProps { - i18nKey: string; - - parent?: string; - regexp?: RegExp; - options?: I18next.TranslationOptions; - - useDangerouslySetInnerHTML?: boolean; - dangerouslySetInnerHTMLPartElement?: string; - - [regexKey: string]: InterpolateValue | RegExp | I18next.TranslationOptions | boolean | undefined; -} - -export class Interpolate extends React.Component { } - -interface TranslateOptions { - withRef?: boolean; - wait?: boolean; - translateFuncName?: string; -} - -export function translate(namespaces?: string[] | string, options?: TranslateOptions): (WrappedComponent: C) => C; - -export function loadNamespaces({ components, i18n }: { components: (React.ComponentClass | React.StatelessComponent)[], i18n: I18next.I18n }): Promise; - -export as namespace ReactI18Next; diff --git a/types/react-i18next/v1/react-i18next-tests.tsx b/types/react-i18next/v1/react-i18next-tests.tsx deleted file mode 100644 index 950e29d293..0000000000 --- a/types/react-i18next/v1/react-i18next-tests.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import * as ReactDOM from 'react-dom'; -import * as React from 'react'; -import * as i18n from 'i18next'; -import { translate, I18nextProvider, Interpolate, InjectedTranslateProps, TranslationFunction } from 'react-i18next'; - - -i18n - .init({ - fallbackLng: 'en', - - // have a common namespace used around the full app - ns: ['common'], - defaultNS: 'common', - - debug: true, - - interpolation: { - escapeValue: false // not needed for react!! - } - }); - - -interface InnerAnotherComponentProps { - _?: TranslationFunction; -} - -class InnerAnotherComponent extends React.Component { - render() { - const _ = this.props._!; - - return

{_('content.text', { /* options t options */ })}

; - } -} - -const AnotherComponent = translate('view', { wait: true, translateFuncName: '_' })(InnerAnotherComponent); - - - -interface InnerYetAnotherComponentProps extends InjectedTranslateProps { -} - -class InnerYetAnotherComponent extends React.Component { - render() { - const t = this.props.t!; - - return

{t('usingDefaultNS', { /* options t options */ })}

; - } -} -const YetAnotherComponent = translate()(InnerYetAnotherComponent); - - -interface TranslatableViewProps extends InjectedTranslateProps { -} - -@translate(['view', 'nav'], { wait: true }) -class TranslatableView extends React.Component { - render() { - const t = this.props.t!; - - let interpolateComponent = "a interpolated component"; - - return ( -
-

{t('common:appName')}

- - - - - {t('nav:link1')} -
- ) - } -} - -class App extends React.Component { - render() { - return ( -
-
- -
-
- ); - } -} - - -ReactDOM.render( - , - document.getElementById('app') -); diff --git a/types/react-i18next/v4/I18nextProvider.d.ts b/types/react-i18next/v4/I18nextProvider.d.ts deleted file mode 100644 index 2ecb87f4a1..0000000000 --- a/types/react-i18next/v4/I18nextProvider.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -// tslint:disable-next-line:interface-name -export interface I18nextProviderProps { - i18n: i18n; - children: React.ReactElement; - initialI18nStore?: any; - initialLanguage?: string; -} - -export default class I18nextProvider extends React.Component { } diff --git a/types/react-i18next/v4/index.d.ts b/types/react-i18next/v4/index.d.ts deleted file mode 100644 index 758a00edef..0000000000 --- a/types/react-i18next/v4/index.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Type definitions for react-i18next 4.6 -// Project: https://github.com/i18next/react-i18next -// Definitions by: Giedrius Grabauskas -// Netanel Gilad -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import { TranslationFunction } from "i18next"; - -import I18nextProvider from "./I18nextProvider"; -import Interpolate from "./interpolate"; -import loadNamespaces from "./loadNamespaces"; -import Trans from "./trans"; -import translate from "./translate"; - -export { - I18nextProvider, - Interpolate, - loadNamespaces, - Trans, - translate, - // Exports for TypeScript only - TranslationFunction -}; - -/** - * Extend your component's Prop interface with this one to get access to `this.props.t` - * - * Please note that if you use the `translateFuncName` option, you should create - * your own interface just like this one, but with your name of the translation function. - * - * interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} - */ -export interface InjectedTranslateProps { - t: TranslationFunction; -} - -export as namespace reactI18Next; diff --git a/types/react-i18next/v4/interpolate.d.ts b/types/react-i18next/v4/interpolate.d.ts deleted file mode 100644 index e6f07893ed..0000000000 --- a/types/react-i18next/v4/interpolate.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as React from "react"; -import { InterpolationOptions } from "i18next"; - -export type InterpolateValue = string | JSX.Element; - -export interface InterpolatePropsBase { - parent?: string; - regexp?: RegExp; - useDangerouslySetInnerHTML?: boolean; - dangerouslySetInnerHTMLPartElement?: string; - options?: InterpolationOptions; - i18nKey?: string; - className?: string; - style?: React.CSSProperties; -} - -export interface OtherInterpolateProps { - [regexKey: string]: InterpolateValue | RegExp | InterpolationOptions | boolean | undefined; -} - -export type InterpolateProps = InterpolatePropsBase & OtherInterpolateProps; - -export default class Interpolate extends React.Component { } diff --git a/types/react-i18next/v4/loadNamespaces.d.ts b/types/react-i18next/v4/loadNamespaces.d.ts deleted file mode 100644 index d0e0b372f5..0000000000 --- a/types/react-i18next/v4/loadNamespaces.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -export interface LoadNamespacesArguments { - components: Array | React.StatelessComponent>; - i18n: i18n; -} - -export default function loadNamespaces(args: LoadNamespacesArguments): Promise; diff --git a/types/react-i18next/v4/react-i18next-tests.tsx b/types/react-i18next/v4/react-i18next-tests.tsx deleted file mode 100644 index 3e57dd091b..0000000000 --- a/types/react-i18next/v4/react-i18next-tests.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import * as React from 'react'; -import * as i18n from 'i18next'; -import { translate, I18nextProvider, Interpolate, InjectedTranslateProps, TranslationFunction, loadNamespaces, Trans } from 'react-i18next'; - -interface InnerAnotherComponentProps { - _?: TranslationFunction; -} - -class InnerAnotherComponent extends React.Component { - render() { - const _ = this.props._!; - return

{_('content.text', { /* options t options */ })}

; - } -} - -const AnotherComponent = translate('view', { wait: true, translateFuncName: '_' })(InnerAnotherComponent); - -class InnerYetAnotherComponent extends React.Component { - render() { - const t = this.props.t; - return

{t('usingDefaultNS', { /* options t options */ })}

; - } -} - -const YetAnotherComponent = translate()(InnerYetAnotherComponent); - -class TranslatableView extends React.Component { - render() { - const t = this.props.t; - const interpolateComponent = "a interpolated component"; - - return ( -
-

{t('common:appName')}

- - - - - {t('nav:link1')} -
- ); - } -} - -const WrappedTranslatableView = translate(['view', 'nav'], { wait: true })(TranslatableView); - -class App extends React.Component { - render() { - return ( -
-
- -
-
- ); - } -} - - - -; - -loadNamespaces({ components: [App], i18n }).then(() => { }).catch(error => { }); - -; -; - - -; - -type Key = "view" | "nav"; - -class GenericsTest extends React.Component { - render() { return null; } -} - -translate(['view', 'nav'])(GenericsTest); - -class GenericsTest2 extends React.Component { - render() { return null; } -} - -translate('view')(GenericsTest2); diff --git a/types/react-i18next/v4/trans.d.ts b/types/react-i18next/v4/trans.d.ts deleted file mode 100644 index 384e1605f9..0000000000 --- a/types/react-i18next/v4/trans.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as React from "react"; - -export interface TransProps { - i18nKey?: string; - [name: string]: any; -} - -export default class Trans extends React.Component { } diff --git a/types/react-i18next/v4/translate.d.ts b/types/react-i18next/v4/translate.d.ts deleted file mode 100644 index 9a4fb6ddc2..0000000000 --- a/types/react-i18next/v4/translate.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; -import { InjectedTranslateProps } from "react-i18next"; - -export interface TranslateOptions { - withRef?: boolean; - bindI18n?: string; - bindStore?: string; - translateFuncName?: string; - wait?: boolean; - nsMode?: string; - i18n?: i18n; -} - -// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 -export type Omit = Pick; - -// Injects props and removes them from the prop requirements. -// Adds the new properties t (or whatever the translation function is called) and i18n if needed. -export type InferableComponentEnhancerWithProps = -

(component: React.ComponentClass

| React.StatelessComponent

) => - React.ComponentClass>; - -// tslint:disable-next-line:ban-types -export default function translate(namespaces?: TKey[] | TKey, options?: TranslateOptions): InferableComponentEnhancerWithProps<"t">; 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/react-instantsearch-core/index.d.ts b/types/react-instantsearch-core/index.d.ts new file mode 100644 index 0000000000..e428cc6432 --- /dev/null +++ b/types/react-instantsearch-core/index.d.ts @@ -0,0 +1,468 @@ +// Type definitions for react-instantsearch-core 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +// Core +/** + * Creates a specialized root InstantSearch component. It accepts + * an algolia client and a specification of the root Element. + * @param defaultAlgoliaClient - a function that builds an Algolia client + * @param root - the defininition of the root of an InstantSearch sub tree. + * @returns an InstantSearch root + */ +export function createInstantSearch( + defaultAlgoliaClient: (appId: string, apiKey: string, options: { _useRequestCache: boolean }) => object, + root: object +): React.ComponentClass; + +/** + * Creates a specialized root Index component. It accepts + * a specification of the root Element. + * @param defaultRoot - the defininition of the root of an Index sub tree. + * @return a Index root + */ +export function createIndex(defaultRoot: object): React.ComponentClass; + +export interface ConnectorDescription { + displayName: string; + propTypes?: any; + defaultProps?: any; + + /** + * This method should return the props to forward to the composed component. + * props are the props that were provided to the higher-order component. + * searchState holds the search state of all widgets. You can find the shape of all widgets search state in the corresponding guide. + * searchResults holds the search results, search errors and search loading state, with the shape + * {results: ?SearchResults, error: ?Error, searching: boolean, searchingForFacetValues: boolean}. The SearchResults type is described in the Helper’s documentation. + * meta is the list of metadata from all widgets whose connector defines a getMetadata method. + * searchForFacetValuesResults holds the search for facet values results. + */ + getProvidedProps?(...args: any[]): any; + + /** + * This method defines exactly how the refine prop of widgets affects the search state. + * It takes in the current props of the higher-order component, the search state of all widgets, as well as all arguments passed + * to the refine and createURL props of stateful widgets, and returns a new state. + */ + refine?(...args: any[]): any; + + /** + * This method applies the current props and state to the provided SearchParameters, and returns a new SearchParameters. The SearchParameters + * type is described in the Helper’s documentation. + * Every time the props or state of a widget change, all the getSearchParameters methods of all the registered widgets are called in a chain + * to produce a new SearchParameters. Then, if the output SearchParameters differs from the previous one, a new search is triggered. + * As such, the getSearchParameters method allows you to describe how the state and props of a widget should affect the search parameters. + */ + getSearchParameters?(...args: any[]): any; + + /** + * This method allows the widget to register a custom metadata object for any props and state combination. + * If your widget is stateful, the corresponding URL key should be declared on the metadata object as the id property, so that the InstantSearch + * component can determine which URL keys it controls and which are foreign and should be left intact. + * The metadata object also allows you to declare any data that you would like to pass down to all other widgets. The list of metadata objects of + * all components is available as the fourth argument to the getProvidedProps method. + * The CurrentRefinements widget leverages this mechanism in order to allow any widget to declare the filters it has applied. If you want to add + * your own filter, declare a filters property on your widget’s metadata + */ + getMetadata?(...args: any[]): any; + + /** + * This method needs to be implemented if you want to have the ability to perform a search for facet values inside your widget. + * It takes in the current props of the higher-order component, the search state of all widgets, as well as all arguments passed to the searchForFacetValues + * props of stateful widgets, and returns an object of the shape: {facetName: string, query: string, maxFacetHits?: number}. The default value for the + * maxFacetHits is the one set by the API which is 10. + */ + searchForFacetValues?(...args: any[]): any; + + /** + * This method is called when a widget is about to unmount in order to clean the searchState. + * It takes in the current props of the higher-order component and the searchState of all widgets and expect a new searchState in return. + * props are the props that were provided to the higher-order component. + * searchState holds the searchState of all widgets, with the shape {[widgetId]: widgetState}. Stateful widgets describe the format of their searchState + * in their respective documentation entry. + */ + cleanUp?(...args: any[]): any; +} + +/** + * Connectors are the HOC used to transform React components + * into InstantSearch widgets. + * In order to simplify the construction of such connectors + * `createConnector` takes a description and transform it into + * a connector. + * @param connectorDesc the description of the connector + * @return a function that wraps a component into + * an instantsearch connected one. + */ +export function createConnector(connectorDesc: ConnectorDescription): (Composed: React.ComponentType) => React.ComponentClass; + +// Utils +export const HIGHLIGHT_TAGS: { + highlightPreTag: string, + highlightPostTag: string, +}; +export const version: string; +export function translatable(defaultTranslations: any): (Composed: React.ComponentType) => React.ComponentClass; + +// Widgets +/** + * Configure is a widget that lets you provide raw search parameters + * to the Algolia API. + * + * Any of the props added to this widget will be forwarded to Algolia. For more information + * on the different parameters that can be set, have a look at the + * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). + * + * This widget can be used either with react-dom and react-native. It will not render anything + * on screen, only configure some parameters. + */ +export class Configure extends React.Component {} + +// Connectors +export function connectAutoComplete(Composed: React.ComponentType): React.ComponentClass; +export function connectBreadcrumb(Composed: React.ComponentType): React.ComponentClass; +export function connectConfigure(Composed: React.ComponentType): React.ComponentClass; +export function connectCurrentRefinements(Composed: React.ComponentType): React.ComponentClass; + +export interface NESW { + northEast: { lat: number, lng: number }; + southWest: { lat: number, lng: number }; +} + +export interface GeoSearchExposed { + defaultRefinement?: NESW; +} +export interface GeoSearchProvided { + /** a function to toggle the refinement */ + refine: (refinement: NESW) => void; + /** a function to generate a URL for the corresponding search state */ + createURL: (...args: any[]) => any; + /** the records that matched the search */ + hits: THit[]; + /** true if the current refinement is set with the map bounds */ + isRefinedWithMap: boolean; + /** the refinement currently applied */ + currentRefinement: NESW; + /** the position of the search */ + position: { lat: number, lng: number }; +} +/** + * The GeoSearch connector provides the logic to build a widget that will display the results on a map. + * It also provides a way to search for results based on their position. The connector provides function to manage the + * search experience (search on map interaction). + * + * https://community.algolia.com/react-instantsearch/connectors/connectGeoSearch.html + */ +export function connectGeoSearch(stateless: React.StatelessComponent): React.ComponentClass; +export function connectGeoSearch>, THit>(ctor: React.ComponentType): ConnectedComponentClass, GeoSearchExposed>; + +export function connectHierarchicalMenu(Composed: React.ComponentType): React.ComponentClass; +export function connectHighlight(Composed: React.ComponentType): React.ComponentClass; + +/** + * connectHits connector provides the logic to create connected components that will render the results retrieved from Algolia. + * To configure the number of hits retrieved, use HitsPerPage widget, connectHitsPerPage connector or pass the hitsPerPage prop to a Configure widget. + * Warning: you will need to use the objectID property available on every hit as a key when iterating over them. This will ensure you have the best possible UI experience especially on slow networks. + * + * https://community.algolia.com/react-instantsearch/connectors/connectHits.html + */ +export function connectHits(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectHitsPerPage(Composed: React.ComponentType): React.ComponentClass; +export function connectInfiniteHits(Composed: React.ComponentType): React.ComponentClass; + +export interface MenuProvided { + items: Array<{count: number, isRefined: boolean, label: string, value: string}>; + currentRefinement: string; + refine: (...args: any[]) => any; + createURL: (...args: any[]) => any; + searchForItems: (...args: any[]) => any; + isFromSearch: boolean; +} +export interface MenuExposed { + attribute: string; + showMore?: boolean; + limit?: number; + showMoreLimit?: number; + defaultRefinement?: string; + transformItems?: (...args: any[]) => any; + searchable?: boolean; +} +/** + * connectMenu connector provides the logic to build a widget that will give the user the ability to choose a single value for a specific facet. + * + * https://community.algolia.com/react-instantsearch/connectors/connectMenu.html + */ +export function connectMenu(stateless: React.StatelessComponent): React.ComponentClass; +export function connectMenu>(ctor: React.ComponentType): ConnectedComponentClass; + +export interface NumericMenuProvided { + /** the list of ranges the NumericMenu can display. */ + items: Array<{isRefined: boolean, label: string, value: string, noRefinement: boolean}>; + /** + * the refinement currently applied. follow the shape of a string with a pattern of '{start}:{end}' which corresponds to the current selected item. + * For instance, when the selected item is {start: 10, end: 20}, the searchState of the widget is '10:20'. When start isn’t defined, the searchState + * of the widget is ':{end}', and the same way around when end isn’t defined. However, when neither start nor end are defined, the searchState is an empty string. + */ + currentRefinement: string; + /** a function to select a range. */ + refine: (...args: any[]) => any; + /** a function to generate a URL for the corresponding search state */ + createURL: (...args: any[]) => any; +} +export interface NumericMenuExposed { + id?: string; + /** the name of the attribute in the records */ + attribute: string; + /** List of options. With a text label, and upper and lower bounds. */ + items: Array<{ + label: string | JSX.Element; + start?: number; + end?: number; + }>; + /** the value of the item selected by default, follow the shape of a string with a pattern of '{start}:{end}'. */ + defaultRefinement?: string; + /** (...args: any[]) => any to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. */ + transformItems?: (...args: any[]) => any; +} +/** + * connectNumericMenu connector provides the logic to build a widget that will give the user the ability to select a range value for a numeric attribute. + * Ranges are defined statically. + * + * https://community.algolia.com/react-instantsearch/connectors/connectNumericMenu.html + */ +export function connectNumericMenu(stateless: React.StatelessComponent): React.ComponentClass; +export function connectNumericMenu>(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectPagination(Composed: React.ComponentType): React.ComponentClass; +export function connectPoweredBy(Composed: React.ComponentType): React.ComponentClass; +export function connectRange(Composed: React.ComponentType): React.ComponentClass; + +export interface RefinementListProvided { + /** a function to toggle a refinement */ + refine: (...args: any[]) => any; + /** a function to generate a URL for the corresponding search state */ + createURL: (...args: any[]) => any; + /** the refinement currently applied */ + currentRefinement: string[]; + /** the list of items the RefinementList can display. */ + items: Array>; + /** a function to toggle a search inside items values */ + searchForItems: (...args: any[]) => any; + /** a boolean that says if the items props contains facet values from the global search or from the search inside items. */ + isFromSearch: boolean; +} +export interface RefinementListExposed { + /** the name of the attribute in the record */ + attribute: string; + /** allow search inside values */ + searchable?: boolean; + /** How to apply the refinements. Possible values: ‘or’ or ‘and’. */ + operator?: 'or' | 'and'; + /** true if the component should display a button that will expand the number of items */ + showMore?: boolean; + /** the minimum number of displayed items */ + limit?: number; + /** the maximun number of displayed items. Only used when showMore is set to true */ + showMoreLimit?: number; + /** + * the values of the items selected by default. The searchState of this widget takes the form of a list of strings, + * which correspond to the values of all selected refinements. However, when there are no refinements selected, + * the value of the searchState is an empty string. + */ + defaultRefinement?: string[]; + /** (...args: any[]) => any to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. */ + transformItems?: (...args: any[]) => any; +} + +/** + * connectRefinementList connector provides the logic to build a widget that will give the user the ability to choose multiple values for a specific facet. + * + * https://community.algolia.com/react-instantsearch/connectors/connectRefinementList.html + */ +export function connectRefinementList(stateless: React.StatelessComponent): React.ComponentClass; +export function connectRefinementList>(ctor: React.ComponentType): + ConnectedComponentClass; + +export function connectScrollTo(Composed: React.ComponentType): React.ComponentClass; + +export interface SearchBoxProvided { + /** a function to change the current query */ + refine: (...args: any[]) => any; + /** the current query used */ + currentRefinement: string; + /** a flag that indicates if InstantSearch has detected that searches are stalled */ + isSearchStalled: boolean; +} +export interface SearchBoxExposed { + /** Provide a default value for the query */ + defaultRefinement?: string; +} +export function connectSearchBox(stateless: React.StatelessComponent): React.ComponentClass; +export function connectSearchBox>(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectSortBy(Composed: React.ComponentType): React.ComponentClass; + +export interface StateResultsProvided { + /** The search state of the instant search component. */ + searchState: SearchState; + /** + * The search results. + * In case of multiple indices: if used under , results will be those of the corresponding index + * otherwise it’ll be those of the root index + */ + searchResults: SearchResults; + /** In case of multiple indices you can retrieve all the results */ + allSearchResults: { [index: string]: SearchResults }; + /** If there is a search in progress. */ + searching: boolean; + /** Flag that indicates if React InstantSearch has detected that searches are stalled. */ + isSearchStalled: any; + /** If the search failed, the error will be logged here. */ + error: AlgoliaError; + /** If there is a search in a list in progress. */ + searchingForFacetValues: any; +} +/** + * The connectStateResults connector provides a way to access the `searchState` and the `searchResults` of InstantSearch. + * For instance this connector allows you to create results/noResults or query/noQuery pages. + * + * https://community.algolia.com/react-instantsearch/connectors/connectStateResults.html + */ +export function connectStateResults(stateless: React.StatelessComponent): React.ComponentClass; +export function connectStateResults>, TDoc>(ctor: React.ComponentType): ConnectedComponentClass>; + +export function connectStats(Composed: React.ComponentType): React.ComponentClass; +export function connectToggleRefinement(Composed: React.ComponentType): React.ComponentClass; + +export interface AlgoliaError { + stack: string; + name: string; + message: string; + debugData: any[]; + statusCode: number; +} + +type Omit = Pick>; + +export type ConnectedComponentClass + = React.ComponentClass & TExposedProps>; + +/** + * The searchState contains all widgets states. If a widget uses an attribute, + * we store it under its widget category to prevent collision. + * + * https://community.algolia.com/react-instantsearch/guide/Search_state.html + */ +export interface SearchState { + range?: { + [key: string]: { + min: number; + max: number; + } + }; + configure?: { + aroundLatLng: boolean; + [key: string]: any; + }; + refinementList?: { + [key: string]: string[] + }; + hierarchicalMenu?: { + [key: string]: string + }; + menu?: { + [key: string]: string + }; + multiRange?: { + [key: string]: string + }; + toggle?: { + [key: string]: boolean + }; + hitsPerPage?: number; + sortBy?: string; + query?: string; + page?: number; + + indices?: { + [index: string]: { + configure: { + hitsPerPage: number, + }, + } + }; +} + +/** + * The most basic possible document in an Algolia index: + * a set of string-value pairs. + */ +export interface BasicDoc { [k: string]: string; } + +/** + * The shape of the searchResults object provided + * via connectors + * https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults + */ +export interface SearchResults { + query: string; + hits: Array>; + index: string; + hitsPerPage: number; + nbHits: number; + nbPages: number; + page: number; + processingTimeMS: number; + exhaustiveNbHits: true; + disjunctiveFacets: any[]; + hierarchicalFacets: any[]; + facets: any[]; + aroundLatLng?: string; + automaticRadius?: string; +} + +/** + * All the records that match the search parameters. + * Each record is augmented with a new attribute `_highlightResult` which is an + * object keyed by attribute and contains additional properties + * https://community.algolia.com/algoliasearch-helper-js/reference.html#SearchResults#hits + */ +export type Hit = TDoc & { + objectID: string; + '_highlightResult': HighlightResult; +}; + +export type HighlightResult = + TDoc extends { [k: string]: any } ? + { [K in keyof TDoc]: HighlightResultField } : + never; + +type HighlightResultField = + TField extends Array ? + HighlightResultArray : + TField extends string ? + HighlightResultPrimitive : + HighlightResult; + +type HighlightResultArray = + TItem extends string ? + HighlightResultPrimitive[] : + Array>; + +interface HighlightResultPrimitive { + /** the value of the facet highlighted (html) */ + value: string; + /** full, partial or none depending on how the query terms match */ + matchLevel: 'none' | 'partial' | 'full'; + matchedWords: string[]; + fullyHighlighted?: boolean; +} + +// Turn off automatic exports - so we don't export internal types like Omit<> +export {}; diff --git a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx new file mode 100644 index 0000000000..62bf99e3d4 --- /dev/null +++ b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx @@ -0,0 +1,155 @@ +import * as React from 'react'; +import { + createInstantSearch, + createIndex, + createConnector, + SearchResults, + connectStateResults, + SearchBoxProvided, + connectSearchBox, + connectRefinementList +} from 'react-instantsearch-core'; + +() => { + const InstantSearch = createInstantSearch(() => ({}), {Root: 'div', props: {className: `widget`}}); + + +

+ ; +}; + +() => { + const Index = createIndex({Root: 'div', props: {className: `widget`}}); + + +
+
; +}; + +// https://community.algolia.com/react-instantsearch/guide/Custom_connectors.html +() => { + const CoolWidget = createConnector({ + displayName: 'CoolWidget', + + getProvidedProps(props, searchState) { + // Since the `queryAndPage` searchState entry isn't necessarily defined, we need + // to default its value. + const [query, page] = searchState.queryAndPage || ['', 0]; + + // Connect the underlying component to the `queryAndPage` searchState entry. + return { + query, + page, + }; + }, + + refine(props, searchState, newQuery, newPage) { + // When the underlying component calls its `refine` prop, update the searchState + // with the new query and page. + return { + // `searchState` represents the search state of *all* widgets. We need to extend it + // instead of replacing it, otherwise other widgets will lose their + // respective state. + ...searchState, + queryAndPage: [newQuery, newPage], + }; + }, + })(props => +
+ The query is {props.query}, the page is {props.page}. + {/* + Clicking on this button will update the searchState to: + { + ...otherSearchState, + query: 'algolia', + page: 20, + } + */} +
+ ); + + +
+
; +}; + +() => { + interface StateResultsProps { + searchResults: SearchResults<{ + field1: string + field2: number + field3: { compound: string } + }>; + // partial of StateResultsProvided + + additionalProp: string; + } + + const Stateless = ({ additionalProp, searchResults }: StateResultsProps) => +
+

{additionalProp}

+ {searchResults.hits.map((h) => { + // $ExpectType string + const compound = h._highlightResult.field3.compound.value; + // $ExpectType never + const field2 = h._highlightResult.field2; + return {compound}; + })} +
; + const ComposedStateless = connectStateResults(Stateless); + + ; // $ExpectError + + ; + + class MyComponent extends React.Component { + render() { + const { additionalProp, searchResults } = this.props; + return
+

{additionalProp}

+ {searchResults.hits.map((h) => { + // $ExpectType string[] + const words = h._highlightResult.field3.compound.matchedWords; + return {h.field2}: {words.join(',')}; + })} +
; + } + } + const ComposedMyComponent = connectStateResults(MyComponent); + + ; // $ExpectError + + ; +}; + +() => { + const InstantSearch = createInstantSearch( + () => null, // $ExpectError + {} + ); +}; + +// https://community.algolia.com/react-instantsearch/guide/Connectors.html +() => { + const MySearchBox = ({currentRefinement, refine}: SearchBoxProvided) => + refine(e.target.value)} + />; + + // `ConnectedSearchBox` renders a `` widget that is connected to + // the state, providing it with `currentRefinement` and `refine` props for + // reading and manipulating the current query of the search. + const ConnectedSearchBox = connectSearchBox(MySearchBox); +}; diff --git a/types/react-instantsearch-core/tsconfig.json b/types/react-instantsearch-core/tsconfig.json new file mode 100644 index 0000000000..44fe46a735 --- /dev/null +++ b/types/react-instantsearch-core/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "jsx": "react", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-instantsearch-core-tests.tsx" + ] +} diff --git a/types/react-instantsearch-core/tslint.json b/types/react-instantsearch-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch-dom/index.d.ts b/types/react-instantsearch-dom/index.d.ts new file mode 100644 index 0000000000..f1dec59118 --- /dev/null +++ b/types/react-instantsearch-dom/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for react-instantsearch 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +import { Hit, BasicDoc } from 'react-instantsearch-core'; + +// Core +export { createConnector } from 'react-instantsearch-core'; +export { HIGHLIGHT_TAGS } from 'react-instantsearch-core'; +export { translatable } from 'react-instantsearch-core'; + +// Widget +export { Configure } from 'react-instantsearch-core'; + +// Connectors +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu } from 'react-instantsearch-core'; +export { connectNumericMenu } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; + +// DOM +interface CommonWidgetProps { + /** + * All static text rendered by widgets, such as “Load more”, “Show more” are translatable using the translations prop on relevant widgets. + * This prop is a mapping of keys to translation values. Translation values can be either a String or a (...args: any[]) => any, as some take parameters. + * + * https://community.algolia.com/react-instantsearch/guide/i18n.html + */ + translations?: { [key: string]: string | ((...args: any[]) => any) }; +} + +export interface InstantSearchProps { + apiKey: string; + appId: string; + indexName: string; + + algoliaClient?: any; + searchClient?: any; + createURL?: (...args: any[]) => any; + searchState?: any; + refresh?: boolean; + onSearchStateChange?: (...args: any[]) => any; + onSearchParameters?: (...args: any[]) => any; + resultsState?: any; + root?: { + Root: string | ((...args: any[]) => any); + props: any; + }; +} +/** + * is the root component of all React InstantSearch implementations. It provides all the connected components (aka widgets) a means to interact with the searchState. + * + * https://community.algolia.com/react-instantsearch/widgets/%3CInstantSearch%3E.html + */ +export class InstantSearch extends React.Component {} +export class Index extends React.Component {} +export class Breadcrumb extends React.Component {} +export class ClearRefinements extends React.Component {} +export class CurrentRefinements extends React.Component {} +export class HierarchicalMenu extends React.Component {} +export class Highlight extends React.Component {} + +export interface HitsProps { + hitComponent?: React.ComponentType<{ hit: Hit }>; +} +/** + * Displays a list of hits. + * To configure the number of hits being shown, use the HitsPerPage widget, connectHitsPerPage connector or the Configure widget. + * + * https://community.algolia.com/react-instantsearch/widgets/Hits.html + */ +export class Hits extends React.Component> {} +export class HitsPerPage extends React.Component {} +export class InfiniteHits extends React.Component {} +export class Menu extends React.Component {} +export class MenuSelect extends React.Component {} +export class NumericMenu extends React.Component {} +export class Pagination extends React.Component {} +export class Panel extends React.Component {} +export class PoweredBy extends React.Component {} +export class RangeInput extends React.Component {} +export class RangeSlider extends React.Component {} +export class RatingMenu extends React.Component {} +export class RefinementList extends React.Component {} +export class ScrollTo extends React.Component {} + +export interface SearchBoxProps extends CommonWidgetProps { + focusShortcuts?: string[]; + autoFocus?: boolean; + defaultRefinement?: string; + searchAsYouType?: boolean; + showLoadingIndicator?: boolean; + + submit?: JSX.Element; + reset?: JSX.Element; + loadingIndicator?: JSX.Element; + + onSubmit?: (...args: any[]) => any; + onReset?: (...args: any[]) => any; +} +/** + * The SearchBox component displays a search box that lets the user search for a specific query. + * + * https://community.algolia.com/react-instantsearch/widgets/SearchBox.html + */ +export class SearchBox extends React.Component {} +export class Snippet extends React.Component {} +export class SortBy extends React.Component {} +/** + * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). + */ +export class Stats extends React.Component<{translations?: { [key: string]: (n: number, ms: number) => string }}> {} +export class ToggleRefinement extends React.Component {} diff --git a/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx new file mode 100644 index 0000000000..1e27e1d09f --- /dev/null +++ b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx @@ -0,0 +1,215 @@ +import * as React from 'react'; +import { InstantSearch, Hits, Highlight, SearchBox, RefinementList, CurrentRefinements, ClearRefinements, Pagination, Menu, Configure, Index } from 'react-instantsearch/dom'; +import { Hit, connectRefinementList, connectMenu } from 'react-instantsearch-core'; + +// DOM +// https://community.algolia.com/react-instantsearch/Getting_started.html +() => { + const App = () => ( + + + + ); + + function Search() { + return ( +
+ +
+ ); + } + + function Product({ hit }: { hit: Hit }) { + return
{hit.name}
; + } + + function Search2() { + return ( +
+ +
+ ); + } + + function Product2({ hit }: { hit: Hit }) { + return ( +
+ + + +
+ ); + } + + function Search3() { + return ( +
+ + + +
+ ); + } + + function Search4() { + return ( +
+ + + + + + +
+ ); + } +}; + +// https://community.algolia.com/react-instantsearch/guide//Highlighting_results.html +() => { + const Hit = ({ hit }: { hit: Hit }) => ( +

+ +

+ ); + + function App() { + return ( + + + + ); + } +}; + +// TODO +// () => { +// const CustomHighlight = connectHighlight( +// ({ highlight, attribute, hit, highlightProperty }) => { +// const parsedHit = highlight({ +// attribute, +// hit, +// highlightProperty: '_highlightResult' +// }); +// const highlightedHits = parsedHit.map(part => { +// if (part.isHighlighted) return {part.value}; +// return part.value; +// }); +// return
{highlightedHits}
; +// } +// ); + +// const Hit = ({ hit }: { hit: Hit }) => ( +//

+// +//

+// ); + +// function App() { +// return ( +// +// +// +// ); +// } +// }; + +// https://community.algolia.com/react-instantsearch/guide/i18n.html +() => { + const App = () => ( + + + + ); +}; + +// https://community.algolia.com/react-instantsearch/guide/Sorting_and_filtering.html +// TODO +// () => { +// const App = () => ( +// +// +// +// orderBy(items, ['label', 'count'], ['asc', 'desc']) +// } +// /> +// +// ); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Default_refinements.html +() => { + const App = () => ( + + + + + ); +}; + +// TODO +// () => { +// const VirtualMenu = connectMenu(() => null); + +// const App = () => ( +// +//
+// +// items.filter(item => item.currentRefinement !== 'Orange') +// } +// /> +// +// +// +//
+//
+// ); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Searching_in_Lists.html + +; + +// https://community.algolia.com/react-instantsearch/guide/Search_parameters.html + + + // widgets +; diff --git a/types/react-instantsearch-dom/tsconfig.json b/types/react-instantsearch-dom/tsconfig.json new file mode 100644 index 0000000000..3a8fbf89ad --- /dev/null +++ b/types/react-instantsearch-dom/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-instantsearch-dom-tests.tsx" + ] +} diff --git a/types/react-instantsearch-dom/tslint.json b/types/react-instantsearch-dom/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-dom/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch-native/index.d.ts b/types/react-instantsearch-native/index.d.ts new file mode 100644 index 0000000000..6b328de132 --- /dev/null +++ b/types/react-instantsearch-native/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for react-instantsearch-native 5.3 +// Project: https://community.algolia.com/react-instantsearch +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +// Core +export { createConnector } from 'react-instantsearch-core'; +export { HIGHLIGHT_TAGS } from 'react-instantsearch-core'; +export { translatable } from 'react-instantsearch-core'; + +// Widget +export { Configure } from 'react-instantsearch-core'; + +// Connectors +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu } from 'react-instantsearch-core'; +export { connectNumericMenu } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; + +// Native +export interface InstantSearchProps { + apiKey: string; + appId: string; + indexName: string; + + algoliaClient?: any; + searchClient?: any; + createURL?: (...args: any[]) => any; + searchState?: any; + refresh?: boolean; + onSearchStateChange?: (...args: any[]) => any; + onSearchParameters?: (...args: any[]) => any; + resultsState?: any; + root?: { + Root: string | ((...args: any[]) => any); + props: any; + }; +} +/** + * is the root component of all React InstantSearch implementations. It provides all the connected components (aka widgets) a means to interact with the searchState. + * + * https://community.algolia.com/react-instantsearch/widgets/%3CInstantSearch%3E.html + */ +export class InstantSearch extends React.Component {} + +export class Index extends React.Component {} diff --git a/types/react-instantsearch-native/react-instantsearch-native-tests.tsx b/types/react-instantsearch-native/react-instantsearch-native-tests.tsx new file mode 100644 index 0000000000..7a369b0487 --- /dev/null +++ b/types/react-instantsearch-native/react-instantsearch-native-tests.tsx @@ -0,0 +1,69 @@ +import * as React from "react"; + +import { SearchBox, Hits, Highlight, Menu } from "react-instantsearch-dom"; +import { InstantSearch, Index, connectStateResults } from 'react-instantsearch-native'; +import { values } from 'lodash'; + +// https://community.algolia.com/react-instantsearch/guide/Conditional_display.html +const App = () => ( + + + +
+ + +
+
first:
+ +
+
+
+ + +
+
second:
+ +
+
+
+ + +
+
third:
+ +
+
+
+
+
+
+); + +const IndexResults = connectStateResults( + ({ searchState, searchResults, children }) => + searchResults && searchResults.nbHits !== 0 ? ( + children as React.ReactElement + ) : ( +
+ No results has been found for {searchState.query} and index{' '} + {searchResults ? searchResults.index : ''} +
+ ) +); + +const AllResults = connectStateResults(({ allSearchResults, children }) => { + const hasResults = + allSearchResults && + values(allSearchResults).some(results => results.nbHits > 0); + + return !hasResults ? ( +
+
No results in category, products or brand
+ + + +
+ ) : ( + children as React.ReactElement + ); +}); diff --git a/types/react-instantsearch-native/tsconfig.json b/types/react-instantsearch-native/tsconfig.json new file mode 100644 index 0000000000..d4fb7501c4 --- /dev/null +++ b/types/react-instantsearch-native/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-instantsearch-native-tests.tsx" + ] +} diff --git a/types/react-instantsearch-native/tslint.json b/types/react-instantsearch-native/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-native/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch/connectors.d.ts b/types/react-instantsearch/connectors.d.ts new file mode 100644 index 0000000000..e926f79e0a --- /dev/null +++ b/types/react-instantsearch/connectors.d.ts @@ -0,0 +1,22 @@ +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch, GeoSearchExposed, GeoSearchProvided, NESW } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits, Hit } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu, MenuExposed, MenuProvided } from 'react-instantsearch-core'; +export { connectNumericMenu, NumericMenuExposed, NumericMenuProvided } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList, RefinementListExposed, RefinementListProvided } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox, SearchBoxExposed, SearchBoxProvided } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults, StateResultsProvided, SearchState, SearchResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; diff --git a/types/react-instantsearch/dom.d.ts b/types/react-instantsearch/dom.d.ts new file mode 100644 index 0000000000..ad857eaa58 --- /dev/null +++ b/types/react-instantsearch/dom.d.ts @@ -0,0 +1,27 @@ +export { InstantSearch, InstantSearchProps } from 'react-instantsearch-dom'; +export { Index } from 'react-instantsearch-dom'; +export { Breadcrumb } from 'react-instantsearch-dom'; +export { ClearRefinements } from 'react-instantsearch-dom'; +export { Configure } from 'react-instantsearch-dom'; +export { CurrentRefinements } from 'react-instantsearch-dom'; +export { HierarchicalMenu } from 'react-instantsearch-dom'; +export { Highlight } from 'react-instantsearch-dom'; +export { Hits, HitsProps } from 'react-instantsearch-dom'; +export { HitsPerPage } from 'react-instantsearch-dom'; +export { InfiniteHits } from 'react-instantsearch-dom'; +export { Menu } from 'react-instantsearch-dom'; +export { MenuSelect } from 'react-instantsearch-dom'; +export { NumericMenu } from 'react-instantsearch-dom'; +export { Pagination } from 'react-instantsearch-dom'; +export { Panel } from 'react-instantsearch-dom'; +export { PoweredBy } from 'react-instantsearch-dom'; +export { RangeInput } from 'react-instantsearch-dom'; +export { RangeSlider } from 'react-instantsearch-dom'; +export { RatingMenu } from 'react-instantsearch-dom'; +export { RefinementList } from 'react-instantsearch-dom'; +export { ScrollTo } from 'react-instantsearch-dom'; +export { SearchBox, SearchBoxProps } from 'react-instantsearch-dom'; +export { Snippet } from 'react-instantsearch-dom'; +export { SortBy } from 'react-instantsearch-dom'; +export { Stats } from 'react-instantsearch-dom'; +export { ToggleRefinement } from 'react-instantsearch-dom'; diff --git a/types/react-instantsearch/index.d.ts b/types/react-instantsearch/index.d.ts new file mode 100644 index 0000000000..3f80cf4aa3 --- /dev/null +++ b/types/react-instantsearch/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for react-instantsearch 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +export { createConnector } from 'react-instantsearch-core'; diff --git a/types/react-instantsearch/native.d.ts b/types/react-instantsearch/native.d.ts new file mode 100644 index 0000000000..ff6ff89a3f --- /dev/null +++ b/types/react-instantsearch/native.d.ts @@ -0,0 +1,3 @@ +export { InstantSearch } from 'react-instantsearch-native'; +export { Index } from 'react-instantsearch-native'; +export { Configure } from 'react-instantsearch-native'; diff --git a/types/react-instantsearch/react-instantsearch-tests.tsx b/types/react-instantsearch/react-instantsearch-tests.tsx new file mode 100644 index 0000000000..82672b7a60 --- /dev/null +++ b/types/react-instantsearch/react-instantsearch-tests.tsx @@ -0,0 +1,386 @@ +import * as React from "react"; + +import { connectMenu, connectRefinementList, connectStateResults, SearchState } from "react-instantsearch/connectors"; +import { InstantSearch, SearchBox, Index, Hits, Highlight, Menu } from "react-instantsearch/dom"; +import { orderBy, omit, values } from 'lodash'; +import { createInstantSearch } from "react-instantsearch-core"; + +// https://community.algolia.com/react-instantsearch/guide/Search_state.html +() => { + const searchState: SearchState = { + range: { + price: { + min: 20, + max: 3000 + } + }, + configure: { + aroundLatLng: true, + }, + refinementList: { + fruits: ['lemon', 'orange'] + }, + hierarchicalMenu: { + products: 'Laptops > Surface' + }, + menu: { + brands: 'Sony' + }, + multiRange: { + rank: '2:5' + }, + toggle: { + freeShipping: true + }, + hitsPerPage: 10, + sortBy: 'mostPopular', + query: 'ora', + page: 2 + }; +}; + +() => { + const searchState: SearchState = { + query: 'ora', // shared state between all indices + page: 2, // shared state between all indices + indices: { + index1: { + configure: { + hitsPerPage: 3, + }, + }, + index2: { + configure: { + hitsPerPage: 10, + }, + }, + }, + }; +}; + +// https://community.algolia.com/react-instantsearch/guide/Custom_connectors.html +// TODO +// () => { +// const CoolWidget = createConnector({ +// displayName: 'CoolWidget', + +// getProvidedProps(props, searchState) { +// // Since the `queryAndPage` searchState entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// // Connect the underlying component to the `queryAndPage` searchState entry. +// return { +// query, +// page, +// }; +// }, + +// refine(props, searchState, newQuery, newPage) { +// // When the underlying component calls its `refine` prop, update the searchState +// // with the new query and page. +// return { +// // `searchState` represents the search state of *all* widgets. We need to extend it +// // instead of replacing it, otherwise other widgets will lose their +// // respective state. +// ...searchState, +// queryAndPage: [newQuery, newPage], +// }; +// }, +// })(props => +//
+// The query is {props.query}, the page is {props.page}. +// {/* +// Clicking on this button will update the searchState to: +// { +// ...otherSearchState, +// query: 'algolia', +// page: 20, +// } +// */} +//
+// ); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine + +// getSearchParameters(searchParameters, props, searchState) { +// // Since the `queryAndPage` state entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// // When the `queryAndPage` state entry changes, update the query and page of +// // search. +// return searchParameters +// .setQuery(query) +// .setPage(page); +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters + +// getMetadata(props, searchState) { +// // Since the `queryAndPage` searchState entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// const filters = []; +// if (query !== '') { +// filters.push({ +// // Unique identifier for this filter. +// key: `queryAndPage.query`, +// // String label (or node) that should appear in the CurrentRefinements +// // component. +// label: `Query: ${query}`, +// // Describes how clearing this filter affects the InstantSearch searchState. +// // In our case, clearing the query just resets it to an empty string +// // without affecting the page. +// clear: nextSearchState => { +// return { +// ...nextSearchState, +// // Do not depend on the current `searchState` here. Since filters can be +// // cleared in batches, the `searchState` parameter is not up-to-date when +// // this method is called. +// queryAndPage: ['', nextSearchState.queryAndPage[1]], +// }; +// }, +// }); +// } + +// if (page !== 0) { +// filters.push({ +// key: `queryAndPage.page`, +// label: `Page: ${page}`, +// clear: nextSearchState => { +// return { +// ...nextSearchState, +// queryAndPage: [nextSearchState.queryAndPage[0], 0], +// }; +// }, +// }); +// } + +// return { +// // This widget manipulates the `queryAndPage` state entry. +// id: 'queryAndPage', +// filters, +// }; +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters, getMetadata + +// searchForFacetValues(props, searchState, nextRefinement) { +// return {facetName: props.attribute, query: nextRefinement}; +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters, getMetadata + +// cleanUp(props, searchState) { +// return omit('queryAndPage', searchState); +// }, +// })(Widget); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Conditional_display.html +() => { + const Content = connectStateResults( + ({ searchState }) => + searchState && searchState.query + ?
+ The query {searchState.query} exists +
+ :
No query
+ ); +}; + +() => { + const Content = connectStateResults( + ({ searchState, searchResults }) => + searchResults && searchResults.nbHits !== 0 + ?
Some results
+ :
+ No results has been found for {searchState.query} +
+ ); +}; + +() => { + const Content = connectStateResults( + ({ error }) => + error ?
Some error
:
No error
+ ); +}; + +() => { + const Content = connectStateResults( + ({ searching }) => + searching ?
We are searching
:
Search finished
+ ); +}; + +() => { + const Content = connectStateResults( + ({ searchingForFacetValues }) => + searchingForFacetValues ?
We are searching
:
Search finished
+ ); +}; + +() => { + const App = () => ( + + + +
+ + +
+
first:
+ +
+
+
+ + +
+
second:
+ +
+
+
+ + +
+
third:
+ +
+
+
+
+
+
+ ); + + const IndexResults = connectStateResults( + ({ searchState, searchResults, children }) => + searchResults && searchResults.nbHits !== 0 ? ( + children as React.ReactElement + ) : ( +
+ No results has been found for {searchState.query} and index{' '} + {searchResults ? searchResults.index : ''} +
+ ) + ); + + const AllResults = connectStateResults(({ allSearchResults, children }) => { + const hasResults = + allSearchResults && + values(allSearchResults).some(results => results.nbHits > 0); + + return !hasResults ? ( +
+
No results in category, products or brand
+ + + +
+ ) : ( + children as React.ReactElement + ); + }); +}; + +// https://github.com/algolia/react-instantsearch/blob/master/packages/react-instantsearch-dom/src/widgets/InstantSearch.js +() => { + const InstantSearch = createInstantSearch( + () => ({}), + { + Root: 'div', + props: { + className: 'ais-InstantSearch__root', + }, + } + ); + + ; +}; + +() => { + const RefinementListWithSearchBox = connectRefinementList(props => { + const values = props.items.map(item => { + const label = item._highlightResult + ? + : item.label; + + return ( +
  • + props.refine(item.value)}> + {label} {item.isRefined ? '- selected' : ''} + +
  • + ); + }); + + return ( +
    + props.searchForItems((e.target as HTMLInputElement).value)}/> +
      {values}
    +
    + ); + }); + + return ; +}; + +// https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html +() => { + const VirtualMenu = connectMenu(() => null); + const Hoodies = () => ; + + const App = () => ( + + + + + + ); +}; diff --git a/types/react-instantsearch/tsconfig.json b/types/react-instantsearch/tsconfig.json new file mode 100644 index 0000000000..9782cbd17e --- /dev/null +++ b/types/react-instantsearch/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "experimentalDecorators": true, + "jsx": "react", + "lib": ["es6", "dom"], + "module": "commonjs", + "noEmit": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "forceConsistentCasingInFileNames": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "connectors.d.ts", + "dom.d.ts", + "native.d.ts", + "react-instantsearch-tests.tsx" + ] +} diff --git a/types/react-instantsearch/tslint.json b/types/react-instantsearch/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/react-instantsearch/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/react-jsonschema-form/index.d.ts b/types/react-jsonschema-form/index.d.ts index 63a4de1b89..7e1e1df7e3 100644 --- a/types/react-jsonschema-form/index.d.ts +++ b/types/react-jsonschema-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-jsonschema-form 1.0.0 +// Type definitions for react-jsonschema-form 1.0.1 // Project: https://github.com/mozilla-services/react-jsonschema-form // Definitions by: Dan Fox // Ivan Jiang @@ -6,6 +6,7 @@ // Philippe Bourdages // Lucian Buzzo // Sylvain Thénault +// Sebastian Busch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -68,7 +69,12 @@ declare module "react-jsonschema-form" { [key: string]: FieldId; }; - export interface WidgetProps extends React.HTMLAttributes { + export interface WidgetProps extends Pick< + React.HTMLAttributes, + Exclude< + keyof React.HTMLAttributes, + "onBlur"|"onFocus"> + > { id: string; schema: JSONSchema6; value: any; @@ -79,6 +85,8 @@ declare module "react-jsonschema-form" { onChange: (value: any) => void; options: object; formContext: any; + onBlur: (id: string, value: string) => void; + onFocus: (id: string, value: string) => void; } export type Widget = diff --git a/types/react-jsonschema-form/react-jsonschema-form-tests.tsx b/types/react-jsonschema-form/react-jsonschema-form-tests.tsx index 0bb6715372..90116127fd 100644 --- a/types/react-jsonschema-form/react-jsonschema-form-tests.tsx +++ b/types/react-jsonschema-form/react-jsonschema-form-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Form, { UiSchema, ErrorListProps } from "react-jsonschema-form"; +import Form, { UiSchema, ErrorListProps, WidgetProps } from "react-jsonschema-form"; import { JSONSchema6 } from "json-schema"; // example taken from the react-jsonschema-form playground: @@ -108,3 +108,9 @@ export class Example extends React.Component { ); } } + +export const CustomWidget: React.SFC = (props) => + props.onFocus('id', 'value')} + onBlur={()=> props.onFocus('id', 'value')} + /> diff --git a/types/react-native-calendars/index.d.ts b/types/react-native-calendars/index.d.ts index 647e64c0f2..20adae432a 100644 --- a/types/react-native-calendars/index.d.ts +++ b/types/react-native-calendars/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/wix/react-native-calendars#readme // Definitions by: Tyler Zhang // David Noreña +// Fabian Meul // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -23,6 +24,10 @@ export interface CalendarDot { selectedDotColor?: string; } +export interface CalendarThemeIdStyle { + [themeId: string]: ViewStyle; +} + export interface CalendarTheme { arrowColor?: string; backgroundColor?: string; @@ -43,6 +48,17 @@ export interface CalendarTheme { textMonthFontSize?: number; textSectionTitleColor?: string; todayTextColor?: string; + + // Theme ID's to style for + "stylesheet.calendar.header"?: CalendarThemeIdStyle; + "stylesheet.calendar.main"?: CalendarThemeIdStyle; + "stylesheet.calendar-list.main"?: CalendarThemeIdStyle; + "stylesheet.agenda.main"?: CalendarThemeIdStyle; + "stylesheet.agenda.list"?: CalendarThemeIdStyle; + "stylesheet.day.basic"?: CalendarThemeIdStyle; + "stylesheet.day.single"?: CalendarThemeIdStyle; + "stylesheet.day.multiDot"?: CalendarThemeIdStyle; + "stylesheet.day.period"?: CalendarThemeIdStyle; } export type DateCallbackHandler = (date: DateObject) => void; @@ -319,6 +335,11 @@ export interface CalendarListBaseProps extends CalendarBaseProps { * Enable or disable vertical scroll indicator. Default = false */ showScrollIndicator?: boolean; + + /** + * Initially selected day + */ + selected?: string; } export class CalendarList extends React.Component { } diff --git a/types/react-native-google-signin/index.d.ts b/types/react-native-google-signin/index.d.ts index a114a06882..54e19715e1 100644 --- a/types/react-native-google-signin/index.d.ts +++ b/types/react-native-google-signin/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Jacob Froman // Michele Bombardi // Christian Chown +// Eric Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -53,6 +54,11 @@ export interface ConfigureParams { */ webClientId?: string; + /** + * If you want to specify the client ID of type iOS + */ + iosClientId?: string; + /** * Must be true if you wish to access user APIs on behalf of the user from * your own server diff --git a/types/react-native-popup-dialog/index.d.ts b/types/react-native-popup-dialog/index.d.ts index 3ff12802f4..dcf6e5cb1c 100644 --- a/types/react-native-popup-dialog/index.d.ts +++ b/types/react-native-popup-dialog/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-popup-dialog 1.0 +// Type definitions for react-native-popup-dialog 0.16 // Project: https://github.com/jacklam718/react-native-popup-dialog/blob/master/README.md // Definitions by: Paito Anderson // connectdotz @@ -55,7 +55,7 @@ export interface PopupDialogProps { dismissOnTouchOutside?: boolean; dismissOnHardwareBackPress?: boolean; haveOverlay?: boolean; - show?: boolean; + visible?: boolean; onShown?: () => void; onDismissed?: () => void; actions?: any[]; diff --git a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx index 379d4fd788..95bfa66f4e 100644 --- a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx +++ b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx @@ -72,7 +72,7 @@ class Test extends React.Component { dismissOnTouchOutside={false} dismissOnHardwareBackPress={false} haveOverlay={true} - show={true} + visible={true} onShown={() => { console.log('onShown'); }} onDismissed={() => { console.log('onDismissed'); }} /> diff --git a/types/react-native-status-bar-height/index.d.ts b/types/react-native-status-bar-height/index.d.ts new file mode 100644 index 0000000000..6b24c8a9a2 --- /dev/null +++ b/types/react-native-status-bar-height/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for react-native-status-bar-height 2.1 +// Project: https://github.com/ovr/react-native-status-bar-height#readme +// Definitions by: Tom Spencer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function getStatusBarHeight(skipAndroid?: boolean): number; diff --git a/types/react-native-status-bar-height/react-native-status-bar-height-tests.ts b/types/react-native-status-bar-height/react-native-status-bar-height-tests.ts new file mode 100644 index 0000000000..a31cb57259 --- /dev/null +++ b/types/react-native-status-bar-height/react-native-status-bar-height-tests.ts @@ -0,0 +1,5 @@ +import { getStatusBarHeight } from 'react-native-status-bar-height'; + +getStatusBarHeight(); // $ExpectType number +getStatusBarHeight(false); // $ExpectType number +getStatusBarHeight(true); // $ExpectType number diff --git a/types/react-native-status-bar-height/tsconfig.json b/types/react-native-status-bar-height/tsconfig.json new file mode 100644 index 0000000000..13c7ab69f5 --- /dev/null +++ b/types/react-native-status-bar-height/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", + "react-native-status-bar-height-tests.ts" + ] +} diff --git a/types/react-native-status-bar-height/tslint.json b/types/react-native-status-bar-height/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-status-bar-height/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-uuid-generator/index.d.ts b/types/react-native-uuid-generator/index.d.ts new file mode 100644 index 0000000000..ad5cb96bec --- /dev/null +++ b/types/react-native-uuid-generator/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-native-uuid-generator 4.0 +// Project: https://github.com/Traviskn/react-native-uuid-generator#readme +// Definitions by: burtek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace UUIDGenerator { + function getRandomUUID(): Promise; + function getRandomUUID(callback: (uuid: string) => void): void; +} + +export default UUIDGenerator; diff --git a/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts new file mode 100644 index 0000000000..b65f0ef410 --- /dev/null +++ b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts @@ -0,0 +1,5 @@ +import UUIDGenerator from 'react-native-uuid-generator'; + +UUIDGenerator.getRandomUUID().then((uuid: string) => { }).catch((error: any) => { }); + +UUIDGenerator.getRandomUUID((uuid: string) => { }); diff --git a/types/react-native-uuid-generator/tsconfig.json b/types/react-native-uuid-generator/tsconfig.json new file mode 100644 index 0000000000..30c1f52249 --- /dev/null +++ b/types/react-native-uuid-generator/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", + "react-native-uuid-generator-tests.ts" + ] +} diff --git a/types/react-native-uuid-generator/tslint.json b/types/react-native-uuid-generator/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-uuid-generator/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 1bdf43bc35..1572c94e25 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-navigation 2.0 +// Type definitions for react-navigation 2.13 // Project: https://github.com/react-navigation/react-navigation // Definitions by: Huhuanming // mhcgrq @@ -25,6 +25,7 @@ // Denis Frezzato // Mickael Wegerich // Max Davidson +// Jason Killian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -518,7 +519,7 @@ interface NavigationTabScreenOptionsBase { tabBarIcon?: | React.ReactElement | (( - options: { tintColor: string | null; focused: boolean } + options: { tintColor: string | null; focused: boolean; horizontal: boolean } ) => React.ReactElement | null); tabBarLabel?: | string diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 47dd7baa0e..1b6bff2586 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -179,7 +179,8 @@ const tabNavigatorConfig: TabNavigatorConfig = { tabBarComponent: TabBarTop, tabBarOptions: { activeBackgroundColor: "blue" }, navigationOptions: () => ({ - tabBarOnPress: ({ scene, jumpToIndex }) => jumpToIndex(scene.index) + tabBarOnPress: ({ scene, jumpToIndex }) => jumpToIndex(scene.index), + tabBarIcon: ({ horizontal }) => , }) }; diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index ca81b0d908..2e1cfb902b 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for React Router 4.0 +// Type definitions for React Router 4.4 // Project: https://github.com/ReactTraining/react-router // Definitions by: Sergey Buturlakin // Yuichi Murata @@ -18,6 +18,7 @@ // Rahul Raina // Maksim Sharipov // Duong Tran +// Ben Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -76,7 +77,7 @@ export interface RouteProps { component?: React.ComponentType> | React.ComponentType; render?: ((props: RouteComponentProps) => React.ReactNode); children?: ((props: RouteComponentProps) => React.ReactNode) | React.ReactNode; - path?: string; + path?: string | string[]; exact?: boolean; sensitive?: boolean; strict?: boolean; diff --git a/types/react-router/test/Switch.tsx b/types/react-router/test/Switch.tsx index fe959504ce..03d65125f0 100644 --- a/types/react-router/test/Switch.tsx +++ b/types/react-router/test/Switch.tsx @@ -4,6 +4,7 @@ import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom'; const Home = () =>

    Home

    ; const About = () =>

    About

    ; const User = () =>

    User

    ; +const Contact = () =>

    Contact

    ; const SwitchTest = () => ( @@ -12,7 +13,8 @@ const SwitchTest = () => ( {[ , - + , + ]} diff --git a/types/react-sortable-tree/index.d.ts b/types/react-sortable-tree/index.d.ts index 2127d0ffef..bcc6596ee6 100644 --- a/types/react-sortable-tree/index.d.ts +++ b/types/react-sortable-tree/index.d.ts @@ -158,7 +158,7 @@ export interface TreeRendererProps { export interface ThemeProps { style?: { [index: string]: any }; innerStyle?: { [index: string]: any }; - reactVirtualizedListProps?: ListProps; + reactVirtualizedListProps?: Partial; scaffoldBlockPxWidth?: number; slideRegionSize?: number; rowHeight?: ((info: Index) => number) | number; @@ -184,7 +184,7 @@ export interface ReactSortableTreeProps { onVisibilityToggle?(data: OnVisibilityToggleData): void; canDrag?: ((data: ExtendedNodeData) => boolean) | boolean; canDrop?(data: OnDragPreviousAndNextLocation & NodeData): boolean; - reactVirtualizedListProps?: ListProps; + reactVirtualizedListProps?: Partial; rowHeight?: ((info: Index) => number) | number; slideRegionSize?: number; scaffoldBlockPxWidth?: number; diff --git a/types/react-stripe-elements/index.d.ts b/types/react-stripe-elements/index.d.ts index 32a94b0639..534bfde9ec 100644 --- a/types/react-stripe-elements/index.d.ts +++ b/types/react-stripe-elements/index.d.ts @@ -12,12 +12,12 @@ import * as React from 'react'; export namespace ReactStripeElements { - import ElementChangeResponse = stripe.elements.ElementChangeResponse; - import ElementsOptions = stripe.elements.ElementsOptions; - import TokenOptions = stripe.TokenOptions; - import TokenResponse = stripe.TokenResponse; - import SourceResponse = stripe.SourceResponse; - import SourceOptions = stripe.SourceOptions; + type ElementChangeResponse = stripe.elements.ElementChangeResponse; + type ElementsOptions = stripe.elements.ElementsOptions; + type TokenOptions = stripe.TokenOptions; + type TokenResponse = stripe.TokenResponse; + type SourceResponse = stripe.SourceResponse; + type SourceOptions = stripe.SourceOptions; /** * There's a bug in @types/stripe which defines the property as diff --git a/types/react-syntax-highlighter/index.d.ts b/types/react-syntax-highlighter/index.d.ts index 8bfd8e3756..c631dea9f7 100644 --- a/types/react-syntax-highlighter/index.d.ts +++ b/types/react-syntax-highlighter/index.d.ts @@ -5,11 +5,14 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +type lineTagPropsFunction = (lineNumber: number) => React.DOMAttributes + interface SyntaxHighlighterProps { language?: string; style?: any; customStyle?: any; - codeTagProps?: HTMLElement; + lineProps?: lineTagPropsFunction | React.DOMAttributes + codeTagProps?: React.DOMAttributes; useInlineStyles?: boolean; showLineNumbers?: boolean; startingLineNumber?: number; diff --git a/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx b/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx index 2abddb4a49..c516d9f610 100644 --- a/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx +++ b/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx @@ -61,3 +61,84 @@ function primsLightHighlighter(): JSX.Element { ) } + +function codeTagProps() { + const codeString: string = `class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + public version(): string { + return this.version; + } + } + `; + + const codeTagProps = { + className: 'some-classname', + style: { + opacity: 0, + }, + onMouseOver: (event: React.MouseEvent) => "foo", + } + + return ( + + ) +} + +function linePropsObject() { + const codeString: string = `class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + public version(): string { + return this.version; + } + } + `; + + const lineProps = { + otherProp: 'otherProp', + className: 'some-classname', + style: { + opacity: 0, + }, + onMouseOver: (event: React.MouseEvent) => "foo" + } + + return ( + + ) +} + +function lineTagPropsFunction() { + const codeString: string = `class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + public version(): string { + return this.version; + } + } + `; + + const lineProps = (lineNumber: number) => ({ + otherProp: 'otherProp', + className: 'some-classname', + style: { + opacity: 0, + }, + onMouseOver: (event: React.MouseEvent) => lineNumber * 5 + }) + + return ( + + ) +} + diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index ca7981a6f8..0d03604ae9 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -1,13 +1,13 @@ // Type definitions for react-table 6.7 // Project: https://github.com/react-tools/react-table -// Definitions by: Roy Xue , Pavel Sakalo , Krzysztof Porębski +// Definitions by: Roy Xue , Pavel Sakalo , Krzysztof Porębski , Andy S // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; export type ReactTableFunction = (value?: any) => void; -export type AccessorFunction = (row: object) => any; -export type Accessor = string | string[] | object | AccessorFunction; +export type AccessorFunction = (row: D) => any; +export type Accessor = string | string[] | AccessorFunction; export type Aggregator = (values: any, rows: any) => any; export type TableCellRenderer = ((data: any, column: any) => React.ReactNode) | React.ReactNode; export type FilterRender = (params: { column: Column, filter: any, onChange: ReactTableFunction, key?: string }) => React.ReactElement; @@ -46,7 +46,7 @@ export interface SortingRule { desc?: true; } -export interface TableProps extends +export interface TableProps extends Partial, Partial, Partial, @@ -54,7 +54,7 @@ export interface TableProps extends Partial, Partial { /** Default: [] */ - data: any[]; + data: D[]; /** Default: false */ loading: boolean; @@ -164,7 +164,7 @@ export interface TableProps extends column: Partial; /** Array of all Available Columns */ - columns?: Column[]; + columns?: Array>; /** Expander defaults. */ expanderDefaults: Partial; @@ -180,9 +180,9 @@ export interface TableProps extends /** Control callback for functional rendering */ children: ( - state: FinalState, + state: FinalState, makeTable: () => React.ReactElement, - instance: Instance + instance: Instance ) => React.ReactNode; } @@ -548,7 +548,7 @@ export interface PivotDefaults { render: TableCellRenderer; } -export interface Column extends +export interface Column extends Partial, Partial, Partial, @@ -562,7 +562,7 @@ export interface Column extends * @example {"a": {"b": {"c": $}}} * @example (row) => row.propertyName */ - accessor?: Accessor; + accessor?: Accessor; /** * Conditional - A unique ID is required if the accessor is not a string or if you would like to override the column name used in server-side calls @@ -598,7 +598,7 @@ export interface Column extends expander?: boolean; /** Header Groups only */ - columns?: any[]; + columns?: Array>; /** * Turns this column into a special column for specifying pivot position in your column definitions. @@ -608,12 +608,12 @@ export interface Column extends pivot?: boolean; } -export interface ColumnRenderProps { +export interface ColumnRenderProps { /** Sorted data. */ - data: any[]; + data: D[]; /** The column. */ - column: Column; + column: Column; } export interface RowRenderProps extends Partial { @@ -662,7 +662,7 @@ export interface RowInfo { original: any; } -export interface FinalState extends TableProps { +export interface FinalState extends TableProps { frozen: boolean; startRow: number; endRow: number; @@ -674,21 +674,21 @@ export interface FinalState extends TableProps { canNext: boolean; rowMinWidth: number; - allVisibleColumns: Column[]; - allDecoratedColumns: Column[]; + allVisibleColumns: Array>; + allDecoratedColumns: Array>; resolvedData: DerivedDataObject[]; sortedData: DerivedDataObject[]; headerGroups: any[]; } export const ReactTableDefaults: TableProps; -export default class ReactTable extends React.Component> { } +export default class ReactTable extends React.Component>> { } -export interface Instance extends ReactTable { +export interface Instance extends ReactTable { context: any; - props: Partial; + props: Partial>; refs: any; - state: FinalState; + state: FinalState; filterColumn(...props: any[]): any; filterData(...props: any[]): any; fireFetchData(...props: any[]): any; diff --git a/types/react-table/react-table-tests.tsx b/types/react-table/react-table-tests.tsx index b8380125b3..ca63bdd67c 100644 --- a/types/react-table/react-table-tests.tsx +++ b/types/react-table/react-table-tests.tsx @@ -5,7 +5,15 @@ import * as ReactDOM from 'react-dom'; import ReactTable, { Column, FinalState, Instance } from "react-table"; import "react-table/react-table.css"; -const columns: Column[] = [ +interface Data { + firstName: string; + lastName: string; + age: number; + visits: number; + progress: number; +} + +const columns: Array> = [ { Header: "Name", columns: [ @@ -16,7 +24,7 @@ const columns: Column[] = [ { Header: "Info", columns: [ - { Header: "Age", accessor: "age" }, + { Header: "Age", accessor: (data: Data) => data.age }, { Header: "Status", accessor: "status" } ] }, @@ -29,7 +37,7 @@ const columns: Column[] = [ ]; const Component = (props: {}) => { - const data = [ + const data: Data[] = [ { firstName: "plastic", lastName: "leather", age: 1, visits: 87, progress: 53 }, { firstName: "eggs", lastName: "quartz", age: 13, visits: 78, progress: 82 }, { firstName: "wash", lastName: "wrench", age: 29, visits: 75, progress: 49 }, @@ -156,9 +164,9 @@ const Component = (props: {}) => { }} > {( - state: FinalState, + state: FinalState, makeTable: () => React.ReactChild, - instance: Instance + instance: Instance ) => { return (
    // 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/redux-orm/index.d.ts b/types/redux-orm/index.d.ts index 31fffa1273..644d86aea1 100644 --- a/types/redux-orm/index.d.ts +++ b/types/redux-orm/index.d.ts @@ -95,7 +95,7 @@ export class Model { static hasId(id: string): boolean; static _findDatabaseRows(lookupObj: object): any; // TODO static get(lookupObj: object): ModelWithFields; - static reducer(session: SessionWithModels, action: any): any; + static reducer(action: any, modelClass: typeof Model, session: SessionWithModels): any; readonly ref: Fields & Additional & ORMId; diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 60e24b7692..c18f97554f 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for request 2.47 +// Type definitions for request 2.48 // Project: https://github.com/request/request // Definitions by: Carlos Ballesteros Velasco , // bonnici , @@ -8,6 +8,7 @@ // Jon Stevens , // Matt R. Wilson // Jose Colella +// Marek Urbanowicz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -24,6 +25,7 @@ import FormData = require('form-data'); import net = require('net'); import tough = require('tough-cookie'); import { Url } from 'url'; +import { SecureContextOptions } from 'tls'; declare namespace request { interface RequestAPI { @@ -132,7 +134,7 @@ declare namespace request { jsonReplacer?: (key: string, value: any) => any; multipart?: RequestPart[] | Multipart; agent?: http.Agent | https.Agent; - agentOptions?: any; + agentOptions?: http.AgentOptions | https.AgentOptions; agentClass?: any; forever?: any; host?: string; diff --git a/types/request/request-tests.ts b/types/request/request-tests.ts index c2c377fcbd..1d13dcbaaa 100644 --- a/types/request/request-tests.ts +++ b/types/request/request-tests.ts @@ -550,7 +550,9 @@ request.get(options); request.get({ url: 'https://api.some-server.com/', agentOptions: { - secureProtocol: 'SSLv3_method' + secureProtocol: 'SSLv3_method', + maxCachedSessions: 3, + keepAlive: true, } }); @@ -626,25 +628,26 @@ request.get('http://10.255.255.1', {timeout: 1500}, (err) => { }); const rand = Math.floor(Math.random() * 100000000).toString(); - request( - { method: 'PUT' - , uri: 'http://mikeal.iriscouch.com/testjs/' + rand - , multipart: - [ { headers: { 'content-type': 'application/json' } - , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, content_type: 'text/plain' }}}) - } - , { body: 'I am an attachment' } - ] + +request( +{ method: 'PUT' +, uri: 'http://mikeal.iriscouch.com/testjs/' + rand +, multipart: + [ { headers: { 'content-type': 'application/json' } + , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, content_type: 'text/plain' }}}) } - , (error, response, body) => { - if (response.statusCode === 201) { - console.log('document saved as: http://mikeal.iriscouch.com/testjs/' + rand); - } else { - console.log('error: ' + response.statusCode); - console.log(body); - } + , { body: 'I am an attachment' } + ] +} +, (error, response, body) => { + if (response.statusCode === 201) { + console.log('document saved as: http://mikeal.iriscouch.com/testjs/' + rand); + } else { + console.log('error: ' + response.statusCode); + console.log(body); } - ); +} +); request( { method: 'GET' diff --git a/types/restify-plugins/index.d.ts b/types/restify-plugins/index.d.ts index 4f495ce593..8ac287a542 100644 --- a/types/restify-plugins/index.d.ts +++ b/types/restify-plugins/index.d.ts @@ -265,7 +265,7 @@ export interface QueryParserOptions { } /** - * Parses URL query paramters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) + * Parses URL query parameter into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) */ export function queryParser(options?: QueryParserOptions): RequestHandler; diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index ee757e8a2f..a035a87396 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -1343,7 +1343,7 @@ export namespace plugins { } /** - * Parses URL query paramters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) + * Parses URL query parameters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) */ function queryParser(options?: QueryParserOptions): RequestHandler; diff --git a/types/restify/v5/index.d.ts b/types/restify/v5/index.d.ts index bacea67cab..11664c60cf 100644 --- a/types/restify/v5/index.d.ts +++ b/types/restify/v5/index.d.ts @@ -1138,7 +1138,7 @@ export namespace plugins { } /** - * Parses URL query paramters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) + * Parses URL query parameters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) */ function queryParser(options?: QueryParserOptions): RequestHandler; diff --git a/types/scheduler/index.d.ts b/types/scheduler/index.d.ts new file mode 100644 index 0000000000..9df4054e8e --- /dev/null +++ b/types/scheduler/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for scheduler 0.10 +// Project: https://reactjs.org/ +// Definitions by: Nathan Bierema +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export interface Deadline { + timeRemaining(): number; + didTimeout: boolean; +} +export type FrameCallbackType = (deadline: Deadline) => FrameCallbackType | void; +export interface CallbackNode { + callback: FrameCallbackType; + priorityLevel: number; + expirationTime: number; + next: CallbackNode | null; + prev: CallbackNode | null; +} + +export const unstable_ImmediatePriority = 1; +export const unstable_UserBlockingPriority = 2; +export const unstable_NormalPriority = 3; +export const unstable_IdlePriority = 4; +export function unstable_runWithPriority(priorityLevel: number, eventHandler: () => T): T | undefined; +export function unstable_scheduleCallback(callback: FrameCallbackType, deprecated_options?: { timeout: number}): CallbackNode; +export function unstable_cancelCallback(callbackNode: CallbackNode): void; +export function unstable_wrapCallback(callback: FrameCallbackType): () => FrameCallbackType | undefined; +export function unstable_getCurrentPriorityLevel(): number; +export function unstable_now(): number; diff --git a/types/scheduler/scheduler-tests.ts b/types/scheduler/scheduler-tests.ts new file mode 100644 index 0000000000..84c35fb5b7 --- /dev/null +++ b/types/scheduler/scheduler-tests.ts @@ -0,0 +1,8 @@ +import { unstable_scheduleCallback, unstable_cancelCallback, unstable_now } from 'scheduler'; + +// $ExpectType CallbackNode +const callbackNode = unstable_scheduleCallback(() => {}, { timeout: 100 }); +unstable_cancelCallback(callbackNode); + +// $ExpectType number +unstable_now(); diff --git a/types/scheduler/tsconfig.json b/types/scheduler/tsconfig.json new file mode 100644 index 0000000000..b6c5c6021a --- /dev/null +++ b/types/scheduler/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", + "scheduler-tests.ts" + ] +} diff --git a/types/scheduler/tslint.json b/types/scheduler/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/scheduler/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/scroll-into-view/index.d.ts b/types/scroll-into-view/index.d.ts index cb2e187147..1d53597c27 100644 --- a/types/scroll-into-view/index.d.ts +++ b/types/scroll-into-view/index.d.ts @@ -20,8 +20,8 @@ declare module __ScrollIntoView { } /** type will be 'complete' if the scroll completed or 'canceled' if the current scroll was canceled by a new scroll */ - type callbackParamterType = "complete" | "canceled" - type Callback = (type: callbackParamterType) => void + type callbackParameterType = "complete" | "canceled" + type Callback = (type: callbackParameterType) => void interface ScrollIntoView { (target: HTMLElement, callback?: __ScrollIntoView.Callback) : void diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index 21474f3a6d..cc115c6d55 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -90,7 +90,7 @@ declare namespace SeamlessImmutable { flatMap(mapFunction: (item: T[0]) => TTarget): Immutable; } - type BaseImmutable = (T extends any[] ? ImmutableArrayMixin : ImmutableObjectMixin) & T; + type BaseImmutable = T extends any[] ? ImmutableArrayMixin : ImmutableObjectMixin; type Immutable = { readonly [P in keyof T]: T[P] extends object ? Immutable : T[P] diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 5f1c8d1d1d..f80d5acc40 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -14,6 +14,7 @@ // Todd Bealmear // Nick Schultz // Thomas Breleur +// Antoine Boisadam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -138,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. @@ -147,7 +148,7 @@ declare namespace sequelize { ( values?: TAttributes, options?: BelongsToCreateAssociationMixinOptions | CreateOptions | BelongsToSetAssociationMixinOptions - ): Promise; + ): Promise; } /** @@ -5698,6 +5699,13 @@ declare namespace sequelize { * Pass object to limit set of aliased operators or false to disable completely. */ operatorsAliases?: boolean | OperatorsAliases; + + /** + * Set to `true` to enable connecting over SSL. + * + * Defaults to undefined + */ + ssl?: boolean; } /** 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/serialport/index.d.ts b/types/serialport/index.d.ts index 2f5f8fc55d..14ded3b6e3 100644 --- a/types/serialport/index.d.ts +++ b/types/serialport/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for serialport 6.0 +// Type definitions for serialport 7.0 // Project: https://github.com/EmergingTechnologyAdvisors/node-serialport // Definitions by: Jeremy Foster // Andrew Pearson @@ -40,7 +40,7 @@ declare class SerialPort extends Stream.Duplex { static Binding: SerialPort.BaseBinding; - static list(): Promise; + static list(callback?: SerialPort.ListCallback): Promise; } declare namespace SerialPort { @@ -77,6 +77,16 @@ declare namespace SerialPort { dsr?: boolean; dtr?: boolean; rts?: boolean; + } + + interface PortInfo { + comName: string; + manufacturer?: string; + serialNumber?: string; + pnpId?: string; + locationId?: string; + productId?: string; + vendorId?: string; } namespace parsers { @@ -119,7 +129,7 @@ declare namespace SerialPort { get(): Promise; flush(): Promise; drain(): Promise; - static list(): Promise; + static list(): Promise; } } diff --git a/types/serialport/serialport-tests.ts b/types/serialport/serialport-tests.ts index 7b540c5e12..16cf2b6a70 100644 --- a/types/serialport/serialport-tests.ts +++ b/types/serialport/serialport-tests.ts @@ -126,3 +126,14 @@ function test_properties() { const isOpen: boolean = port.isOpen; const path: string = port.path; } + +function test_list_ports_promise() { + const ports = SerialPort + .list() + .then((ports: any) => {}) + .catch((err: Error) => {}); +} + +function test_list_ports_callback() { + const ports = SerialPort.list((error: Error, port: any[]) => {}); +} diff --git a/types/serialport/v6/index.d.ts b/types/serialport/v6/index.d.ts new file mode 100644 index 0000000000..2f5f8fc55d --- /dev/null +++ b/types/serialport/v6/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for serialport 6.0 +// Project: https://github.com/EmergingTechnologyAdvisors/node-serialport +// Definitions by: Jeremy Foster +// Andrew Pearson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as Stream from 'stream'; + +declare class SerialPort extends Stream.Duplex { + constructor(path: string, callback?: SerialPort.ErrorCallback); + constructor(path: string, options?: SerialPort.OpenOptions, callback?: SerialPort.ErrorCallback); + + readonly baudRate: number; + readonly binding: SerialPort.BaseBinding; + readonly isOpen: boolean; + readonly path: string; + + open(callback?: SerialPort.ErrorCallback): void; + update(options: SerialPort.UpdateOptions, callback?: SerialPort.ErrorCallback): void; + + write(data: string| number[] | Buffer, callback?: (error: any, bytesWritten: number) => void): boolean; + write(buffer: string| number[] | Buffer, encoding?: 'ascii'|'utf8'|'utf16le'|'ucs2'|'base64'|'binary'|'hex', callback?: (error: any, bytesWritten: number) => void): boolean; + + read(size?: number): string | Buffer | null; + + close(callback?: (error: Error) => void): void; + + set(options: SerialPort.SetOptions, callback?: SerialPort.ErrorCallback): void; + get(callback?: SerialPort.ModemBitsCallback): void; + + flush(callback?: SerialPort.ErrorCallback): void; + drain(callback?: SerialPort.ErrorCallback): void; + + pause(): this; + resume(): this; + + on(event: string, callback: (data?: any) => void): this; + + static Binding: SerialPort.BaseBinding; + + static list(): Promise; +} + +declare namespace SerialPort { + // Callbacks Type Defs + type ErrorCallback = (error: Error) => void; + type ModemBitsCallback = (error: Error, status: {cts: boolean, dsr: boolean, dcd: boolean }) => void; + type ListCallback = (error: Error, port: any[]) => void; + + // Options Type Defs + interface OpenOptions { + autoOpen?: boolean; + baudRate?: 115200|57600|38400|19200|9600|4800|2400|1800|1200|600|300|200|150|134|110|75|50|number; + dataBits?: 8|7|6|5; + highWaterMark?: number; + lock?: boolean; + stopBits?: 1|2; + parity?: 'none'|'even'|'mark'|'odd'|'space'; + rtscts?: boolean; + xon?: boolean; + xoff?: boolean; + xany?: boolean; + binding?: BaseBinding; + bindingOptions?: { + vmin?: number; + vtime?: number; + }; + } + interface UpdateOptions { + baudRate?: 115200|57600|38400|19200|9600|4800|2400|1800|1200|600|300|200|150|134|110|75|50|number; + } + interface SetOptions { + brk?: boolean; + cts?: boolean; + dsr?: boolean; + dtr?: boolean; + rts?: boolean; + } + + namespace parsers { + class ByteLength extends Stream.Transform { + constructor(options: {length: number}); + } + class CCTalk extends Stream.Transform { + constructor(); + } + class Delimiter extends Stream.Transform { + constructor(options: {delimiter: string | Buffer | number[], includeDelimiter?: boolean}); + } + class Readline extends Delimiter { + constructor(options: {delimiter: string | Buffer | number[], encoding?: 'ascii'|'utf8'|'utf16le'|'ucs2'|'base64'|'binary'|'hex'}); + } + class Ready extends Stream.Transform { + constructor(options: {data: string | Buffer | number[]}); + } + class Regex extends Stream.Transform { + constructor(options: {regex: RegExp}); + } + } + + // Binding Type Defs + type win32Binding = BaseBinding; + type darwinBinding = BaseBinding; + type linuxBinding = BaseBinding; + + // Binding Type Def + class BaseBinding { + constructor(options: any); + + open(path: string, options: OpenOptions): Promise; + close(): Promise; + + read(data: Buffer, offset: number, length: number): Promise; + write(data: Buffer): Promise; + update(options?: UpdateOptions): Promise; + set(options?: SetOptions): Promise; + get(): Promise; + flush(): Promise; + drain(): Promise; + static list(): Promise; + } +} + +export = SerialPort; diff --git a/types/serialport/v6/serialport-tests.ts b/types/serialport/v6/serialport-tests.ts new file mode 100644 index 0000000000..7b540c5e12 --- /dev/null +++ b/types/serialport/v6/serialport-tests.ts @@ -0,0 +1,128 @@ +// Tests taken from documentation samples. + +import SerialPort = require('serialport'); + +function test_basic_connect() { + const port = new SerialPort(''); +} + +function test_connect_config() { + const port1 = new SerialPort('', { + }, (error: Error) => {}); + + const port4 = new SerialPort('', { + autoOpen: false, + lock: false, + baudRate: 115200, + dataBits: 5, + stopBits: 2, + parity: 'odd', + rtscts: true, + xon: true, + xoff: true, + highWaterMark: 1024, + bindingOptions: { + vmin: 1, + vtime: 1 + } + }, (error: Error) => {}); +} + +function test_open() { + const port = new SerialPort(''); + port.open(() => {}); +} + +function test_update() { + const port = new SerialPort(''); + port.update({baudRate: 57600}); +} + +function test_write() { + const port = new SerialPort(''); + + port.write('test', (error: Error) => {}); + port.write('test', 'utf8', (error: Error) => {}); +} + +function test_read() { + const port = new SerialPort(''); + + const data = port.read(8); +} + +function test_close() { + const port = new SerialPort(''); + + port.close((error: Error) => {}); +} + +function test_set() { + const port = new SerialPort(''); + + port.set({}, (error: Error) => {}); +} + +function test_get() { + const port = new SerialPort(''); + + port.get((error, status) => {}); +} + +function test_flush() { + const port = new SerialPort(''); + + port.flush((error: Error) => {}); +} + +function test_drain() { + const port = new SerialPort(''); + + port.drain((error: Error) => {}); +} + +function test_pause_resume() { + const port = new SerialPort(''); + + const pauseItem: SerialPort = port.pause(); + const resumeItem: SerialPort = port.resume(); +} + +function test_on_events() { + const port = new SerialPort(''); + + const onItem: SerialPort = port.on('event', (data: any) => {}); +} + +function test_binding() { + const port = new SerialPort(''); + + const bindingItem: SerialPort.BaseBinding = SerialPort.Binding; +} + +function test_parsers() { + const port = new SerialPort(''); + + const ByteLengthParser = new SerialPort.parsers.ByteLength({length: 8}); + const CCTalkParser = new SerialPort.parsers.CCTalk(); + const DelimiterParser = new SerialPort.parsers.Delimiter({ delimiter: Buffer.from('EOL') }); + const ReadlineParser = new SerialPort.parsers.Readline({ delimiter: '\r\n' }); + const ReadyParser = new SerialPort.parsers.Ready({ data: 'READY' }); + const RegexParser = new SerialPort.parsers.Regex({regex: /.*/}); + + port.pipe(ByteLengthParser); + port.pipe(CCTalkParser); + port.pipe(DelimiterParser); + port.pipe(ReadlineParser); + port.pipe(ReadyParser); + port.pipe(RegexParser); +} + +function test_properties() { + const port = new SerialPort(''); + + const baudRate: number = port.baudRate; + const binding: SerialPort.BaseBinding = port.binding; + const isOpen: boolean = port.isOpen; + const path: string = port.path; +} diff --git a/types/serialport/v6/tsconfig.json b/types/serialport/v6/tsconfig.json new file mode 100644 index 0000000000..fbce55cebb --- /dev/null +++ b/types/serialport/v6/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "serialport": [ + "serialport/v6" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "serialport-tests.ts" + ] +} diff --git a/types/serialport/v6/tslint.json b/types/serialport/v6/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/serialport/v6/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/serverless/classes/Plugin.d.ts b/types/serverless/classes/Plugin.d.ts new file mode 100644 index 0000000000..f9b85e29a0 --- /dev/null +++ b/types/serverless/classes/Plugin.d.ts @@ -0,0 +1,11 @@ +import Serverless = require("../index"); + +declare abstract class Plugin { + hooks: { + [event: string]: Promise; + }; + + constructor(serverless: Serverless, options: Serverless.Options) +} + +export = Plugin; diff --git a/types/serverless/classes/PluginManager.d.ts b/types/serverless/classes/PluginManager.d.ts new file mode 100644 index 0000000000..95e01f721a --- /dev/null +++ b/types/serverless/classes/PluginManager.d.ts @@ -0,0 +1,27 @@ +import Serverless = require("../index"); +import Plugin = require("./Plugin"); + +declare class PluginManager { + constructor(serverless: Serverless) + + setCliOptions(options: Serverless.Options): void; + setCliCommands(commands: {}): void; + + addPlugin(plugin: typeof Plugin): void; + loadAllPlugins(servicePlugins: {}): void; + loadPlugins(plugins: {}): void; + loadCorePlugins(): void; + loadServicePlugins(servicePlugins: {}): void; + loadCommand(pluginName: string, details: {}, key: string): {}; + loadCommands(pluginInstance: Plugin): void; + + cliOptions: {}; + cliCommands: {}; + serverless: Serverless; + plugins: Plugin[]; + commands: {}; + hooks: {}; + deprecatedEvents: {}; +} + +export = PluginManager; diff --git a/types/serverless/classes/Service.d.ts b/types/serverless/classes/Service.d.ts new file mode 100644 index 0000000000..2f05f3b7c0 --- /dev/null +++ b/types/serverless/classes/Service.d.ts @@ -0,0 +1,37 @@ +import Serverless = require("../index"); + +declare namespace Service { + interface Custom { + [key: string]: any; + } +} + +declare class Service { + custom: Service.Custom; + + provider: { + compiledCloudFormationTemplate: { + Resources: any[]; + }; + + name: string; + }; + constructor(serverless: Serverless, data: {}); + + load(rawOptions: {}): Promise; + setFunctionNames(rawOptions: {}): void; + + getServiceName(): string; + getAllFunctions(): string[]; + getAllFunctionsNames(): string[]; + getFunction(functionName: string): Serverless.FunctionDefinition; + getEventInFunction(eventName: string, functionName: string): Serverless.Event; + getAllEventsInFunction(functionName: string): Serverless.Event[]; + + mergeResourceArrays(): void; + validate(): Service; + + update(data: {}): {}; +} + +export = Service; diff --git a/types/serverless/classes/Utils.d.ts b/types/serverless/classes/Utils.d.ts new file mode 100644 index 0000000000..d45f4890bb --- /dev/null +++ b/types/serverless/classes/Utils.d.ts @@ -0,0 +1,22 @@ +import Serverless = require("../index"); + +declare class Utils { + constructor(serverless: Serverless); + + getVersion(): string; + dirExistsSync(dirPath: string): boolean; + fileExistsSync(filePath: string): boolean; + writeFileDir(filePath: string): void; + writeFileSync(filePath: string, contents: string): void; + writeFile(filePath: string, contents: string): PromiseLike<{}>; + appendFileSync(filePath: string, contents: string): PromiseLike<{}>; + readFileSync(filePath: string): {}; + readFile(filePath: string): PromiseLike<{}>; + walkDirSync(dirPath: string): string[]; + copyDirContentsSync(srcDir: string, destDir: string): void; + generateShortId(length: number): string; + findServicePath(): string; + logStat(serverless: Serverless, context: string): PromiseLike<{}>; +} + +export = Utils; diff --git a/types/serverless/classes/YamlParser.d.ts b/types/serverless/classes/YamlParser.d.ts new file mode 100644 index 0000000000..88c3975fcf --- /dev/null +++ b/types/serverless/classes/YamlParser.d.ts @@ -0,0 +1,8 @@ +import Serverless = require("../index"); + +declare class YamlParser { + constructor(serverless: Serverless) + parse(yamlFilePath: string): Promise; +} + +export = YamlParser; diff --git a/types/serverless/index.d.ts b/types/serverless/index.d.ts new file mode 100644 index 0000000000..01f9d7a73e --- /dev/null +++ b/types/serverless/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for serverless 1.18 +// Project: https://github.com/serverless/serverless#readme +// Definitions by: Hassan Khan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import Service = require("./classes/Service"); +import Plugin = require("./classes/Plugin"); +import PluginManager = require("./classes/PluginManager"); +import Utils = require("./classes/Utils"); +import YamlParser = require("./classes/YamlParser"); +import AwsProvider = require("./plugins/aws/provider/awsProvider"); + +declare namespace Serverless { + interface Options { + stage: string | null; + region: string | null; + noDeploy?: boolean; + } + + interface Config { + servicePath: string; + } + + interface FunctionDefinition { + name: string; + } + + interface Event { + eventName: string; + } +} + +declare class Serverless { + constructor(config?: {}); + + init(): Promise; + run(): Promise; + + setProvider(name: string, provider: AwsProvider): null; + getProvider(name: string): AwsProvider; + + getVersion(): string; + + cli: { + log(message: string): null; + }; + + providers: {}; + utils: Utils; + variables: {}; + yamlParser: YamlParser; + pluginManager: PluginManager; + + config: Serverless.Config; + serverlessDirPath: string; + + service: Service; + version: string; +} + +export = Serverless; diff --git a/types/serverless/plugins/aws/provider/awsProvider.d.ts b/types/serverless/plugins/aws/provider/awsProvider.d.ts new file mode 100644 index 0000000000..c5c2c43414 --- /dev/null +++ b/types/serverless/plugins/aws/provider/awsProvider.d.ts @@ -0,0 +1,12 @@ +import Serverless = require("../../../index"); + +declare class Aws { + constructor(serverless: Serverless, options: Serverless.Options) + + getProviderName(): string; + getRegion(): string; + getServerlessDeploymentBucketName(): string; + getStage(): string; +} + +export = Aws; diff --git a/types/serverless/serverless-tests.ts b/types/serverless/serverless-tests.ts new file mode 100644 index 0000000000..ae5941e5ee --- /dev/null +++ b/types/serverless/serverless-tests.ts @@ -0,0 +1,9 @@ +import Serverless from 'serverless'; + +const options: Serverless.Options = { + noDeploy: false, + stage: null, + region: '' +}; + +const serverless = new Serverless(); diff --git a/types/serverless/tsconfig.json b/types/serverless/tsconfig.json new file mode 100644 index 0000000000..1d3097b8f5 --- /dev/null +++ b/types/serverless/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "serverless-tests.ts" + ] +} diff --git a/types/serverless/tslint.json b/types/serverless/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/serverless/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/slate-base64-serializer/index.d.ts b/types/slate-base64-serializer/index.d.ts index 6d356aa1c3..6e55220481 100644 --- a/types/slate-base64-serializer/index.d.ts +++ b/types/slate-base64-serializer/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ianstormtaylor/slate // Definitions by: Brandon Shelton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Value, Node } from "slate"; export function deserialize(string: string, options?: object): Value; diff --git a/types/slate-plain-serializer/index.d.ts b/types/slate-plain-serializer/index.d.ts index ed57cf3cca..1361c7f743 100644 --- a/types/slate-plain-serializer/index.d.ts +++ b/types/slate-plain-serializer/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brandon Shelton // Martin Kiefel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { BlockProperties, MarkProperties, Value } from 'slate'; export interface DeserializeOptions { diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index 31e7b95cbf..183cb462ef 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -93,9 +93,9 @@ export interface Plugin { renderEditor?: (props: RenderAttributes, editor?: Editor) => object | void; schema?: Schema; decorateNode?: (node: Node) => Range[] | void; - renderMark?: (props: RenderMarkProps) => any; - renderNode?: (props: RenderNodeProps) => any; - renderPlaceholder?: (props: RenderAttributes) => any; + renderMark?: (props: RenderMarkProps, next: () => void) => any; + renderNode?: (props: RenderNodeProps, next: () => void) => any; + renderPlaceholder?: (props: RenderAttributes, next: () => void) => any; renderPortal?: (props: RenderAttributes) => any; validateNode?: (node: Node) => any; } diff --git a/types/slate-react/slate-react-tests.tsx b/types/slate-react/slate-react-tests.tsx index d8c8ea0073..4b4a0cd9ed 100644 --- a/types/slate-react/slate-react-tests.tsx +++ b/types/slate-react/slate-react-tests.tsx @@ -3,7 +3,7 @@ import { Change, Value } from "slate"; import * as React from "react"; class MyPlugin implements Plugin { - renderNode(props: RenderNodeProps) { + renderNode(props: RenderNodeProps, next: () => void) { const { node } = props; if (node) { switch (node.object) { diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index f1cd8ecc64..8f80ba4615 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for slate 0.40 +// Type definitions for slate 0.43 // Project: https://github.com/ianstormtaylor/slate // Definitions by: Andy Kent // Jamie Talbot @@ -7,9 +7,11 @@ // Kalley Powell // Francesco Agnoletto // Irwan Fario Subastian +// Sebastian Greaves // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as Immutable from "immutable"; +import { SyntheticEvent } from "react"; export class Data extends Immutable.Record({}) { [key: string]: any; @@ -1476,10 +1478,10 @@ export class SlateError extends Error { [key: string]: any; } -export interface KeyUtils { - create(key: string): string; - setGenerator(func: () => any): void; - resetGenerator(): void; +export namespace KeyUtils { + function create(key?: string): string; + function setGenerator(func: () => any): void; + function resetGenerator(): void; } export type useMemoization = () => void; @@ -1527,4 +1529,30 @@ export interface PathUtils { ): Immutable.List; } +export interface EditorProperties { + onChange?: (change: Change) => void; + plugins?: any[]; + readOnly?: boolean; + value?: Value; +} + +export class Editor { + object: "editor"; + onChange: (change: Change) => void; + plugins: any[]; + readOnly: boolean; + value: Value; + constructor(attributes: EditorProperties) + + change(customChange: (change: Change, ...args: any[]) => Change): void; + command(name: string, ...args: any[]): void; + event(handler: string, event: Event | SyntheticEvent): void; + query(query: string, ...args: any[]): any; + registerCommand(command: string): void; + registerQuery(query: string): void; + run(key: string, ...args: any[]): any; + setReadOnly(readOnly: boolean): Editor; + setValue(value: Value, options?: object): Editor; +} + export {}; diff --git a/types/slate/slate-tests.ts b/types/slate/slate-tests.ts index 91ef2dadcb..7eb81633bf 100644 --- a/types/slate/slate-tests.ts +++ b/types/slate/slate-tests.ts @@ -1,4 +1,4 @@ -import { Value, Data, BlockJSON, Document } from "slate"; +import { Value, Data, BlockJSON, Document, Editor, Change, KeyUtils } from "slate"; const data = Data.create({ foo: "bar " }); const value = Value.create({ data }); @@ -45,3 +45,20 @@ const doc = Document.fromJSON({ data: {}, nodes: [node] }); + +const editor = new Editor({ value }); +editor.change((change: Change) => { + return change.insertText("test"); +}); + +editor.registerQuery("testQuery"); +editor.registerCommand("testCommand"); +editor.setReadOnly(true).setValue(value); +editor.command("testCommand"); +editor.query("testQuery"); +editor.run("testCommand"); +editor.event("mouseDown", new Event("mouseDown")); + +KeyUtils.setGenerator(() => "Test"); +KeyUtils.create(); +KeyUtils.resetGenerator(); diff --git a/types/snapsvg/index.d.ts b/types/snapsvg/index.d.ts index c012cc238c..85f1eda7b8 100644 --- a/types/snapsvg/index.d.ts +++ b/types/snapsvg/index.d.ts @@ -27,7 +27,7 @@ declare namespace Snap { export function fragment(varargs:any):Fragment; export function getElementByPoint(x:number,y:number):Snap.Element; export function is(o:any,type:string):boolean; - export function load(url:string,callback:Function,scope?:Object):void; + export function load(url:string,callback:(f:Fragment)=>void,scope?:Object):void; export function plugin(f:Function):void; export function select(query:string):Snap.Element; export function selectAll(query:string):any; diff --git a/types/snapsvg/test/3.ts b/types/snapsvg/test/3.ts index 45e7024c0a..7cd45e1ae9 100644 --- a/types/snapsvg/test/3.ts +++ b/types/snapsvg/test/3.ts @@ -175,8 +175,8 @@ window.onload=()=>{ { // Snap load and animate svg var g = s.group(); - var tux = Snap.load("Dreaming_tux.svg", function ( loadedFragment:Snap.Element ) { - g.append( loadedFragment ); + var tux = Snap.load("Dreaming_tux.svg", function ( loadedFragment:Snap.Fragment ) { + g.append( loadedFragment.selectAll() ); g.hover( hoverover, hoverout ); g.text(300,100, 'hover over me'); } ); diff --git a/types/socket.io/index.d.ts b/types/socket.io/index.d.ts index 95a9ff1b4f..f5e6c5fd00 100644 --- a/types/socket.io/index.d.ts +++ b/types/socket.io/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for socket.io 1.4.5 +// Type definitions for socket.io 2.1 // Project: http://socket.io/ // Definitions by: PROGRE // Damian Connolly @@ -188,7 +188,7 @@ declare namespace SocketIO { * with a '/' * @return The Namespace */ - of( nsp: string ): Namespace; + of( nsp: string | RegExp | Function ): Namespace; /** * Closes the server connection diff --git a/types/socket.io/socket.io-tests.ts b/types/socket.io/socket.io-tests.ts index 60f0d70551..5a70af45db 100644 --- a/types/socket.io/socket.io-tests.ts +++ b/types/socket.io/socket.io-tests.ts @@ -103,6 +103,15 @@ function testRestrictingYourselfToANamespace() { }); } +function testDynamicNamespace() { + var io = socketIO.listen(80); + var dynamic = io + .of(/^\/dynamic-\d+$/) + .on('connection', function (socket) { + socket.emit('item', { dynamic: 'item' }); + }); +} + function testSendingVolatileMessages() { var io = socketIO.listen(80); @@ -188,4 +197,4 @@ function testSocketUse() { console.log(packet); }); }); -} \ No newline at end of file +} diff --git a/types/socket.io/v1/index.d.ts b/types/socket.io/v1/index.d.ts new file mode 100644 index 0000000000..95a9ff1b4f --- /dev/null +++ b/types/socket.io/v1/index.d.ts @@ -0,0 +1,850 @@ +// Type definitions for socket.io 1.4.5 +// Project: http://socket.io/ +// Definitions by: PROGRE +// Damian Connolly +// Florent Poujol +// KentarouTakeda +// Alexey Snigirev +// Ezinwa Okpoechi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const SocketIO: SocketIOStatic; +export = SocketIO; +/** @deprecated Available as a global for backwards-compatibility. */ +export as namespace SocketIO; + +interface SocketIOStatic { + /** + * Default Server constructor + */ + (): SocketIO.Server; + + /** + * Creates a new Server + * @param srv The HTTP server that we're going to bind to + * @param opts An optional parameters object + */ + (srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param port A port to bind to, as a number, or a string + * @param An optional parameters object + */ + (port: string|number, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param A parameters object + */ + (opts: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Backwards compatibility + * @see io().listen() + */ + listen: SocketIOStatic; +} + +declare namespace SocketIO { + interface Server { + engine: { ws: any }; + + /** + * A dictionary of all the namespaces currently on this Server + */ + nsps: {[namespace: string]: Namespace}; + + /** + * The default '/' Namespace + */ + sockets: Namespace; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Server; + + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the clients are not ready to receive messages + */ + volatile: Server; + + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node + */ + local: Server; + + /** + * Server request verification function, that checks for allowed origins + * @param req The http.IncomingMessage request + * @param fn The callback to be called. It should take one parameter, err, + * which will be null if there was no problem, and one parameter, success, + * of type boolean + */ + checkRequest( req:any, fn:( err: any, success: boolean ) => void ):void; + + /** + * Gets whether we're serving the client.js file or not + * @default true + */ + serveClient(): boolean; + + /** + * Sets whether we're serving the client.js file or not + * @param v True if we want to serve the file, false otherwise + * @default true + * @return This Server + */ + serveClient( v: boolean ): Server; + + /** + * Gets the client serving path + * @default '/socket.io' + */ + path(): string; + + /** + * Sets the client serving path + * @param v The path to serve the client file on + * @default '/socket.io' + * @return This Server + */ + path( v: string ): Server; + + /** + * Gets the adapter that we're going to use for handling rooms + * @default typeof Adapter + */ + adapter(): any; + + /** + * Sets the adapter (class) that we're going to use for handling rooms + * @param v The class for the adapter to create + * @default typeof Adapter + * @return This Server + */ + adapter( v: any ): Server; + + /** + * Gets the allowed origins for requests + * @default "*:*" + */ + origins(): string|string[]; + + /** + * Sets the allowed origins for requests + * @param v The allowed origins, in host:port form + * @default "*:*" + * return This Server + */ + origins( v: string|string[] ): Server; + + /** + * Attaches socket.io to a server + * @param srv The http.Server that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( srv: any, opts?: ServerOptions ): Server; + + /** + * Attaches socket.io to a port + * @param port The port that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( port: number, opts?: ServerOptions ): Server; + + /** + * @see attach( srv, opts ) + */ + listen( srv: any, opts?: ServerOptions ): Server; + + /** + * @see attach( port, opts ) + */ + listen( port: number, opts?: ServerOptions ): Server; + + /** + * Binds socket.io to an engine.io intsance + * @param src The Engine.io (or compatible) server to bind to + * @return This Server + */ + bind( srv: any ): Server; + + /** + * Called with each incoming connection + * @param socket The Engine.io Socket + * @return This Server + */ + onconnection( socket: any ): Server; + + /** + * Looks up/creates a Namespace + * @param nsp The name of the NameSpace to look up/create. Should start + * with a '/' + * @return The Namespace + */ + of( nsp: string ): Namespace; + + /** + * Closes the server connection + */ + close( fn ?: () => void ):void; + + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return The default '/' Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @return The default '/' Namespace + */ + on( event: string, listener: Function ): Namespace; + + /** + * Targets a room when emitting to the default '/' Namespace + * @param room The name of the room that we're targeting + * @return The default '/' Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket, on the default '/' Namespace + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return The default '/' Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Emits an event to the default Namespace + * @param event The event that we want to emit + * @param args Any number of optional arguments to pass with the event. If the + * last argument is a function, it will be called as an ack. The ack should + * take whatever data was sent with the packet + * @return The default '/' Namespace + */ + emit( event: string, ...args: any[]): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return The default '/' Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; + + /** + * Gets a list of clients + * @return The default '/' Namespace + */ + clients( ...args: any[] ): Namespace; + + /** + * Sets the compress flag + * @return The default '/' Namespace + */ + compress( ...args: any[] ): Namespace; + } + + /** + * Options to pass to our server when creating it + */ + interface ServerOptions { + + /** + * The path to server the client file to + * @default '/socket.io' + */ + path?: string; + + /** + * Should we serve the client file? + * @default true + */ + serveClient?: boolean; + + /** + * The adapter to use for handling rooms. NOTE: this should be a class, + * not an object + * @default typeof Adapter + */ + adapter?: Adapter; + + /** + * Accepted origins + * @default '*:*' + */ + origins?: string|string[]; + + /** + * How many milliseconds without a pong packed to consider the connection closed (engine.io) + * @default 60000 + */ + pingTimeout?: number; + + /** + * How many milliseconds before sending a new ping packet (keep-alive) (engine.io) + * @default 25000 + */ + pingInterval?: number; + + /** + * How many bytes or characters a message can be when polling, before closing the session + * (to avoid Dos) (engine.io) + * @default 10E7 + */ + maxHttpBufferSize?: number; + + /** + * A function that receives a given handshake or upgrade request as its first parameter, + * and can decide whether to continue or not. The second argument is a function that needs + * to be called with the decided information: fn( err, success ), where success is a boolean + * value where false means that the request is rejected, and err is an error code (engine.io) + * @default null + */ + allowRequest?: (request:any, callback: (err: number, success: boolean) => void) => void; + + /** + * Transports to allow connections to (engine.io) + * @default ['polling','websocket'] + */ + transports?: string[]; + + /** + * Whether to allow transport upgrades (engine.io) + * @default true + */ + allowUpgrades?: boolean; + + /** + * parameters of the WebSocket permessage-deflate extension (see ws module). + * Set to false to disable (engine.io) + * @default true + */ + perMessageDeflate?: Object|boolean; + + /** + * Parameters of the http compression for the polling transports (see zlib). + * Set to false to disable, or set an object with parameter "threshold:number" + * to only compress data if the byte size is above this value (1024) (engine.io) + * @default true|1024 + */ + httpCompression?: Object|boolean; + + /** + * Name of the HTTP cookie that contains the client sid to send as part of + * handshake response headers. Set to false to not send one (engine.io) + * @default "io" + */ + cookie?: string|boolean; + } + + /** + * The Namespace, sandboxed environments for sockets, each connection + * to a Namespace requires a new Socket + */ + interface Namespace extends NodeJS.EventEmitter { + + /** + * The name of the NameSpace + */ + name: string; + + /** + * The controller Server for this Namespace + */ + server: Server; + + /** + * A dictionary of all the Sockets connected to this Namespace, where + * the Socket ID is the key + */ + sockets: { [id: string]: Socket }; + + /** + * A dictionary of all the Sockets connected to this Namespace, where + * the Socket ID is the key + */ + connected: { [id: string]: Socket }; + + /** + * The Adapter that we're using to handle dealing with rooms etc + */ + adapter: Adapter; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return This Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Targets a room when emitting + * @param room The name of the room that we're targeting + * @return This Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return This Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; + + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return This Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): this; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): this; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @ This Namespace + */ + on( event: string, listener: Function ): this; + + /** + * Gets a list of clients. + * @return This Namespace + */ + clients( fn: Function ): Namespace; + + /** + * Sets the compress flag. + * @param compress If `true`, compresses the sending data + * @return This Namespace + */ + compress( compress: boolean ): Namespace; + } + + interface Packet extends Array { + /** + * Event name + */ + [0]: string; + /** + * Packet data + */ + [1]: any; + /** + * Ack function + */ + [2]: (...args: any[]) => void; + } + + /** + * The socket, which handles our connection for a namespace. NOTE: while + * we technically extend NodeJS.EventEmitter, we're not putting it here + * as we have a problem with the emit() event (as it's overridden with a + * different return) + */ + interface Socket extends NodeJS.EventEmitter{ + + /** + * The namespace that this socket is for + */ + nsp: Namespace; + + /** + * The Server that our namespace is in + */ + server: Server; + + /** + * The Adapter that we use to handle our rooms + */ + adapter: Adapter; + + /** + * The unique ID for this Socket. Regenerated at every connection. This is + * also the name of the room that the Socket automatically joins on connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The Client associated with this Socket + */ + client: Client; + + /** + * The underlying Engine.io Socket instance + */ + conn: EngineSocket; + + /** + * The list of rooms that this Socket is currently in, where + * the ID the the room ID + */ + rooms: { [id: string]: string }; + + /** + * Is the Socket currently connected? + */ + connected: boolean; + + /** + * Is the Socket currently disconnected? + */ + disconnected: boolean; + + /** + * The object used when negociating the handshake + */ + handshake: Handshake; + /** + * Sets the 'json' flag when emitting an event + */ + json: Socket; + + /** + * Sets the 'volatile' flag when emitting an event. Volatile messages are + * messages that can be dropped because of network issues and the like. Use + * for high-volume/real-time messages where you don't need to receive *all* + * of them + */ + volatile: Socket; + + /** + * Sets the 'broadcast' flag when emitting an event. Broadcasting an event + * will send it to all the other sockets in the namespace except for yourself + */ + broadcast: Socket; + + /** + * Targets a room when broadcasting + * @param room The name of the room that we're targeting + * @return This Socket + */ + to( room: string ): Socket; + + /** + * @see to( room ) + */ + in( room: string ): Socket; + + /** + * Registers a middleware, which is a function that gets executed for every incoming Packet and receives as parameter the packet and a function to optionally defer execution to the next registered middleware. + * + * Errors passed to middleware callbacks are sent as special error packets to clients. + */ + use( fn: ( packet: Packet, next: (err?: any) => void ) => void ): Socket; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + */ + send( ...args: any[] ): Socket; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Socket; + + /** + * Joins a room. You can join multiple rooms, and by default, on connection, + * you join a room with the same name as your ID + * @param name The name of the room that we want to join + * @param fn An optional callback to call when we've joined the room. It should + * take an optional parameter, err, of a possible error + * @return This Socket + */ + join( name: string|string[], fn?: ( err?: any ) => void ): Socket; + + /** + * Leaves a room + * @param name The name of the room to leave + * @param fn An optional callback to call when we've left the room. It should + * take on optional parameter, err, of a possible error + */ + leave( name: string, fn?: Function ): Socket; + + /** + * Leaves all the rooms that we've joined + */ + leaveAll(): void; + + /** + * Disconnects this Socket + * @param close If true, also closes the underlying connection + * @return This Socket + */ + disconnect( close?: boolean ): Socket; + + /** + * Returns all the callbacks for a particular event + * @param event The event that we're looking for the callbacks of + * @return An array of callback Functions, or an empty array if we don't have any + */ + listeners( event: string ):Function[]; + + /** + * Sets the compress flag + * @param compress If `true`, compresses the sending data + * @return This Socket + */ + compress( compress: boolean ): Socket; + } + + interface Handshake { + /** + * The headers passed along with the request. e.g. 'host', + * 'connection', 'accept', 'referer', 'cookie' + */ + headers: any; + + /** + * The current time, as a string + */ + time: string; + + /** + * The remote address of the connection request + */ + address: string; + + /** + * Is this a cross-domain request? + */ + xdomain: boolean; + + /** + * Is this a secure request? + */ + secure: boolean; + + /** + * The timestamp for when this was issued + */ + issued: number; + + /** + * The request url + */ + url: string; + + /** + * Any query string parameters in the request url + */ + query: any; + } + + /** + * The interface describing a room + */ + interface Room { + sockets: {[id: string]: boolean }; + length: number; + } + + /** + * The interface describing a dictionary of rooms + * Where room is the name of the room + */ + + interface Rooms { + [room: string]: Room; + } + + /** + * The interface used when dealing with rooms etc + */ + interface Adapter extends NodeJS.EventEmitter { + + /** + * The namespace that this adapter is for + */ + nsp: Namespace; + + /** + * A dictionary of all the rooms that we have in this namespace + */ + rooms: Rooms; + + /** + * A dictionary of all the socket ids that we're dealing with, and all + * the rooms that the socket is currently in + */ + sids: {[id: string]: {[room: string]: boolean}}; + + /** + * Adds a socket to a room. If the room doesn't exist, it's created + * @param id The ID of the socket to add + * @param room The name of the room to add the socket to + * @param callback An optional callback to call when the socket has been + * added. It should take an optional parameter, error, if there was a problem + */ + add( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from a room. If there are no more sockets in the room, + * the room is deleted + * @param id The ID of the socket that we're removing + * @param room The name of the room to remove the socket from + * @param callback An optional callback to call when the socket has been + * removed. It should take on optional parameter, error, if there was a problem + */ + del( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from all the rooms that it's joined + * @param id The ID of the socket that we're removing + */ + delAll( id: string ):void; + + /** + * Broadcasts a packet + * @param packet The packet to broadcast + * @param opts Any options to send along: + * - rooms: An optional list of rooms to broadcast to. If empty, the packet is broadcast to all sockets + * - except: A list of Socket IDs to exclude + * - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast') + */ + broadcast( packet: any, opts: { rooms?: string[]; except?: string[]; flags?: {[flag: string]: boolean} } ):void; + } + + /** + * The client behind each socket (can have multiple sockets) + */ + interface Client { + /** + * The Server that this client belongs to + */ + server: Server; + + /** + * The underlying Engine.io Socket instance + */ + conn: EngineSocket; + + /** + * The ID for this client. Regenerated at every connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The dictionary of sockets currently connect via this client (i.e. to different + * namespaces) where the Socket ID is the key + */ + sockets: {[id: string]: Socket}; + + /** + * A dictionary of all the namespaces for this client, with the Socket that + * deals with that namespace + */ + nsps: {[nsp: string]: Socket}; + } + + /** + * A reference to the underlying engine.io Socket connection. + */ + interface EngineSocket extends NodeJS.EventEmitter { + /** + * The ID for this socket - matches Client.id + */ + id: string; + + /** + * The Engine.io Server for this socket + */ + server: any; + + /** + * The ready state for the client. Either 'opening', 'open', 'closing', or 'closed' + */ + readyState: string; + + /** + * The remote IP for this connection + */ + remoteAddress: string; + + /** + * whether the transport has been upgraded + */ + upgraded: boolean; + + /** + * (http.IncomingMessage): request that originated the Socket + */ + request: any; + + /** + * (Transport): transport reference + */ + transport: any; + } +} diff --git a/types/socket.io/v1/socket.io-tests.ts b/types/socket.io/v1/socket.io-tests.ts new file mode 100644 index 0000000000..60f0d70551 --- /dev/null +++ b/types/socket.io/v1/socket.io-tests.ts @@ -0,0 +1,191 @@ +import socketIO = require('socket.io'); + +function testUsingWithNodeHTTPServer() { + var app = require('http').createServer(handler); + var io: socketIO.Server = socketIO(app); + var fs = require('fs'); + + app.listen(80); + + function handler(req: any, res: any) { + fs.readFile(__dirname + '/index.html', + function (err: any, data: any) { + if (err) { + res.writeHead(500); + return res.end('Error loading index.html'); + } + + res.writeHead(200); + res.end(data); + }); + } + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithExpress() { + var app = require('express')(); + var server = require('http').Server(app); + var io = socketIO(server); + + server.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithTheExpressFramework() { + var app = require('express').createServer(); + var io = socketIO(app); + + app.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testSendingAndReceivingEvents() { + var io = socketIO(80); + + io.on('connection', function (socket) { + io.emit('this', { will: 'be received by everyone' }); + + socket.on('private message', function (from: any, msg: any) { + console.log('I received a private message by ', from, ' saying ', msg); + }); + + socket.on('disconnect', function () { + io.sockets.emit('user disconnected'); + }); + }); +} + +function testRestrictingYourselfToANamespace() { + var io = socketIO.listen(80); + var chat = io + .of('/chat') + .on('connection', function (socket) { + socket.emit('a message', { + that: 'only' + , '/chat': 'will get' + }); + chat.emit('a message', { + everyone: 'in' + , '/chat': 'will get' + }); + }); + + var news = io + .of('/news') + .on('connection', function (socket) { + socket.emit('item', { news: 'item' }); + }); +} + +function testSendingVolatileMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + var tweets = setInterval(function () { + socket.volatile.emit('bieber tweet', {}); + }, 100); + + socket.on('disconnect', function () { + clearInterval(tweets); + }); + }); +} + +function testSendingAndGettingData() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('ferret', function (name: any, fn: any) { + fn('woot'); + }); + }); +} + +function testBroadcastingMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.broadcast.emit('user connected'); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('message', function () { }); + socket.on('disconnect', function () { }); + }); +} + +function testSocketConnection() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + console.log(socket.client.conn === socket.conn); + console.log(socket.client.request.httpVersion); + console.log(socket.conn.id); + console.log(socket.conn.upgraded); + console.log(socket.conn.readyState); + + socket.on('packet', function(message :string, ping :string){ + console.log(message, ping); + });; + }); +} + +function testClosingServerWithCallback() { + var io = socketIO.listen(80); + io.close(function() { + }); +} + +function testClosingServerWithoutCallback() { + var io = socketIO.listen(80); + io.close(); +} + +function testLocalServerMessages() { + var io = socketIO.listen(80); + io.local.emit('local', 'Local data'); +} + +function testVolatileServerMessages() { + var io = socketIO.listen(80); + io.volatile.emit('volatile', 'Lost data'); +} + +function testSocketUse() { + var io = socketIO.listen(80); + io.on('connection', (socket) => { + socket.use((packet, next) => { + console.log(packet); + }); + }); +} \ No newline at end of file diff --git a/types/socket.io/v1/tsconfig.json b/types/socket.io/v1/tsconfig.json new file mode 100644 index 0000000000..8f7bad0ba7 --- /dev/null +++ b/types/socket.io/v1/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "socket.io": [ "socket.io/v1" ] + } + }, + "files": [ + "index.d.ts", + "socket.io-tests.ts" + ] +} diff --git a/types/react-i18next/v1/tslint.json b/types/socket.io/v1/tslint.json similarity index 100% rename from types/react-i18next/v1/tslint.json rename to types/socket.io/v1/tslint.json diff --git a/types/sonic-boom/index.d.ts b/types/sonic-boom/index.d.ts new file mode 100644 index 0000000000..292770bd0d --- /dev/null +++ b/types/sonic-boom/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for sonic-boom 0.6 +// Project: https://github.com/mcollina/sonic-boom.git +// Definitions by: Alex Ferrando +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { EventEmitter } from 'events'; + +export = SonicBoom; + +declare class SonicBoom extends EventEmitter { + /** + * @param [fileDescriptor] File path or numerical file descriptor + * relative protocol is enabled. Default: process.stdout + * @returns a new sonic-boom instance + */ + constructor(fileDescriptor: string | number) + + /** + * Writes the string to the file. It will return false to signal the producer to slow down. + */ + write(string: string): void; + + /** + * Writes the current buffer to the file if a write was not in progress. + * Do nothing if minLength is zero or if it is already writing. + */ + flush(): void; + + /** + * Reopen the file in place, useful for log rotation. + */ + reopen(file: string): void; + + /** + * Flushes the buffered data synchronously. This is a costly operation. + */ + flushSync(): void; + + /** + * Closes the stream, the data will be flushed down asynchronously + */ + end(): void; + + /** + * Closes the stream immediately, the data is not flushed. + */ + destroy(): void; +} diff --git a/types/sonic-boom/sonic-boom-tests.ts b/types/sonic-boom/sonic-boom-tests.ts new file mode 100644 index 0000000000..a3beb06d0c --- /dev/null +++ b/types/sonic-boom/sonic-boom-tests.ts @@ -0,0 +1,12 @@ +import SonicBoom = require('sonic-boom'); +const sonic = new SonicBoom(1); + +sonic.write('hello sonic\n'); + +sonic.flush(); + +sonic.flushSync(); + +sonic.end(); + +sonic.destroy(); diff --git a/types/sonic-boom/tsconfig.json b/types/sonic-boom/tsconfig.json new file mode 100644 index 0000000000..46c62493b0 --- /dev/null +++ b/types/sonic-boom/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", + "sonic-boom-tests.ts" + ] +} diff --git a/types/sonic-boom/tslint.json b/types/sonic-boom/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sonic-boom/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/speakeasy/index.d.ts b/types/speakeasy/index.d.ts index 06d79ea6aa..573a9df820 100644 --- a/types/speakeasy/index.d.ts +++ b/types/speakeasy/index.d.ts @@ -1,119 +1,452 @@ -// Type definitions for speakeasy v2.0.0 +// Type definitions for speakeasy 2.0 // Project: https://github.com/speakeasyjs/speakeasy // Definitions by: Lucas Woo , Alexander Batukhtin , Aayush Kapoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface SharedOptions { - encoding?: string; - algorithm?: string; +/// + +export type Encoding = 'ascii' | 'hex' | 'base32' | 'base64'; +export type Algorithm = 'sha1' | 'sha256' | 'sha512'; + +export interface SharedOptions { + /** + * Key encoding, defaults to ascii + */ + encoding?: Encoding; + /** + * Algorithm, defaults to sha1 + */ + algorithm?: Algorithm; } -interface Key { +export interface GeneratedSecret { + /** + * ASCII representation of the secret + */ ascii: string; - base32: string; + /** + * Hex representation of the secret + */ hex: string; - qr_code_ascii: string; - qr_code_hex: string; - qr_code_base32: string; + /** + * Base32 representation of the secret + */ + base32: string; + /** + * URL for the QR code for the ASCII secret. + * + * @deprecated use a separate QR code library + */ + qr_code_ascii?: string; + /** + * URL for the QR code for the hex secret. + * + * @deprecated use a separate QR code library + */ + qr_code_hex?: string; + /** + * URL for the QR code for the base32 secret. + * + * @deprecated use a separate QR code library + */ + qr_code_base32?: string; + /** + * URL for the Google Authenticator otpauth + * URL's QR code. + * + * @deprecated use a separate QR code library + */ google_auth_qr: string; + /** + * Google Authenticator-compatible otpauth URL. + */ otpauth_url?: string; } +export interface GeneratedSecretWithOtpAuthUrl extends GeneratedSecret { + /** + * Google Authenticator-compatible otpauth URL. + */ + otpauth_url: string; +} -interface DigestOptions extends SharedOptions { +export interface DigestOptions extends SharedOptions { secret: string; - counter: string; + counter: number; + /** + * @deprecated use secret + */ key?: string; } -interface GenerateOptions { +export interface GenerateSecretOptions { + /** + * Length of the secret, defaults to 32 + */ length?: number; + /** + * Whether to include symbols, defaults to false + */ symbols?: boolean; - qr_codes?: boolean; - google_auth_qr?: boolean; + /** + * The name to use with Google Authenticator, deaults to 'SecretKey' + */ name?: string; -} - -interface GenerateSecretOptions { - length?: number; - name?: string; - qr_codes?: boolean; - google_auth_qr?: boolean; + /** + * Whether to output a Google Authenticator-compatible otpauth:// URL + * (only returns otpauth:// URL, no QR code), defaults to false + */ otpauth_url?: boolean; - symbols?: boolean; + /** + * The provider or service with which the + * secret key is associated, defaults to '' + */ + issuer?: string; + /** + * Output QR code URLs for the token. + * + * @deprecated use your own QR code implementation to prevent + * leaking of secret to a third party. + */ + qr_codes?: boolean; + /** + * Output a Google Authenticator otpauth:// QR code URL. + * + * @deprecated use your own QR code implementation to prevent + * leaking of secret to a third party. + */ + google_auth_qr?: boolean; +} +export interface GenerateSecretWithOtpAuthUrlOptions extends GenerateSecretOptions { + /** + * Whether to output a Google Authenticator-compatible otpauth:// URL + * (only returns otpauth:// URL, no QR code), defaults to false + */ + otpauth_url: true; } -interface TotpOptions extends SharedOptions { - key?: string; - step?: number; +export interface HotpOptions extends DigestOptions { + /** + * @deprecated use digits + */ + length?: number; + /** + * The number of digits for the one-time passcode, defaults to 6 + */ + digits?: number; + /** + * The digest, automatically generated by default + */ + digest?: Buffer; +} + +export interface HotpVerifyOptions extends SharedOptions { + /** + * Shared secret key + */ + secret: string; + /** + * Passcode to validate + */ + token: string; + /** + * Counter value. This should be stored by + * the application and must be incremented for each request. + */ + counter: number; + /** + * The number of digits for the one-time passcode, defaults to 6 + */ + digits?: number; + /** + * The allowable margin for the counter. + * The function will check "W" codes in the future against the provided + * passcode, e.g. if W = 10, and C = 5, this function will check the + * passcode against all One Time Passcodes between 5 and 15, inclusive, + * defaults to 0 + */ + window?: number; +} + +export interface TotpOptions extends SharedOptions { + /** + * Time in seconds with which to calculate + * counter value, defaults to `Date.now() / 1000`. + */ time?: number; + /** + * Time step in seconds, defaults to 30 + */ + step?: number; + /** + * Initial time since the UNIX epoch from which to calculate the counter value, + * defaults to 0 (no offset). + */ + epoch?: number; + /** + * @deprecated use epoch + */ initial_time?: number; - length?: number; - counter?: number; - epoch?: number; - secret?: string; + /** + * The number of digits for the one-time passcode, defaults to 6 + */ digits?: number; - digest?: () => string; + /** + * @deprecated use digits + */ + length?: number; + /** + * The digest, automatically generated by default + */ + digest?: Buffer; + /** + * Shared secret key + */ + secret: string; + /** + * @deprecated use secret + */ + key?: string; + /** + * The counter value, calculated from time by default + */ + counter?: string; } -interface TotpVerifyOptions extends SharedOptions { +export interface TotpVerifyOptions extends SharedOptions { + /** + * Shared secret key + */ secret: string; + /** + * Passcode to validate + */ token: string; + /** + * Time in seconds with which to calculate + * counter value, defaults to `Date.now() / 1000`. + */ time?: number; + /** + * Time step in seconds, defaults to 30 + */ step?: number; + /** + * Initial time since the UNIX epoch from which to calculate the counter value, + * defaults to 0 (no offset). + */ epoch?: number; - counter?: number; + /** + * The number of digits for the one-time passcode, defaults to 6 + */ digits?: number; + /** + * The allowable margin for the counter. + * The function will check "W" codes in the future and the past against the + * provided passcode, e.g. if W = 5, and C = 1000, this function will check + * the passcode against all One Time Passcodes between 995 and 1005, inclusive + * defaults to 0 + */ window?: number; + /** + * The counter value, calculated from time by default + */ + counter?: string; } -interface HotpOptions extends SharedOptions { - key: string; - counter: number; - length?: number; - digits?: number; - digest?: () => string; -} - -interface HotpVerifyOptions extends SharedOptions { - secret: string; - token: string; - counter: number; - digits?: number; - window?: number; -} - -interface OtpauthURLOptions extends SharedOptions { +export interface OtpauthURLOptions extends SharedOptions { + /** + * Shared secret key + */ secret: string; + /** + * Used to identify the account with which the secret key is associated, + * e.g. the user's email address. + */ label: string; - issuer?: any; - type?: string; + /** + * Either 'hotp' or 'totp', defaults to 'totp' + */ + type?: 'htop' | 'totp'; + /** + * The initial counter value, required for HOTP. + */ counter?: number; + /** + * The provider or service with which the secret key is associated. + */ + issuer?: string; + /** + * The number of digits for the one-time passcode. Currently ignored + * by Google Authenticator, defaults to 6 + */ digits?: number; + /** + * The length of time for which a TOTP code will be valid, in seconds. + * Currently ignored by Google Authenticator, defaults to 30 + */ period?: number; } -interface Hotp { +export interface Delta { + delta: number; +} + +export interface Hotp { + /** + * Generate a counter-based one-time token. Specify the key and counter, and + * receive the one-time password for that counter position as a string. You can + * also specify a token length, as well as the encoding (ASCII, hexadecimal, or + * base32) and the hashing algorithm to use (SHA1, SHA256, SHA512). + * + * @return The one-time passcode. + */ (options: HotpOptions): string; - verifyDelta: (options: HotpVerifyOptions) => boolean; + /** + * Verify a counter-based one-time token against the secret and return the delta. + * By default, it verifies the token at the given counter value, with no leeway + * (no look-ahead or look-behind). A token validated at the current counter value + * will have a delta of 0. + * + * You can specify a window to add more leeway to the verification process. + * Setting the window param will check for the token at the given counter value + * as well as `window` tokens ahead (one-sided window). See param for more info. + * + * `verifyDelta()` will return the delta between the counter value of the token + * and the given counter value. For example, if given a counter 5 and a window + * 10, `verifyDelta()` will look at tokens from 5 to 15, inclusive. If it finds + * it at counter position 7, it will return `{ delta: 2 }`. + * + * @return On success, returns an object with the counter + * difference between the client and the server as the `delta` property (i.e. + * `{ delta: 0 }`). + */ + verifyDelta: (options: HotpVerifyOptions) => undefined | Delta; + /** + * Verify a counter-based one-time token against the secret and return true if + * it verifies. Helper function for `hotp.verifyDelta()`` that returns a boolean + * instead of an object. + * + * @return Returns true if the token matches within the given window, false otherwise. + */ verify: (options: HotpVerifyOptions) => boolean; } -interface Totp { +export interface Totp { + /** + * Generate a time-based one-time token. Specify the key, and receive the + * one-time password for that time as a string. By default, it uses the current + * time and a time step of 30 seconds, so there is a new token every 30 seconds. + * You may override the time step and epoch for custom timing. You can also + * specify a token length, as well as the encoding (ASCII, hexadecimal, or + * base32) and the hashing algorithm to use (SHA1, SHA256, SHA512). + * + * Under the hood, TOTP calculates the counter value by finding how many time + * steps have passed since the epoch, and calls HOTP with that counter value. + * + * @return The one-time passcode. + */ (options: TotpOptions): string; - verifyDelta: (options: TotpVerifyOptions) => boolean; + /** + * Verify a time-based one-time token against the secret and return the delta. + * By default, it verifies the token at the current time window, with no leeway + * (no look-ahead or look-behind). A token validated at the current time window + * will have a delta of 0. + * + * You can specify a window to add more leeway to the verification process. + * Setting the window param will check for the token at the given counter value + * as well as `window` tokens ahead and `window` tokens behind (two-sided + * window). See param for more info. + * + * `verifyDelta()` will return the delta between the counter value of the token + * and the given counter value. For example, if given a time at counter 1000 and + * a window of 5, `verifyDelta()` will look at tokens from 995 to 1005, + * inclusive. In other words, if the time-step is 30 seconds, it will look at + * tokens from 2.5 minutes ago to 2.5 minutes in the future, inclusive. + * If it finds it at counter position 1002, it will return `{ delta: 2 }`. + * If it finds it at counter position 997, it will return `{ delta: -3 }`. + * + * @return On success, returns an object with the time step + * difference between the client and the server as the `delta` property (e.g. + * `{ delta: 0 }`). + */ + verifyDelta: (options: TotpVerifyOptions) => undefined | Delta; + /** + * Verify a time-based one-time token against the secret and return true if it + * verifies. Helper function for verifyDelta() that returns a boolean instead of + * an object. + * + * @return Returns true if the token matches within the given + * window, false otherwise. + */ verify: (options: TotpVerifyOptions) => boolean; } -export declare const hotp: Hotp; -export declare const totp: Totp; +/** + * Digest the one-time passcode options. + * + * @return The one-time passcode as a buffer. + */ +export function digest(options: DigestOptions): Buffer; -export declare function time(options: TotpOptions): string; -export declare function counter(options: HotpOptions): string; -export declare function digest(options: DigestOptions): string; -export declare function generate_key(options: GenerateOptions): Key; -export declare function generateSecret(options?: GenerateSecretOptions): Key; -export declare function generateSecretASCII( +export const hotp: Hotp; +// Alias counter() for hotp() +export const counter: Hotp; + +export const totp: Totp; +// Alias time() for totp() +export const time: Totp; + +/** + * Generates a random secret with the set A-Z a-z 0-9 and symbols, of any length + * (default 32). Returns the secret key in ASCII, hexadecimal, and base32 format, + * along with the URL used for the QR code for Google Authenticator (an otpauth + * URL). Use a QR code library to generate a QR code based on the Google + * Authenticator URL to obtain a QR code you can scan into the app. + */ +export function generateSecret(options: GenerateSecretWithOtpAuthUrlOptions): GeneratedSecretWithOtpAuthUrl; +/** + * Generates a random secret with the set A-Z a-z 0-9 and symbols, of any length + * (default 32). Returns the secret key in ASCII, hexadecimal, and base32 format, + * along with the URL used for the QR code for Google Authenticator (an otpauth + * URL). Use a QR code library to generate a QR code based on the Google + * Authenticator URL to obtain a QR code you can scan into the app. + */ +export function generateSecret(options?: GenerateSecretOptions): GeneratedSecret; +/** + * @deprecated use generateSecret + */ +export const generate_key: typeof generateSecret; + +/** + * Generates a key of a certain length (default 32) from A-Z, a-z, 0-9, and + * symbols (if requested). + * + * @param length The length of the key, defaults to 32 + * @param symbols Whether to include symbols in the key, defaults to false + * @return The generated key. + */ +export function generateSecretASCII( length?: number, symbols?: boolean ): string; -export declare function otpauthURL(options: OtpauthURLOptions): string; +/** + * @deprecated use generateSecret + */ +export const generate_key_ascii: typeof generateSecretASCII; + +/** + * Generate a Google Authenticator-compatible otpauth:// URL for passing the + * secret to a mobile device to install the secret. + * + * Authenticator considers TOTP codes valid for 30 seconds. Additionally, + * the app presents 6 digits codes to the user. According to the + * documentation, the period and number of digits are currently ignored by + * the app. + * + * To generate a suitable QR Code, pass the generated URL to a QR Code + * generator, such as the `qr-image` module. + * + * @return A URL suitable for use with the Google Authenticator. + * @see https://github.com/google/google-authenticator/wiki/Key-Uri-Format + */ +export function otpauthURL(options: OtpauthURLOptions): string; diff --git a/types/speakeasy/speakeasy-tests.ts b/types/speakeasy/speakeasy-tests.ts index c807e568a3..587b95fd55 100644 --- a/types/speakeasy/speakeasy-tests.ts +++ b/types/speakeasy/speakeasy-tests.ts @@ -3,34 +3,39 @@ import * as speakeasy from 'speakeasy'; speakeasy.generate_key({length: 20, google_auth_qr: true}); // normal use. -speakeasy.hotp({key: 'secret', counter: 582}); +speakeasy.hotp({secret: 'secret', counter: 582}); // use a custom length. -speakeasy.hotp({key: 'secret', counter: 582, length: 8}); +speakeasy.hotp({secret: 'secret', counter: 582, length: 8}); // use a custom encoding. -speakeasy.hotp({key: 'AJFIEJGEHIFIU7148SF', counter: 147, encoding: 'base32'}); +speakeasy.hotp({secret: 'AJFIEJGEHIFIU7148SF', counter: 147, encoding: 'base32'}); // normal use. -speakeasy.totp({key: 'secret'}); +speakeasy.totp({secret: 'secret'}); // use a custom time step. -speakeasy.totp({key: 'secret', step: 60}); +speakeasy.totp({secret: 'secret', step: 60}); // use a custom time. -speakeasy.totp({key: 'secret', time: 159183717}); +speakeasy.totp({secret: 'secret', time: 159183717}); // use a initial time. -speakeasy.totp({key: 'secret', initial_time: 4182881485}); +speakeasy.totp({secret: 'secret', initial_time: 4182881485}); -speakeasy.generateSecret({ +const otpauth_url: string = speakeasy.generateSecret({ length: 3, name: 'testName', qr_codes: true, google_auth_qr: true, otpauth_url: true, symbols: true -}); +}).otpauth_url; + +const otpauth_url2: string | undefined = speakeasy.generateSecret({ + length: 3, + name: 'testName', +}).otpauth_url; speakeasy.generateSecretASCII(5, true); @@ -39,10 +44,10 @@ speakeasy.otpauthURL({ label: 'otpauthURLLength' }); -speakeasy.totp.verify({secret: "secret", token: "123456"}) +speakeasy.totp.verify({secret: "secret", token: "123456"}); -speakeasy.totp.verifyDelta({secret: "secret", token: "123456"}) +speakeasy.totp.verifyDelta({secret: "secret", token: "123456"}); -speakeasy.hotp.verify({secret: "secret", token: "123456", counter: 123}) +speakeasy.hotp.verify({secret: "secret", token: "123456", counter: 123}); -speakeasy.hotp.verifyDelta({secret: "secret", token: "123456", counter: 123}) +speakeasy.hotp.verifyDelta({secret: "secret", token: "123456", counter: 123}); diff --git a/types/speakeasy/tsconfig.json b/types/speakeasy/tsconfig.json index e27d664bc4..7831b0837f 100644 --- a/types/speakeasy/tsconfig.json +++ b/types/speakeasy/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/speakeasy/tslint.json b/types/speakeasy/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/speakeasy/tslint.json +++ b/types/speakeasy/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index 68ad432585..d690398d0c 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -4,6 +4,7 @@ // Triston Jones // Paul Selden // Max Bause +// Timur Ramazanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -455,6 +456,8 @@ export class AccountResponse implements AccountRecord { export class Asset { static native(): Asset; + static fromOperation(xdr: xdr.Asset): Asset; + constructor(code: string, issuer: string) getCode(): string; @@ -462,6 +465,7 @@ export class Asset { getAssetType(): 'native' | 'credit_alphanum4' | 'credit_alphanum12'; isNative(): boolean; equals(other: Asset): boolean; + toXDRObject(): xdr.Asset; code: string; issuer: string; diff --git a/types/string-replace-webpack-plugin/index.d.ts b/types/string-replace-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..b62c43e448 --- /dev/null +++ b/types/string-replace-webpack-plugin/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for string-replace-webpack-plugin 0.1 +// Project: https://github.com/jamesandersen/string-replace-webpack-plugin +// Definitions by: Rongjian Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin, RuleSetUse } from "webpack"; + +export = StringReplacePlugin; + +declare class StringReplacePlugin extends Plugin { + static replace( + options: StringReplacePlugin.Options, + /** + * loaders to follow the replacement + */ + nextLoaders?: string + ): RuleSetUse; + static replace( + /** + * loaders to apply prior to the replacement + */ + prevLoaders: string, + options: StringReplacePlugin.Options, + /** + * loaders to follow the replacement + */ + nextLoaders?: string + ): RuleSetUse; +} + +declare namespace StringReplacePlugin { + interface Options { + replacements: ReplacementItem[]; + } + + interface ReplacementItem { + /** + * a regex to match against the file contents + */ + pattern: RegExp; + /** + * an ECMAScript string replacement function + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter + */ + replacement: (substring: string, ...args: any[]) => string; + } +} diff --git a/types/string-replace-webpack-plugin/string-replace-webpack-plugin-tests.ts b/types/string-replace-webpack-plugin/string-replace-webpack-plugin-tests.ts new file mode 100644 index 0000000000..b4b0d5304a --- /dev/null +++ b/types/string-replace-webpack-plugin/string-replace-webpack-plugin-tests.ts @@ -0,0 +1,17 @@ +import StringReplacePlugin = require('string-replace-webpack-plugin'); + +StringReplacePlugin.replace('babel-loader', { + replacements: [ + { + // Taken from: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter + pattern: /([^\d]*)(\d*)([^\w]*)/, + replacement: (match, p1, p2, p3, offset, string) => { + // p1 is nondigits, p2 digits, and p3 non-alphanumerics + return [p1, p2, p3].join(' - '); + } + } + ] +}); + +new StringReplacePlugin(); diff --git a/types/string-replace-webpack-plugin/tsconfig.json b/types/string-replace-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..0c92ee657b --- /dev/null +++ b/types/string-replace-webpack-plugin/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "string-replace-webpack-plugin-tests.ts"] +} diff --git a/types/string-replace-webpack-plugin/tslint.json b/types/string-replace-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/string-replace-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/stripe-checkout/index.d.ts b/types/stripe-checkout/index.d.ts index c84fdeeb1d..d0e283504c 100644 --- a/types/stripe-checkout/index.d.ts +++ b/types/stripe-checkout/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Chris Wrench // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface StripeCheckoutStatic { configure(options: StripeCheckoutOptions): StripeCheckoutHandler; @@ -16,7 +16,8 @@ interface StripeCheckoutHandler { interface StripeCheckoutOptions { key?: string; - token?(token: stripe.StripeCardTokenResponse): void; + token?(token: stripe.Token): void; + source?(source: stripe.Source): void; image?: string; name?: string; description?: string; diff --git a/types/stripe-checkout/stripe-checkout-tests.ts b/types/stripe-checkout/stripe-checkout-tests.ts index 6cd221debf..e310c2e7d0 100644 --- a/types/stripe-checkout/stripe-checkout-tests.ts +++ b/types/stripe-checkout/stripe-checkout-tests.ts @@ -1,9 +1,9 @@ // Test the minimum amount of configuration required. let handler = StripeCheckout.configure({ - key: "my-secret-key", - token: (token: stripe.StripeTokenResponse) => { - console.log(token.id); - } + key: "my-secret-key", + token: (token: stripe.Token) => { + console.log(token.id); + } }); handler.open(); @@ -12,10 +12,13 @@ handler.close(); // Test all configuration options. const options: StripeCheckoutOptions = { - key: "my-secret-key", - token: (token: stripe.StripeTokenResponse) => { - console.log(token.id); - }, + key: "my-secret-key", + token: (token: stripe.Token) => { + console.log(token.id); + }, + source: (src: stripe.Source) => { + console.log(src.id); + }, image: "http://placehold.it/128x128", name: "Definitely Typed", description: "A DefinitelyTyped test for Stripe Checkout", diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index c6210edf91..f436b8d490 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -82,7 +82,7 @@ export interface ThemedStyledFunction { strings: TemplateStringsArray, ...interpolations: Array>> ): StyledComponentClass

    ; - attrs = {}>( + attrs & { [others: string]: any; } = {}>( attrs: Attrs

    , ): ThemedStyledFunction, T, DiffBetween>; } diff --git a/types/styled-components/macro.d.ts b/types/styled-components/macro.d.ts new file mode 100644 index 0000000000..08cee96a96 --- /dev/null +++ b/types/styled-components/macro.d.ts @@ -0,0 +1,2 @@ +export { default } from '.'; +export * from '.'; diff --git a/types/styled-components/styled-components-tests.tsx b/types/styled-components/test/index.tsx similarity index 98% rename from types/styled-components/styled-components-tests.tsx rename to types/styled-components/test/index.tsx index 8adfb03307..7f2197389f 100644 --- a/types/styled-components/styled-components-tests.tsx +++ b/types/styled-components/test/index.tsx @@ -312,6 +312,12 @@ const AttrsInput = styled.input.attrs({ padding: ${props => props.padding}; `; +// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30042 +const AttrsWithOnlyNewProps = styled.h2.attrs({ as: 'h1' })` + color: ${props => props.as === 'h1' ? 'red' : 'blue'}; + font-size: ${props => props.as === 'h1' ? 2 : 1}; +`; + /** * component type */ diff --git a/types/styled-components/test/macro.tsx b/types/styled-components/test/macro.tsx new file mode 100644 index 0000000000..59acd127a3 --- /dev/null +++ b/types/styled-components/test/macro.tsx @@ -0,0 +1,20 @@ +import styled, { createGlobalStyle } from 'styled-components/macro'; + +// Check that the default export works. +const TitleFromMacro = styled.h1` + font-size: 1.5em; + text-align: center; + color: palevioletred; +`; + +// Check that named exports work as well. +const GlobalStyleFromMacro = createGlobalStyle` + @font-face { + font-family: 'Operator Mono'; + src: url('../fonts/Operator-Mono.ttf'); + } + + body { + margin: 0; + } +`; diff --git a/types/styled-components/tsconfig.json b/types/styled-components/tsconfig.json index 26cb1835d5..22af0d4a13 100644 --- a/types/styled-components/tsconfig.json +++ b/types/styled-components/tsconfig.json @@ -13,5 +13,10 @@ "typeRoots": ["../"], "types": [] }, - "files": ["index.d.ts", "styled-components-tests.tsx"] + "files": [ + "index.d.ts", + "macro.d.ts", + "test/index.tsx", + "test/macro.tsx" + ] } diff --git a/types/styled-system/dist/styles.d.ts b/types/styled-system/dist/styles.d.ts index ab045b3b4b..5851c51f79 100644 --- a/types/styled-system/dist/styles.d.ts +++ b/types/styled-system/dist/styles.d.ts @@ -192,7 +192,7 @@ export interface RatioProps { export function ratio(...args: any[]): any; -export type VerticleAlignValue = +export type VerticalAlignValue = | "baseline" | "sub" | "super" @@ -203,13 +203,13 @@ export type VerticleAlignValue = | "bottom" | string | number; -export type ResponsiveVerticleAlignValue = ResponsiveValue; +export type ResponsiveVerticalAlignValue = ResponsiveValue; -export interface VerticleAlignProps { - verticalAlign?: ResponsiveVerticleAlignValue; +export interface VerticalAlignProps { + verticalAlign?: ResponsiveVerticalAlignValue; } -export function verticleAlign(...args: any[]): any; +export function verticalAlign(...args: any[]): any; /** * Flexbox diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index d9c386242c..2511fbb99c 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -7,6 +7,7 @@ // Eloy Durán // Matthieu Vachon // Adam Lavin +// Joachim Schuler // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index c0f9ba9ded..756dd0c039 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -121,6 +121,8 @@ import { VariantArgs, ButtonStyleProps, MixedProps, + VerticalAlignProps, + verticalAlign } from "styled-system"; // tslint:disable-next-line:strict-export-declare-modifiers @@ -166,7 +168,8 @@ interface BoxProps BackgroundSizeProps, ColorStyleProps, TextStyleProps, - MixedProps { + MixedProps, + VerticalAlignProps { boxStyle?: string; } const Box: React.ComponentType = styled` @@ -213,6 +216,7 @@ const Box: React.ComponentType = styled` ${textStyle} ${colorStyle} ${mixed} + ${verticalAlign} `; Box.defaultProps = { @@ -449,6 +453,8 @@ const test = () => ( backgroundPosition="center" backgroundRepeat="repeat-x" /> + // verticalAlign +

    diff --git a/types/styled-theming/index.d.ts b/types/styled-theming/index.d.ts new file mode 100644 index 0000000000..fab32a7617 --- /dev/null +++ b/types/styled-theming/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for styled-theming 2.2 +// Project: https://github.com/styled-components/styled-theming#readme +// Definitions by: Arjan Jassal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +declare function theme(name: string, values: theme.ThemeMap): theme.ThemeSet; + +declare namespace theme { + type ThemeValueFn = (props: object) => string; + type ThemeValue = string | ThemeValueFn; + + interface ThemeMap { + [key: string]: ThemeValue; + } + + interface VariantMap { + [key: string]: ThemeMap; + } + + type ThemeSet = (props: object) => string; + type VariantSet = (props: object) => string; + + function variants( + name: string, + prop: string, + values: VariantMap + ): VariantSet; +} + +export = theme; diff --git a/types/styled-theming/styled-theming-tests.ts b/types/styled-theming/styled-theming-tests.ts new file mode 100644 index 0000000000..2d9e947009 --- /dev/null +++ b/types/styled-theming/styled-theming-tests.ts @@ -0,0 +1,13 @@ +import theme from "styled-theming"; + +const textColor = theme("mode", { + dark: "white", + light: "black" +}); + +const backgroundColor = theme.variants("mode", "variant", { + default: { light: "gray", dark: "darkgray" }, + primary: { light: "blue", dark: "darkblue" }, + success: { light: "green", dark: "darkgreen" }, + warning: { light: "orange", dark: "darkorange" } +}); diff --git a/types/styled-theming/tsconfig.json b/types/styled-theming/tsconfig.json new file mode 100644 index 0000000000..57714000f6 --- /dev/null +++ b/types/styled-theming/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "esModuleInterop": true, + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "styled-theming-tests.ts"] +} diff --git a/types/styled-theming/tslint.json b/types/styled-theming/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/styled-theming/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/swiper/index.d.ts b/types/swiper/index.d.ts index 7243ec2a10..9e77516978 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for Swiper 4.2 // Project: https://github.com/nolimits4web/Swiper -// Definitions by: Sebastián Galiano , Luca Trazzi , Eugene Matseruk , Luiz M. +// Definitions by: Sebastián Galiano +// Luca Trazzi +// Eugene Matseruk +// Luiz M. +// Justin Abene // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -1047,7 +1051,7 @@ export default class Swiper { * @param runCallbacks Set it to false (by default it is true) and transition will * not produce transition events. */ - slideNext(speed: number, runCallbacks: boolean): void; + slideNext(speed?: number, runCallbacks?: boolean): void; /** * Run transition to previous slide. diff --git a/types/tern/index.d.ts b/types/tern/index.d.ts new file mode 100644 index 0000000000..ef01c0e289 --- /dev/null +++ b/types/tern/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for tern 0.22 +// Project: https://github.com/ternjs/tern +// Definitions by: Nikolaj Kappler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// IMPORTANT Note: These type definitions adhere strictly to the official documentation, +// which does not seem to match the implementation exactly in some places. +// As a result, these type definitions may lack some parts of the API that are actually exposed. +// The type definitions are at a point where they are usable and match the documentation, +// thus if you want to use undocumented APIs, you should extends these definitions with +// ambient declaration merging: https://www.typescriptlang.org/docs/handbook/declaration-merging.html + +export * from "./lib/tern"; +export * from "./lib/infer"; diff --git a/types/tern/lib/infer/index.d.ts b/types/tern/lib/infer/index.d.ts new file mode 100644 index 0000000000..58e83ea1c7 --- /dev/null +++ b/types/tern/lib/infer/index.d.ts @@ -0,0 +1,218 @@ +import * as ESTree from "estree"; +export { }; + +// #### Context #### +interface ContextConstructor { + new(defs: any[]): Context; +} +export const Context: ContextConstructor; +export interface Context { + topScope: Scope; + /** The primitive number type. */ + num: Type; + /** The primitive string type. */ + str: Type; + /** The primitive boolean type. */ + bool: Type; +} +export function cx(): Context; +export function withContext(context: Context, f: () => void): void; + +// #### Analysis #### +/** Parse a piece of code for use by Tern. Will automatically fall back to the error-tolerant parser if the regular parser can’t parse the code. */ +export function parse(text: string, options?: {}): ESTree.Program; +/** + * Analyze a syntax tree. `name` will be used to set the origin of types, properties, and variables produced by this code. + * The optional `scope` argument can be used to specify a scope in which the code should be analyzed. + * It will default to the top-level scope. + */ +export function analyze(ast: ESTree.Program, name: string, scope?: Scope): void; +/** + * Purges the types that have one of the origins given from the context. `start` and `end` can be given to only purge + * types that occurred in the source code between those offsets. This is not entirely precise — the state of the + * context won’t be back where it was before the file was analyzed — but it prevents most of the + * noticeable inaccuracies that re-analysis tends to produce. + */ +export function purgeTypes(origins: string[], start?: number, end?: number): void; +/** + * Cleaning up variables is slightly trickier than cleaning up types. This does a first pass over the given scope, + * and marks variables defined by the given origins. This is indended to be followed by a call to `analyze` and then a call to `purgeMarkedVariables`. + */ +export function markVariablesDefinedBy(scope: Scope, origins: string[], start?: number, end?: number): void; +/** Purges variables that were marked by a call to markVariablesDefinedBy and not re-defined in the meantime. */ +export function purgeMarkedVariables(): void; + +// #### Types #### +interface ObjConstructor { + new(proto: object | true | null, name?: string): Obj; +} +/** Constructor for the type that represents JavaScript objects. `proto` may be another object, or `true` as a short-hand for `Object.prototype`, or `null` for prototype-less objects. */ +export const Obj: ObjConstructor; +export interface Obj extends Type { + /** The prototype of the object, or null. */ + proto: any; + /** An object mapping the object’s known properties to AVals. Don’t manipulate this directly (ever), only use it if you have to iterate over the properties. */ + props: Readonly<{ + [key: string]: AVal; + }>; + /** Looks up the AVal associated with the given property, or returns null if it doesn’t exist. */ + hasProp(prop: string): AVal | null; + /** Looks up the given property, or defines it if it did not yet exist (in which case it will be associated with the given AST node). */ + defProp(prop: string, originNode?: ESTree.Node): AVal; +} + +interface FnConstructor { + new(name: string | undefined, self: AVal, args: AVal[], argNames: string[], retval: AVal): Fn; +} +/** Constructor for the type that implements functions. Inherits from `Obj`. The `AVal` types are used to track the input and output types of the function. */ +export const Fn: FnConstructor; +export type Fn = Obj; + +interface ArrConstructor { + /** Constructor that creates an array type with the given content type. */ + new(contentType: AVal): Arr; +} +export const Arr: ArrConstructor; +export type Arr = Obj; + +export interface Type extends AVal { + /** The name of the type, if any. */ + name: string; + /** The origin file of the type. */ + origin: string; + /** + * The syntax node that defined the type. Only present for object and function types, + * and even for those it may be missing (if the type was created by a type definition file, + * or synthesized in some other way). + */ + originNode?: ESTree.Node; + /** Return a string that describes the type. maxDepth indicates the depth to which inner types should be shown. */ + toString(maxDepth: number): string; + /** Get an `AVal` that represents the named property of this type. */ + getProp(prop: string): AVal; + /** Call the given function for all properties of the object, including properties that are added in the future. */ + forAllProps(f: (prop: string, val: AVal, local: boolean) => void): void; +} + +// #### Abstract Values #### + +interface AValConstructor { + new(): AVal; +} +export const AVal: AValConstructor; +export interface AVal { + /** + * Add a type to this abstract value. If the type is already in there, + * this is a no-op. weight can be given to give this type a non-default + * weight, which is mostly useful when adding a provisionary type that + * should be overridden later if a real type is found. The default weight + * is 100, and passing a weight lower than that will make the type + * assignment “weak”. + */ + addType(type: Type, weight?: number): void; + /** + * Sets this AVal to propagate all types it receives to the given + * constraint. This is the mechanism by which types are propagated + * through the type graph. + */ + propagate(target: Constraint): void; + /** Queries whether the AVal _currently_ holds the given type. */ + hasType(type: Type): boolean; + /** Queries whether the AVal is empty. */ + isEmpty(): boolean; + /** + * Asks the abstract value for its current type. May return `null` + * when there is no type, or conflicting types are present. When + * `guess` is true or not given, an empty AVal will try to use + * heuristics based on its propagation edges to guess a type. + */ + getType(guess?: boolean): Type | null; + /** + * Asks the AVal if it contains a function type. Useful when + * you aren’t interested in other kinds of types. + */ + getFunctionType(): Type | undefined; + /** + * Abstract values that are used to represent variables + * or properties will have, when possible, an `originNode` + * property pointing to an AST node. + */ + originNode?: ESTree.Node; +} + +export const ANull: ANull; +export interface ANull extends AVal { + addType(): void; + propagate(target: never): void; + hasType(): false; + isEmpty(): true; + getFunctionType(): undefined; + getType(): null; + originNode: undefined; +} + +// #### Constraints #### +interface ConstraintConstructor { + new(methods: { [key: string]: any }): { new(): Constraint }; +} +/** + * This is a constructor-constructor for constraints. It’ll create a + * constructor with all the given methods copied into its prototype, + * which will run its construct method on its arguments when instantiated. + */ +export const constraint: ConstraintConstructor; +export interface Constraint extends AVal { + /** May return a type that `getType` can use to “guess” its type based on the fact that it propagates to this constraint. */ + typeHint?(): Type | undefined; + /** May return a string when this constraint is indicative of the presence of a specific property in the source AVal. */ + propHint?(): string | undefined; +} + +// #### Scopes #### +interface ScopeConstructor { + new(parent?: Scope): Scope; +} +export const Scope: ScopeConstructor; +export interface Scope extends Obj { + /** + * Ensures that this scope or some scope above it has a property by the given name + * (defining it in the top scope if it is missing), and, if the property doesn’t + * already have an `originNode`, assigns the given node to it. + */ + defVar(name: string, originNode: ESTree.Node): AVal; +} + +// #### Utilities #### +/** + * Searches the given syntax tree for an expression that ends at the given `end` offset and, + * if `start` is given, starts at the given start offset. `scope` can be given to override the + * outer scope, which defaults to the context’s top scope. Will return a `{node, state}` + * object if successful, where `node` is AST node, and `state` is the scope at that point. + * Returns `null` if unsuccessful. + */ +export function findExpressionAt(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null; +/** + * Similar to `findExpressionAt`, except that it will return the innermost expression + * node that spans the given range, rather than only exact matches. + */ +export function findExpressionAround(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null; +/** Similar to `findExpressionAround`, except that it use the same AST walker as `findExpressionAt`. */ +export function findClosestExpression(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null; +/** Determine an expression for the given node and scope (as returned by the functions above). Will return an `AVal` or plain `Type`. */ +export function expressionType(expr: { node: ESTree.Node, state: Scope }): AVal | Type; +/** Find the scope at a given position in the syntax tree. The `scope` parameter can be used to override the scope used for code that isn’t wrapped in any function. */ +export function scopeAt(ast: ESTree.Program, pos: number, scope?: Scope): Scope; +/** + * Will traverse the given syntax tree, using `scope` as the starting scope, looking for references to variable `name` that + * resolve to scope `refScope`, and call `f` with the node of the reference and its local scope for each of them. + */ +export function findRefs(ast: ESTree.Program, scope: Scope, name: string, refScope: Scope, f: (Node: ESTree.Node, Scope: Scope) => void): void; +/** + * Analogous to `findRefs`, but used to look for references to a specific property instead. Whereas `findRefs` + * is precise, this is dependent on type inference, and thus can not be relied on to be precise. + */ +export function findPropRefs(ast: ESTree.Program, scope: Scope, objType: Obj, propName: string, f: (Node: ESTree.Node) => void): void; +/** Whenever infer guesses a type through fuzzy heuristics (through `getType` or `expressionType`), it sets a flag. `didGuess` tests whether the guessing flag is set. */ +export function didGuess(): boolean; +/** Whenever infer guesses a type through fuzzy heuristics (through `getType` or `expressionType`), it sets a flag. `resetGuessing` resets the guessing flag. */ +export function resetGuessing(val?: boolean): void; diff --git a/types/tern/lib/tern/index.d.ts b/types/tern/lib/tern/index.d.ts new file mode 100644 index 0000000000..ee51a79119 --- /dev/null +++ b/types/tern/lib/tern/index.d.ts @@ -0,0 +1,500 @@ +import * as ESTree from "estree"; +import { Scope, Type } from "../infer"; + +export { }; + +// #### Programming interface #### +export type ConstructorOptions = CtorOptions & (SyncConstructorOptions | ASyncConstructorOptions); + +interface CtorOptions { + /** The definition objects to load into the server’s environment. */ + defs?: Def[]; + /** The ECMAScript version to parse. Should be either 5 or 6. Default is 6. */ + ecmaVersion?: 5 | 6; + /** Indicates the maximum amount of milliseconds to wait for an asynchronous getFile before giving up on it. Defaults to 1000. */ + fetchTimeout?: number; + /** Specifies the set of plugins that the server should load. The property names of the object name the plugins, and their values hold options that will be passed to them. */ + plugins?: { [key: string]: object }; +} + +interface SyncConstructorOptions { + /** Indicates whether `getFile` is asynchronous. Default is `false`. */ + async?: false; + /** + * Provides a way for the server to try and fetch the content of files. + * Depending on the `async` option, this is either a function that takes a filename and returns a string (when not `async`), or + * a function that takes a `filename` and a `callback`, and calls the callback with an optional `error` as the first argument, + * and the `content` string (if no error) as the second. + */ + getFile?(filename: string): string; +} + +interface ASyncConstructorOptions { + /** Indicates whether `getFile` is asynchronous. Default is `false`. */ + async: true; + /** + * Provides a way for the server to try and fetch the content of files. + * Depending on the `async` option, this is either a function that takes a filename and returns a string (when not `async`), or + * a function that takes a `filename` and a `callback`, and calls the callback with an optional `error` as the first argument, + * and the `content` string (if no error) as the second. + */ + getFile?(filename: string, callback: (error: Error | undefined, content?: string) => void): void; +} + +interface TernConstructor { + new(options?: ConstructorOptions): Server; +} + +export const Server: TernConstructor; + +export interface Server { + /** + * Add a set of type definitions to the server. If `atFront` is true, they will be added before all other + * existing definitions. Otherwise, they are added at the back. + */ + addDefs(defs: Def[], atFront?: boolean): void; + + /** + * Register a file with the server. Note that files can also be included in requests. When using this + * to automatically load a dependency, specify the name of the file (as Tern knows it) as the third + * argument. That way, the file is counted towards the dependency budget of the root of its dependency graph. + */ + addFile(name: string, text?: string, parent?: string): void; + + /** Unregister a file. */ + delFile(name: string): void; + + /** + * Delete a set of type definitions from the server, by providing the name, taken from + * `defs[!name]` property from the definitions. If that property is not available in the + * current type definitions, it can’t be removed. + */ + deleteDefs(name: string): void; + + /** Forces all files to be fetched an analyzed, and then calls the callback function. */ + flush(callback: () => void): void; + + /** Load a server plugin (or don’t do anything, if the plugin is already loaded). */ + loadPlugin(name: string, options: object): void; + + /** Unregister an event handler. */ + off(eventType: K, handler: Events[K]): void; + + /** Register an event handler for the named type of event. */ + on(eventType: K, handler: Events[K]): void; + + /** + * Perform a request. `doc` is a (parsed) JSON document as described in the protocol documentation. + * The `callback` function will be called when the request completes. If an `error` occurred, + * it will be passed as a first argument. Otherwise, the `response` (parsed) JSON object will be passed as second argument. + * + * When the server hasn’t been configured to be asynchronous, the callback will be called before request returns. + */ + request( + doc: D & { query?: Q }, + callback: ( + error: Error | undefined, + response: (D extends { query: undefined } ? {} : D extends { query: Query } ? QueryResult : {}) | undefined + ) => void + ): void; +} + +// #### JSON Protocol #### + +type QueryResult = QueryRegistry[Q["type"]]["result"]; + +type Query = QueryRegistry[keyof QueryRegistry]["query"]; + +export interface QueryRegistry { + completions: { + query: CompletionsQuery, + result: CompletionsQueryResult + }; + type: { + query: TypeQuery, + result: TypeQueryResult + }; + definition: { + query: DefinitionQuery, + result: DefinitionQueryResult + }; + documentation: { + query: DocumentationQuery; + result: DocumentationQueryResult; + }; + refs: { + query: RefsQuery; + result: RefsQueryResult; + }; + rename: { + query: RenameQuery, + result: RenameQueryResult + }; + properties: { + query: PropertiesQuery, + result: PropertiesQueryResult + }; + files: { + query: FilesQuery, + result: FilesQueryResult + }; +} + +export interface Def { + [key: string]: string | Def; +} + +export interface Document { + query?: Query; + files?: File[]; + timeout?: number; +} + +export interface File { + name: string; + text: string; + scope: Scope; + ast: ESTree.Program; + type?: "full" | "part" | "delete"; +} + +export interface BaseQuery { + type: string; + lineCharPositions?: boolean; + docFormat?: "full"; +} + +interface Position { + ch: number; + line: number; +} + +/** Asks the server for a set of completions at the given point. */ +export interface CompletionsQuery extends BaseQuery { + /** Asks the server for a set of completions at the given point. */ + type: "completions"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location to complete at. */ + end: number | Position; + /** Whether to include the types of the completions in the result data. Default `false` */ + types?: boolean; + /** Whether to include the distance (in scopes for variables, in prototypes for properties) between the completions and the origin position in the result data. Default `false` */ + depths?: boolean; + /** Whether to include documentation strings in the result data. Default `false` */ + docs?: boolean; + /** Whether to include urls in the result data. Default `false` */ + urls?: boolean; + /** Whether to include origin files (if found) in the result data. Default `false` */ + origins?: boolean; + /** When on, only completions that match the current word at the given point will be returned. Turn this off to get all results, so that you can filter on the client side. Default `true` */ + filter?: boolean; + /** Whether to use a case-insensitive compare between the current word and potential completions. Default `false` */ + caseInsensitive?: boolean; + /** When completing a property and no completions are found, Tern will use some heuristics to try and return some properties anyway. Set this to `false` to turn that off. Default `true` */ + guess?: boolean; + /** Determines whether the result set will be sorted. Default `true` */ + sort?: boolean; + /** + * When disabled, only the text before the given position is considered part of the word. When enabled (the default), + * the whole variable name that the cursor is on will be included. Default `true` + */ + expandWordForward?: boolean; + /** Whether to ignore the properties of `Object.prototype` unless they have been spelled out by at least two characters. Default `true` */ + omitObjectPrototype?: boolean; + /** Whether to include JavaScript keywords when completing something that is not a property. Default `false` */ + includeKeywords?: boolean; + /** If completions should be returned when inside a literal. Default `true` */ + inLiteral?: boolean; +} + +interface CompletionsQueryResult { + /** start offsets of the word that was completed */ + start: number | Position; + /** end offsets of the word that was completed */ + end: number | Position; + /** whether the completion is for a property or a variable */ + isProperty: boolean; + // TODO depends on completionsquery settings -> conditional types? + /** + * array of completions. When one of the `types`, `depths`, `docs`, `urls`, or `origins` + * options was passed, the array will hold objects with a `name` property (the completion text), + * and, depending on the options, `type`, `depth`, `doc`, `url`, and `origin` properties. + * When none of these options are enabled, the result array will hold plain strings. + */ + completions: string[] | Array<{ + name: string, + type?: string, + depth?: number, + doc?: string, + url?: string, + origin?: string + }>; +} + +/** Query the type of something. */ +export interface TypeQuery extends BaseQuery { + /** Query the type of something. */ + type: "type"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; + /** + * Set to `true` when you are interested in a function type. + * This will cause function types to win when something has multiple types. + * Default `false` + */ + preferFunction?: boolean; + /** + * Determines how deep the type string must be expanded. + * Nested objects will only display property types up to this depth, + * and be represented by their type name or a representation showing + * only property names below it. Default `0` + */ + depth?: number; +} + +interface TypeQueryResult { + /** A description of the type of the value. May be "?" when no type was found. */ + type: string; + /** Whether the given type was guessed, or should be considered reliable. */ + guess: boolean; + /** The name associated with the type. */ + name?: string; + /** When the inspected expression was an identifier or a property access, this will hold the name of the variable or property. */ + exprName?: string; + /** If the type had documentation associated with it, these will also be returned. */ + doc?: string; + /** If the type had urls associated with it, these will also be returned. */ + url?: string; + /** If the type had origin information associated with it, these will also be returned. */ + origin?: string; +} + +/** + * Asks for the definition of something. This will try, for a variable or property, + * to return the point at which it was defined. If that fails, or the chosen + * expression is not an identifier or property reference, it will try to return + * the definition site of the type the expression has. If no type is found, or the + * type is not an object or function (other types don’t store their definition site), + * it will fail to return useful information. + */ +export interface DefinitionQuery extends BaseQuery { + /** + * Asks for the definition of something. This will try, for a variable or property, + * to return the point at which it was defined. If that fails, or the chosen + * expression is not an identifier or property reference, it will try to return + * the definition site of the type the expression has. If no type is found, or the + * type is not an object or function (other types don’t store their definition site), + * it will fail to return useful information. + */ + type: "definition"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; +} + +interface DefinitionQueryResult { + /** The start position of the expression. */ + start?: number | Position; + /** The end position of the expression. */ + end?: number | Position; + /** The file in which the definition was defined. */ + file?: string; + /** A slice of the code in front of the definition Can be used to find a definition’s location in a modified file. */ + context?: string; + /** The offset from the start of the context to the actual definition. Can be used to find a definition’s location in a modified file. */ + contextOffset?: number; + /** If the definition had documentation associated with it, these will also be returned. */ + doc?: string; + /** If the definition had urls associated with it, these will also be returned. */ + url?: string; + /** If the definition had origin information associated with it, these will also be returned. */ + origin?: string; +} + +/** Get the documentation string and URL for a given expression, if any. */ +export interface DocumentationQuery extends BaseQuery { + /** Get the documentation string and URL for a given expression, if any. */ + type: "documentation"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; +} + +interface DocumentationQueryResult { + /** The documentation string of the definition or value, if any. */ + doc?: string; + /** The url of the definition or value, if any. */ + url?: string; + /** The origin of the definition or value, if any. */ + origin?: string; +} + +/** Used to find all references to a given variable or property. */ +export interface RefsQuery extends BaseQuery { + /** Used to find all references to a given variable or property. */ + type: "refs"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; +} + +interface RefsQueryResult { + /** The name of the variable or property */ + name: string; + refs: Array<{ + file: string, + start: number | Position, + end: number | Position + }>; + /** for variables: a type property holding either "global" or "local". */ + type?: "global" | "local"; +} + +/** Rename a variable in a scope-aware way. */ +export interface RenameQuery extends BaseQuery { + /** Rename a variable in a scope-aware way. */ + type: "rename"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the variable. */ + end: number | Position; + /** Specify the location of the variable. */ + start?: number | Position; + /** The new name of the variable */ + newName: string; +} + +/** + * Returns an object whose `changes` property holds an array of `{file, start, end, text}` objects, which + * give the changes that must be performed to apply the rename. The client is responsible for doing the actual modification. + */ +interface RenameQueryResult { + /** Array of changes that must be performed to apply the rename. The client is responsible for doing the actual modification. */ + changes: Array<{ + file: string, + start: number | Position, + end: number | Position, + text: string + }>; +} + +/** Get a list of all known object property names (for any object). */ +export interface PropertiesQuery extends BaseQuery { + /** Get a list of all known object property names (for any object). */ + type: "properties"; + /** Causes the server to only return properties that start with the given string. */ + prefix?: string; + /** Whether the result should be sorted. Default `true` */ + sort?: boolean; +} + +interface PropertiesQueryResult { + /** The property names. */ + completions: string[]; +} + +/** Get the files that the server currently holds in its set of analyzed files. */ +export interface FilesQuery extends BaseQuery { + /** Get the files that the server currently holds in its set of analyzed files. */ + type: "files"; + docFormat?: never; + lineCharPositions?: never; +} + +interface FilesQueryResult { + /** The file names. */ + files: string[]; +} + +export interface Events { + /** When the server throws away its current analysis data and starts a fresh run. */ + reset(): void; + /** Before analyzing a file. file is an object holding {name, text, scope} properties. */ + beforeLoad(file: File): void; + /** After analyzing a file. */ + afterLoad(file: File): void; + /** + * Will be run right before a file is parsed, and passed the given text and options. If a handler + * returns a new text value, the origin text will be overriden. This is useful for + * instance when a plugin is able to extract JavaScript content from an HTML file. + */ + preParse(text: string, options: object): string | void; + /** Run right after a file is parsed, and passed the parse tree and the parsed file as arguments. */ + postParse(ast: ESTree.Program, text: string): void; + /** Run right before the type inference pass, passing the syntax tree and a scope object. */ + preInfer(ast: ESTree.Program, scope: Scope): void; + /** Run after the type inference pass. */ + postInfer(ast: ESTree.Program, scope: Scope): void; + /** + * Run after Tern attempts to find the type at the position end in the given file. + * A handler may return either the given type (already calculated by Tern and earlier "typeAt" passes) + * or an alternate type to be used instead. This is useful when + * a plugin can provide a more helpful type than Tern (e.g. within comments). + */ + typeAt(file: File, end: Position, expr: ESTree.Node, type: Type): Type | void; + /** Run at the start of a completion query. May return a valid completion result to replace the default completion algorithm. */ + completion(file: File, query: Query): CompletionsQueryResult | void; +} + +export const version: string; + +// ###### Plugins ######## + +/** + * This can be used to register an initialization function for the plugin with the given name. + * A Tern server, when configured to load this plugin, will call this initialization function, + * passing in the server instance and the options specified for the plugin (if any). This is the + * place where you register event handlers on the server, add type definitions, load other + * plugins as dependencies, and/or initialize the plugin’s state. + * + * See the server’s [list of events](http://ternjs.net/doc/manual.html#events) for ways to wire up plugin behavior. + */ +export function registerPlugin(name: string, init: (server: Server, options?: ConstructorOptions) => void): void; + +interface Desc { + run(Server: Server, query: QueryRegistry[T]["query"], file?: File): QueryRegistry[T]["result"]; + takesfile?: boolean; +} + +/** + * Defines a new type of query with the server. The `desc` object is a property describing the request. + * It should at least have a `run` property, which holds a function fn(Server, query) that will + * be called to handle queries with a type property that matches the given `name`. It may also have + * a `takesFile` property which, if true, will cause the server to try and resolve the file on which + * the query operates (from its file property) and pass that (a {name, text, scope, ast} object) as + * a third argument to the run function. You will probably need to use the inference + * module’s API to do someting useful in this function. + * + * To be able to use this function and the `request` function in a useful way, you probably want + * to define an interface for the query and the result of the query and extend the interface `QueryRegistry` via + * [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) + * in the following manner: + * + * ```typescript + * declare module "tern/lib/tern" { + * interface QueryRegistry { + * [CustomQueryType]: { + * query: CustomQuery + * result: CustomQueryResult + * } + * } + * } + * ``` + * _Note that your query interface should extend_ `BaseQuery` _and that its_ `type` _property has to be spelled + * exactly like the key in the_ `QueryRegistry` _interface._ + */ +export function defineQueryType(name: T, desc: Desc): void; diff --git a/types/tern/test/tern.test.ts b/types/tern/test/tern.test.ts new file mode 100644 index 0000000000..87cfee1ee6 --- /dev/null +++ b/types/tern/test/tern.test.ts @@ -0,0 +1,55 @@ +import * as tern from "tern"; + +const server: tern.Server = null as any; + +server.request({ + query: { + type: "completions", + file: "", + end: 0 + } +}, (error, response) => { + if (response && response.isProperty) { + // + } +}); + +server.request({ +}, (error, response) => { + // $ExpectError + if (response && response.isProperty) { + // + } +}); + +declare module "tern/lib/tern" { + interface QueryRegistry { + someUnknownType: { + query: { + type: "someUnknownType" + }, + result: { + abc: boolean + } + }; + } +} + +server.request({ + query: { + type: "someUnknownType" + } +}, (error, response) => { + if (response && response.abc) { + // + } +}); + +server.request({ + query: undefined +}, (error, response) => { + // $ExpectError + if (response && response.isProperty) { + // + } +}); diff --git a/types/tern/tsconfig.json b/types/tern/tsconfig.json new file mode 100644 index 0000000000..24e87522b3 --- /dev/null +++ b/types/tern/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/tern/index.d.ts", + "lib/infer/index.d.ts", + "test/tern.test.ts" + ] +} \ No newline at end of file diff --git a/types/tern/tslint.json b/types/tern/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/tern/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/terser/index.d.ts b/types/terser/index.d.ts new file mode 100644 index 0000000000..44a3e1cdb7 --- /dev/null +++ b/types/terser/index.d.ts @@ -0,0 +1,648 @@ +// Type definitions for terser 3.8 +// Project: https://github.com/terser-js/terser +// Definitions by: JordiAnderl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import * as MOZ_SourceMap from "source-map"; + +export interface Tokenizer { + /** + * The type of this token. + * "comment1" and "comment2" are for single-line, respectively multi-line comments. + */ + type: "num" | "string" | "regexp" | "operator" | "punc" | "atom" | "name" | "keyword" | "comment1" | "comment2"; + + /** + * The name of the file where this token originated from. Useful when compressing multiple files at once to generate the proper source map. + */ + file: string; + + /** + * The "value" of the token. + * That's additional information and depends on the token type: "num", "string" and "regexp" tokens you get their literal value. + * - For "operator" you get the operator. + * - For "punc" it's the punctuation sign (parens, comma, semicolon etc). + * - For "atom", "name" and "keyword" it's the name of the identifier + * - For comments it's the body of the comment (excluding the initial "//" and "/*". + */ + value: string; + + /** + * The line number of this token in the original code. + * 1-based index. + */ + line: number; + + /** + * The column number of this token in the original code. + * 0-based index. + */ + col: number; + + /** + * Short for "newline before", it's a boolean that tells us whether there was a newline before this node in the original source. It helps for automatic semicolon insertion. + * For multi-line comments in particular this will be set to true if there either was a newline before this comment, or * * if this comment contains a newline. + */ + nlb: boolean; + + /** + * This doesn't apply for comment tokens, but for all other token types it will be an array of comment tokens that were found before. + */ + comments_before: string[]; +} + +export class AST_Node { + // The first token of this node + start: AST_Node; + + // The last token of this node + end: AST_Node; + + value?: string | number; + file?: string; + property?: string; + key?: string; + + transform(tt: TreeTransformer): AST_Toplevel; + + walk(walker: TreeWalker): void; +} + +export class AST_Toplevel extends AST_Node { + // Terser contains a scope analyzer which figures out variable/function definitions, references etc. + // You need to call it manually before compression or mangling. + // The figure_out_scope method is defined only on the AST_Toplevel node. + figure_out_scope(): void; + + // Get names that are optimized for GZip compression (names will be generated using the most frequent characters first) + compute_char_frequency(): void; + + mangle_names(): void; + + print(stream: OutputStream): void; + + print_to_string(options?: BeautifierOptions): string; +} + +export interface MinifyOptions { + spidermonkey?: boolean; + outSourceMap?: string; + sourceRoot?: string; + inSourceMap?: string; + fromString?: boolean; + warnings?: boolean; + mangle?: boolean | MangleOptions; + output?: OutputOptions; + compress?: boolean | CompressOptions; + nameCache?: {}; +} + +export interface MinifyOutput { + code: string; + map: string; + warnings?: string[]; + error?: string; + ast?: boolean | AST_Toplevel; +} + +export function minify(files: {}, options?: MinifyOptions): MinifyOutput; + +export interface ParseOptions { + // Default is false + strict?: boolean; + + // Input file name, default is null + filename?: string; + + // Default is null + toplevel?: AST_Toplevel; +} +export interface CompressOptions { + /** Replace `arguments[index]` with function parameter name whenever possible. */ + arguments?: boolean; + /** Various optimizations for boolean context, for example `!!a ? b : c → a ? b : c` */ + booleans?: boolean; + /** Collapse single-use non-constant variables, side effects permitting. */ + collapse_vars?: boolean; + /** Apply certain optimizations to binary nodes, e.g. `!(a <= b) → a > b,` attempts to negate binary nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc */ + comparisons?: boolean; + /** Apply optimizations for `if-s` and conditional expressions. */ + conditionals?: boolean; + /** Remove unreachable code */ + dead_code?: boolean; + /** + * Pass `true` to discard calls to console.* functions. + * If you wish to drop a specific function call such as `console.info` and/or retain side effects from function + * arguments after dropping the function call then use `pure_funcs` instead. + */ + drop_console?: boolean; + /** Remove `debugger;` statements */ + drop_debugger?: boolean; + /** Attempt to evaluate constant expressions */ + evaluate?: boolean; + /** Pass `true` to preserve completion values from terminal statements without `return`, e.g. in bookmarklets. */ + expression?: boolean; + global_defs?: object; + /** hoist function declarations */ + hoist_funs?: boolean; + /** + * Hoist properties from constant object and array literals into regular variables subject to a set of constraints. + * For example: `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props` works best with mangle enabled, + * the compress option passes set to 2 or higher, and the compress option toplevel enabled. + */ + hoist_props?: boolean; + /** Hoist var declarations (this is `false` by default because it seems to increase the size of the output in general) */ + hoist_vars?: boolean; + /** Optimizations for if/return and if/continue */ + if_return?: boolean; + /** + * Inline calls to function with simple/return statement + * - false -- same as `Disabled` + * - `Disabled` -- disabled inlining + * - `SimpleFunctions` -- inline simple functions + * - `WithArguments` -- inline functions with arguments + * - `WithArgumentsAndVariables` -- inline functions with arguments and variables + * - true -- same as `WithArgumentsAndVariables` + */ + inline?: boolean | InlineFunctions; + /** join consecutive `var` statements */ + join_vars?: boolean; + /** Prevents the compressor from discarding unused function arguments. You need this for code which relies on `Function.length` */ + keep_fargs?: boolean; + /** Pass true to prevent the compressor from discarding function names. Useful for code relying on `Function.prototype.name`. */ + keep_fnames?: boolean; + /** Pass true to prevent Infinity from being compressed into `1/0`, which may cause performance issues on `Chrome` */ + keep_infinity?: boolean; + /** Optimizations for `do`, `while` and `for` loops when we can statically determine the condition. */ + loops?: boolean; + /** negate `Immediately-Called Function Expressions` where the return value is discarded, to avoid the parens that the code generator would insert. */ + negate_iife?: boolean; + /** The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time. */ + passes?: number; + /** Rewrite property access using the dot notation, for example `foo["bar"]` to `foo.bar` */ + properties?: boolean; + /** + * An array of names and UglifyJS will assume that those functions do not produce side effects. + * DANGER: will not check if the name is redefined in scope. + * An example case here, for instance `var q = Math.floor(a/b)`. + * If variable q is not used elsewhere, UglifyJS will drop it, but will still keep the `Math.floor(a/b)`, + * not knowing what it does. You can pass `pure_funcs: [ 'Math.floor' ]` to let it know that this function + * won't produce any side effect, in which case the whole statement would get discarded. The current + * implementation adds some overhead (compression will be slower). + */ + pure_funcs?: string[]; + pure_getters?: boolean | 'strict'; + /** + * Allows single-use functions to be inlined as function expressions when permissible allowing further optimization. + * Enabled by default. Option depends on reduce_vars being enabled. Some code runs faster in the Chrome V8 engine if + * this option is disabled. Does not negatively impact other major browsers. + */ + reduce_funcs?: boolean; + /** Improve optimization on variables assigned with and used as constant values. */ + reduce_vars?: boolean; + sequences?: boolean; + /** Pass false to disable potentially dropping functions marked as "pure". */ + side_effects?: boolean; + /** De-duplicate and remove unreachable `switch` branches. */ + switches?: boolean; + /** Drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (false by default, true to drop both unreferenced functions and variables) */ + toplevel?: boolean; + /** Prevent specific toplevel functions and variables from unused removal (can be array, comma-separated, RegExp or function. Implies toplevel) */ + top_retain?: boolean; + typeofs?: boolean; + unsafe?: boolean; + /** Compress expressions like a `<= b` assuming none of the operands can be (coerced to) `NaN`. */ + unsafe_comps?: boolean; + /** Compress and mangle `Function(args, code)` when both args and code are string literals. */ + unsafe_Function?: boolean; + /** Optimize numerical expressions like `2 * x * 3` into `6 * x`, which may give imprecise floating point results. */ + unsafe_math?: boolean; + /** Optimize expressions like `Array.prototype.slice.call(a)` into `[].slice.call(a)` */ + unsafe_proto?: boolean; + /** Enable substitutions of variables with `RegExp` values the same way as if they are constants. */ + unsafe_regexp?: boolean; + unsafe_undefined?: boolean; + unused?: boolean; + /** display warnings when dropping unreachable code or unused declarations etc. */ + warnings?: boolean; +} + +export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 +} + +export interface MangleOptions { + /** Pass true to mangle names visible in scopes where `eval` or with are used. */ + eval?: boolean; + /** Pass true to not mangle function names. Useful for code relying on `Function.prototype.name`. */ + keep_fnames?: boolean; + /** Pass an array of identifiers that should be excluded from mangling. Example: `["foo", "bar"]`. */ + reserved?: string[]; + /** Pass true to mangle names declared in the top level scope. */ + toplevel?: boolean; + properties?: boolean | ManglePropertiesOptions; +} + +export interface ManglePropertiesOptions { + /** Use true to allow the mangling of builtin DOM properties. Not recommended to override this setting. */ + builtins?: boolean; + /** Mangle names with the original name still present. Pass an empty string "" to enable, or a non-empty string to set the debug suffix. */ + debug?: boolean; + /** Only mangle unquoted property names */ + keep_quoted?: boolean; + /** Pass a RegExp literal to only mangle property names matching the regular expression. */ + regex?: RegExp; + /** Do not mangle property names listed in the reserved array */ + reserved?: string[]; +} + +export interface OutputOptions { + ascii_only?: boolean; + beautify?: boolean; + braces?: boolean; + comments?: boolean | 'all' | 'some' | RegExp; + indent_level?: number; + indent_start?: boolean; + inline_script?: boolean; + keep_quoted_props?: boolean; + max_line_len?: boolean | number; + preamble?: string; + preserve_line?: boolean; + quote_keys?: boolean; + quote_style?: OutputQuoteStyle; + semicolons?: boolean; + shebang?: boolean; + webkit?: boolean; + width?: number; + wrap_iife?: boolean; +} + +export enum OutputQuoteStyle { + PreferDouble = 0, + AlwaysSingle = 1, + AlwaysDouble = 2, + AlwaysOriginal = 3 +} + +/** + * The parser creates a custom abstract syntax tree given a piece of JavaScript code. + * Perhaps you should read about the AST first. + */ +export function parse(code: string, options?: ParseOptions): AST_Toplevel; + +export interface BeautifierOptions { + /** + * Start indentation on every line (only when `beautify`) + */ + indent_start?: number; + + /** + * Indentation level (only when `beautify`) + */ + indent_level?: number; + + /** + * Quote all keys in {} literals? + */ + quote_keys?: boolean; + + /** + * Add a space after colon signs? + */ + space_colon?: boolean; + + /** + * Output ASCII-safe? (encodes Unicode characters as ASCII) + */ + ascii_only?: boolean; + + /** + * Escape " void): void; + + // This is used to output blocks in curly brackets. + // It'll print an open bracket at current point, then call newline() and with the next indentation level it calls your func. + // Lastly, it'll print an indented closing bracket. As usual, if beautification is off you'll just get {x} where x is whatever func outputs. + with_block(func: () => void): void; + + // Adds parens around the output that your function prints. + with_parens(func: () => void): void; + + // Adds square brackets around the output that your function prints. + with_square(func: () => void): void; + + // If options.source_map is set, this will generate a source mapping between the given token (which should be an AST_Token-like {}) and the current line/col. + // The name is optional; in most cases it will be inferred from the token. + add_mapping(token: AST_Node, name?: string): void; + + // Returns the option with the given name. + option(name: string): any; + + // Returns the current line in the output (1-based). + line(): number; + + // Returns the current column in the output (zero-based). + col(): number; + + // Push the given node into an internal stack. This is used to keep track of current node's parent(s). + push_node(node: AST_Node): void; + + // Pops the top of the stack and returns it. + pop_node(): AST_Node; + + // Returns that internal stack. + stack(): any; + + // Returns the n-th parent node (where zero means the direct parent). + parent(n: number): AST_Node; +} + +/** + * The code generator is a recursive process of getting back source code from an AST returned by the parser. + * Every AST node has a “print” method that takes an OutputStream and dumps the code from that node into it. + * The stream {} supports a lot of options that control the output. + * You can specify whether you'd like to get human-readable (indented) output, the indentation level, whether you'd like to quote all properties in {} literals etc. + */ +export function OutputStream(options?: BeautifierOptions): OutputStream; + +export interface SourceMapOptions { + /** + * The compressed file name + */ + file?: string; + + /** + * The root URL to the original sources + */ + root?: string; + + /** + * The input source map. + * Useful when you compress code that was generated from some other source (possibly other programming language). + * If you have an input source map, pass it in this argument and Terser will generate a mapping that maps back + * to the original source (as opposed to the compiled code that you are compressing). + */ + orig?: {} | JSON; +} + +export interface SourceMap { + add(source: string, gen_line: number, gen_col: number, orig_line: number, orig_col: number, name?: string): void; + get(): MOZ_SourceMap.SourceMapGenerator; + toString(): string; +} + +/** + * The output stream keeps track of the current line/column in the output and can trivially generate a source mapping to the original code via Mozilla's source-map library. + * To use this functionality, you must load this library (it's automatically require-d by Terser in the NodeJS version, but in a browser you must load it yourself) + * and make it available via the global MOZ_SourceMap variable. + */ +export function SourceMap(options?: SourceMapOptions): SourceMap; + +export interface CompressorOptions { + // Join consecutive statemets with the “comma operator” + sequences?: boolean; + + // Optimize property access: a["foo"] → a.foo + properties?: boolean; + + // Discard unreachable code + dead_code?: boolean; + + // Discard “debugger” statements + drop_debugger?: boolean; + + // Some unsafe optimizations (see below) + unsafe?: boolean; + + // Optimize if-s and conditional expressions + conditionals?: boolean; + + // Optimize comparisons + comparisons?: boolean; + + // Evaluate constant expressions + evaluate?: boolean; + + // Optimize boolean expressions + booleans?: boolean; + + // Optimize loops + loops?: boolean; + + // Drop unused variables/functions + unused?: boolean; + + // Hoist function declarations + hoist_funs?: boolean; + + // Hoist variable declarations + hoist_vars?: boolean; + + // Optimize if-s followed by return/continue + if_return?: boolean; + + // Join var declarations + join_vars?: boolean; + + // Try to cascade `right` into `left` in sequences + cascade?: boolean; + + // Drop side-effect-free statements + side_effects?: boolean; + + // Warn about potentially dangerous optimizations/code + warnings?: boolean; + + // Global definitions + global_defs?: {}; +} + +/** + * The compressor is a tree transformer which reduces the code size by applying various optimizations on the AST + */ +export function Compressor(options?: CompressorOptions): AST_Toplevel; + +// TODO: + +/** + * Terser provides a TreeWalker {} and every node has a walk method that given a walker will apply your visitor to each node in the tree. + * Your visitor can return a non-falsy value in order to prevent descending the current node. + */ +export class TreeWalker { + constructor(visitor: visitor); + parent: () => AST_Scope; + stack: AST_Scope[]; +} + +export type visitor = (node: AST_Node, descend: () => void) => boolean | void; + +// TODO: + +/** + * The tree transformer is a special case of a tree walker. + * In fact it even inherits from TreeWalker and you can use the same methods, but initialization and visitor protocol are a bit different. + */ +export class TreeTransformer extends TreeWalker { + constructor(visitor: visitor, after: visitor); +} + +// TODO: http://lisperator.net/uglifyjs/ast + +export class AST_PropAccess extends AST_Node { +} + +export class AST_ObjectKeyVal extends AST_Node { +} + +export class AST_Scope extends AST_Node { + find_variable(name: string): AST_SymbolDeclaration; +} + +export class AST_Symbol extends AST_Node { + scope?: AST_Scope; + name: string; + thedef: unknown; +} + +export class AST_SymbolDeclaration extends AST_Symbol { + orig: AST_SymbolDeclaration[]; + references: AST_SymbolRef[]; + global: boolean; + undeclared: boolean; + constant: boolean; + mangledName?: string; + mangled_name?: string; +} + +export class AST_SymbolRef extends AST_Symbol { +} + +export class AST_Call extends AST_Node { + expression: { name?: string, property?: string }; + args: AST_Node[]; +} +export class AST_String extends AST_Node { + value: string; +} +export class AST_Lambda extends AST_Node { + name?: string; +} +export class AST_SymbolMethod extends AST_Node { + name?: string; +} +export class AST_ConciseMethod extends AST_Node { +} +export class AST_SymbolVar extends AST_Node { + name?: string; +} diff --git a/types/terser/package.json b/types/terser/package.json new file mode 100644 index 0000000000..25c65e7595 --- /dev/null +++ b/types/terser/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "source-map": "*" + } +} diff --git a/types/terser/terser-tests.ts b/types/terser/terser-tests.ts new file mode 100644 index 0000000000..49b9190070 --- /dev/null +++ b/types/terser/terser-tests.ts @@ -0,0 +1,33 @@ +/// + +import { OutputQuoteStyle, minify } from 'terser'; + +let code: any; + +code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; + +minify(code); + +code = "function add(first, second) { return first + second; }"; +minify(code); + +minify(code); + +const output = minify(code, { + warnings: true, + mangle: { + properties: { + regex: /reg/ + } + }, + compress: { + arguments: true + } +}); + +if (output.warnings) { + output.warnings.filter(x => x === 'Dropping unused variable'); +} diff --git a/types/terser/tsconfig.json b/types/terser/tsconfig.json new file mode 100644 index 0000000000..937a5d1350 --- /dev/null +++ b/types/terser/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", + "terser-tests.ts" + ] +} diff --git a/types/terser/tslint.json b/types/terser/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/terser/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 74ce9ac0ee..fdcae48767 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -21,6 +21,7 @@ // Ethan Kay , // Methuselah96 // Dilip Ramirez +// Zhang Hao // Definitions: https://github.com//DefinitelyTyped // TypeScript Version: 2.8 @@ -32,7 +33,7 @@ export * from "./three-copyshader"; export * from "./three-css3drenderer"; export * from "./three-ctmloader"; export * from "./three-ddsloader"; -export * from './three-dragcontrols'; +export * from "./three-dragcontrols"; export * from "./three-editorcontrols"; export * from "./three-effectcomposer"; export * from "./three-examples"; diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 3ab89ea5a9..6f0051404c 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -1127,7 +1127,8 @@ export class EventDispatcher { export interface Event { type: string; - target: any; + target?: any; + [attachment: string]: any; } /** @@ -3378,17 +3379,18 @@ export class Color { */ getStyle(): string; - offsetHSL(h: number, s: number, l: number): Color; + offsetHSL(h: number, s: number, l: number): this; - add(color: Color): Color; - addColors(color1: Color, color2: Color): Color; - addScalar(s: number): Color; - sub(color: Color): Color; - multiply(color: Color): Color; - multiplyScalar(s: number): Color; - lerp(color: Color, alpha: number): Color; + add(color: Color): this; + addColors(color1: Color, color2: Color): this; + addScalar(s: number): this; + sub(color: Color): this; + multiply(color: Color): this; + multiplyScalar(s: number): this; + lerp(color: Color, alpha: number): this; + lerpHSL(color: Color, alpha: number): this; equals(color: Color): boolean; - fromArray(rgb: number[], offset?: number): Color; + fromArray(rgb: number[], offset?: number): this; toArray(array?: number[], offset?: number): number[]; } diff --git a/types/three/three-unrealbloompass.d.ts b/types/three/three-unrealbloompass.d.ts index dec35b3da7..ed58b853ac 100644 --- a/types/three/three-unrealbloompass.d.ts +++ b/types/three/three-unrealbloompass.d.ts @@ -22,6 +22,8 @@ export class UnrealBloomPass extends Pass { camera: OrthographicCamera; scene: Scene; quad: Mesh; + radius: number; + threshold: number; dispose(): void; getSeparableBlurMaterial(): ShaderMaterial; getCompositeMaterial(): ShaderMaterial; diff --git a/types/torrent-search-api/index.d.ts b/types/torrent-search-api/index.d.ts new file mode 100644 index 0000000000..cca767e4fe --- /dev/null +++ b/types/torrent-search-api/index.d.ts @@ -0,0 +1,90 @@ +// Type definitions for torrent-search-api 2.0 +// Project: https://github.com/JimmyLaurent/torrent-search-api +// Definitions by: Nicolas Girardin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Torrent { + title: string; + time: string; + size: string; + magnet: string; + desc: string; + provider: string; +} + +export interface TorrentProvider { + name: string; + baseUrl: string; + requireAuthentification: boolean; + supportTokenAuthentification: boolean; + supportCookiesAuthentification: boolean; + supportCredentialsAuthentification: boolean; + loginUrl: string; + loginQueryString: string; + searchUrl: string; + categories: any; // FIXME {key: [string]} + defaultCategory: string; + resultsPerPageCount: number; + itemsSelector: string; + itemSelectors: any; // FIXME {key: [string]} + paginateSelector: string; + torrentDetailsSelector: string; + enableCloudFareBypass: boolean; + headers: any; // FIXME {key:[string]} + magnetSelector: string; + autoFixUnstableUrl: boolean; +} + +export function lodProvider(providerParam: string): void; +export function loadProvider(providerParam: string | TorrentProvider): void; + +export function addProvider(provider: string): void; + +export function loadProviders(...args: string[]): void; +export function loadProviders(...args: TorrentProvider[]): void; + +export function removeProvider(providerName: string): void; + +export function enableProvider(providerName: string, args?: string[]): void; +export function enableProvider(providerName: string, ...args: string[]): void; + +export function enablePublicProviders(): void; + +export function disableProvider(providerName: string): void; + +export function disableAllProviders(): void; + +export function getProviders(): TorrentProvider[]; + +export function getActiveProviders(): TorrentProvider[]; + +export function isProviderActive(name: string): boolean; + +export function search( + query: string, + category: string, + limit: number +): Promise; + +export function search( + providers: string[], + query: string, + category: string, + limit: number +): Promise; + +export function getTorrentDetails(torrent: Torrent): Promise; + +export function downloadTorrent( + torrent: Torrent, + filenamePath?: string +): Promise; + +export function overrideConfig( + providerName: string, + newConfig: TorrentProvider +): Promise; + +export function getMagnet(torrent: Torrent): Promise; + +export function getProvider(name: string, throwOnError: boolean): string; diff --git a/types/torrent-search-api/torrent-search-api-tests.ts b/types/torrent-search-api/torrent-search-api-tests.ts new file mode 100644 index 0000000000..f035c7240e --- /dev/null +++ b/types/torrent-search-api/torrent-search-api-tests.ts @@ -0,0 +1,107 @@ +import TorrentSearchApi = require("torrent-search-api"); + +// $ExpectType void +TorrentSearchApi.enableProvider("Torrent9"); + +// $ExpectType Promise +TorrentSearchApi.search("1080", "Movies", 20); + +// $ExpectType TorrentProvider[] +TorrentSearchApi.getProviders(); + +// $ExpectType TorrentProvider[] +TorrentSearchApi.getActiveProviders(); + +// $ExpectType void +TorrentSearchApi.enablePublicProviders(); + +// $ExpectType void +TorrentSearchApi.enableProvider("Torrent9"); + +// $ExpectType void +TorrentSearchApi.enableProvider("IpTorrents", ["uid=XXX;", "pass=XXX;"]); + +// $ExpectType void +TorrentSearchApi.enableProvider("IpTorrents", "USERNAME", "PASSWORD"); + +// $ExpectType void +TorrentSearchApi.enableProvider("xxx", "TOKEN"); + +// $ExpectType void +TorrentSearchApi.disableProvider("TorrentLeech"); + +// $ExpectType void +TorrentSearchApi.disableAllProviders(); + +// $ExpectType boolean +TorrentSearchApi.isProviderActive("1337x"); + +// $ExpectType Promise +TorrentSearchApi.search("1080", "Movies", 20); + +// $ExpectType Promise +TorrentSearchApi.search(["IpTorrents", "Torrent9"], "1080", "Movies", 20); + +const torrent = { + title: "tile", + time: "time", + size: "size", + magnet: "magnet", + desc: "desc", + provider: "provider" +}; + +// $ExpectType Promise +TorrentSearchApi.getTorrentDetails(torrent); + +// $ExpectType Promise +TorrentSearchApi.getMagnet(torrent); + +// $ExpectType Promise +TorrentSearchApi.downloadTorrent(torrent); + +// $ExpectType Promise +TorrentSearchApi.downloadTorrent(torrent, "file.mp4"); + +const provider = { + name: "name", + baseUrl: "baseUrl", + requireAuthentification: true, + supportTokenAuthentification: true, + supportCookiesAuthentification: true, + supportCredentialsAuthentification: true, + loginUrl: "loginUrl", + loginQueryString: "loginQueryString", + searchUrl: "searchUrl", + categories: { + All: "all", + Movies: "movies" + }, + defaultCategory: "all", + resultsPerPageCount: 50, + itemsSelector: ".selector", + itemSelectors: { + title: ".title", + seeds: ".seeds", + peers: ".peers", + size: ".size", + desc: ".desc" + }, + paginateSelector: ".page", + torrentDetailsSelector: ".detail", + enableCloudFareBypass: true, + headers: { + UserAgent: "ua" + }, + magnetSelector: ".magnet", + autoFixUnstableUrl: true +}; + +// $ExpectType void +TorrentSearchApi.loadProvider(provider); + +// $ExpectType void +TorrentSearchApi.loadProviders("/path/to/provider"); + +// $ExpectType void +TorrentSearchApi.removeProvider("MyCustomProvider"); diff --git a/types/torrent-search-api/tsconfig.json b/types/torrent-search-api/tsconfig.json new file mode 100644 index 0000000000..7b342437d9 --- /dev/null +++ b/types/torrent-search-api/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "torrent-search-api-tests.ts"] +} diff --git a/types/torrent-search-api/tslint.json b/types/torrent-search-api/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/torrent-search-api/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/tough-cookie/index.d.ts b/types/tough-cookie/index.d.ts index d4e9a58548..e68496d302 100644 --- a/types/tough-cookie/index.d.ts +++ b/types/tough-cookie/index.d.ts @@ -30,7 +30,7 @@ export function canonicalDomain(str: string): string; * The str is the "current" domain-name and the domStr is the "cookie" domain-name. * Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". * - * The canonicalize parameter will run the other two paramters through canonicalDomain or not. + * The canonicalize parameter will run the other two parameters through canonicalDomain or not. */ export function domainMatch(str: string, domStr: string, canonicalize?: boolean): boolean; diff --git a/types/universal-router/index.d.ts b/types/universal-router/index.d.ts index c510352338..eb698fc8bf 100644 --- a/types/universal-router/index.d.ts +++ b/types/universal-router/index.d.ts @@ -9,7 +9,7 @@ import pathToRegexp = require('path-to-regexp'); /** - * Params is a key/value object that represents extracted URL paramters. + * Params is a key/value object that represents extracted URL parameters. * Each URL parameter resolves to a string. */ export interface Params { diff --git a/types/update-notifier/index.d.ts b/types/update-notifier/index.d.ts index 98c71d87f6..b8d6e02f52 100644 --- a/types/update-notifier/index.d.ts +++ b/types/update-notifier/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for update-notifier 2.2 +// Type definitions for update-notifier 2.5 // Project: https://github.com/yeoman/update-notifier // Definitions by: vvakame // Noah Chen // Jason Dreyzehner +// Michael Grinich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = UpdateNotifier; @@ -27,6 +28,7 @@ declare namespace UpdateNotifier { packageName?: string; packageVersion?: string; updateCheckInterval?: number; // in milliseconds, default 1000 * 60 * 60 * 24 (1 day) + shouldNotifyInNpmScript?: boolean; } interface BoxenOptions { 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/victory/index.d.ts b/types/victory/index.d.ts index 5b245440bd..5670547317 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -513,6 +513,7 @@ declare module "victory" { /** * Default theme */ + grayscale: VictoryThemeDefinition; material: VictoryThemeDefinition; } diff --git a/types/vimeo__player/index.d.ts b/types/vimeo__player/index.d.ts index cf7475f246..2ef9555813 100755 --- a/types/vimeo__player/index.d.ts +++ b/types/vimeo__player/index.d.ts @@ -70,8 +70,8 @@ export interface VimeoCuePoint { id: string; } -export interface VimeoCuePointData extends Object { - customKey: string; +export interface VimeoCuePointData { + [key: string]: any; } export interface VimeoTextTrack { diff --git a/types/w3c-gamepad/index.d.ts b/types/w3c-gamepad/index.d.ts new file mode 100644 index 0000000000..bff1d30567 --- /dev/null +++ b/types/w3c-gamepad/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for W3C Gamepad API +// Project: http://www.w3.org/TR/gamepad/ +// Definitions by: Kon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Gamepad{ + /** + * This interface defines an individual gamepad device. + */ + export interface Gamepad{ + /** + * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. + * @readonly + */ + id:string; + + /** + * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. + * @readonly + */ + index:number; + + /** + * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. + * @readonly + */ + timestamp:number; + + /** + * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. + * @readonly + */ + axes:number[]; + + /** + * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. + * @readonly + */ + buttons:GamepadButton[]; + + /** + * Indicates whether the physical device represented by this object is still connected to the system. When a gamepad becomes unavailable, whether by being physically disconnected, powered off or otherwise unusable, the connected attribute must be set to false. + * @readonly + */ + connected:boolean; + + /** + * The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it should indicate that a mapping is in use by setting this property to a known mapping name. Currently the only known mapping is "standard", which corresponds to the Standard Gamepad layout. If the user agent does not have knowledge of the device layout and is simply providing the controls as represented by the driver in use, then it must set the mapping property to an empty string. + * @readonly + */ + mapping:string; + } + + /** + * + */ + export interface GamepadEvent extends Event{ + /** + * The single gamepad attribute provides access to the associated gamepad data for this event. + * @readonly + */ + gamepad:Gamepad; + } + + export interface GamepadList{ + [index: number]: Gamepad; + length: number; + } + + export interface GamepadButton{ + pressed: boolean; + value: number; + } + + /* + * @event gamepadconnected + * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. + */ + + /* + * @event gamepaddisconnected + * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. + */ +} + +interface Navigator{ + /** + * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. + * @readonly + */ + getGamepads(): Gamepad.Gamepad[]; + + webkitGetGamepads(): Gamepad.GamepadList; + + // Not supported yet :( + // mozGetGamepads(): Gamepad[]; +} diff --git a/types/w3c-gamepad/tsconfig.json b/types/w3c-gamepad/tsconfig.json new file mode 100644 index 0000000000..e8a490bcf2 --- /dev/null +++ b/types/w3c-gamepad/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "w3c-gamepad-tests.ts" + ] +} diff --git a/types/w3c-gamepad/tslint.json b/types/w3c-gamepad/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/w3c-gamepad/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/w3c-gamepad/w3c-gamepad-tests.ts b/types/w3c-gamepad/w3c-gamepad-tests.ts new file mode 100644 index 0000000000..af3095adb0 --- /dev/null +++ b/types/w3c-gamepad/w3c-gamepad-tests.ts @@ -0,0 +1,70 @@ + + + +()=>{ + function runAnimation() + { + window.requestAnimationFrame(runAnimation); + + var gamepads = navigator.getGamepads(); + + for (var i = 0; i < gamepads.length; ++i) + { + var pad = gamepads[i]; + // todo; simple demo of displaying pad.axes and pad.buttons + } + } + + window.requestAnimationFrame(runAnimation); +}; + +(()=>{ + var gamepadconnected = (e: Gamepad.GamepadEvent) => { + console.log('Gamepad ' + e.gamepad.index + ' connected!'); + if(e.gamepad.mapping == 'standard'){ + console.log("The Gamepad's controls have been mapped to the Standard Gamepad layout."); + } + }; + var gamepaddisconnected = (e: Gamepad.GamepadEvent) => { + console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); + }; + + window.addEventListener('GamepadConnected', gamepadconnected, false); + window.addEventListener('GamepadDisconnected', gamepaddisconnected, false); + window.addEventListener('webkitGamepadConnected', gamepadconnected, false); + window.addEventListener('webkitGamepadDisconnected', gamepaddisconnected, false); + window.addEventListener('mozGamepadConnected', gamepadconnected, false); + window.addEventListener('mozGamepadDisconnected', gamepaddisconnected, false); + + var requestAnimationFrame = window.requestAnimationFrame || (window).mozRequestAnimationFrame; + var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; + if(getGamepads){ + function runAnimation() + { + requestAnimationFrame.call(window, runAnimation); + + var gamepads: Gamepad.Gamepad[] = getGamepads.call(navigator); + for(var i = 0; i < gamepads.length; i++){ + var pad: Gamepad.Gamepad = gamepads[i]; + if(pad && pad.connected){ + for (var k = 0; k < pad.buttons.length; k++) + { + var button: Gamepad.GamepadButton = pad.buttons[k]; + if(button.pressed){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button.value); + } + } + for (var k = 0; k < pad.axes.length; k++) + { + var axis = pad.axes[k]; + if(Math.abs(axis) > 0.1){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis); + } + } + } + } + } + + runAnimation(); + } +})(); \ No newline at end of file diff --git a/types/wavesurfer.js/index.d.ts b/types/wavesurfer.js/index.d.ts index c468df6e05..49a9757558 100644 --- a/types/wavesurfer.js/index.d.ts +++ b/types/wavesurfer.js/index.d.ts @@ -90,7 +90,7 @@ declare namespace WaveSurfer { } class WaveSurferPlugin { - constructor(ws: WaveSurfer, params: object); + constructor(params: object, ws: WaveSurfer); static create(params: object): PluginDefinition; init(): void; destroy(): void; @@ -151,7 +151,7 @@ declare namespace WaveSurfer { staticProps?: object; deferInit?: boolean; params: object; - instance: { new(ws: WaveSurfer, params: object): WaveSurferPlugin }; + instance: { new(params: object, ws: WaveSurfer): WaveSurferPlugin }; } interface ListenerDescriptor { diff --git a/types/wavesurfer.js/wavesurfer.js-tests.ts b/types/wavesurfer.js/wavesurfer.js-tests.ts index 49f0136d54..dc7521e59b 100644 --- a/types/wavesurfer.js/wavesurfer.js-tests.ts +++ b/types/wavesurfer.js/wavesurfer.js-tests.ts @@ -1,5 +1,3 @@ -/// -import * as fs from "fs"; import * as WaveSurfer from "wavesurfer.js"; // https://www.npmjs.com/package/wavesurfer.js#api-in-examples @@ -29,7 +27,7 @@ wsNewed.empty(); // - create an instance with plugins class SamplePlugin { - constructor(ws: WaveSurfer, params: object) { } + constructor(params: object, ws: WaveSurfer) { } static create(params: object): WaveSurfer.PluginDefinition { return { name: "samplePlugin", diff --git a/types/web3/index.d.ts b/types/web3/index.d.ts index 12ab849a94..3b1fe0c562 100644 --- a/types/web3/index.d.ts +++ b/types/web3/index.d.ts @@ -18,6 +18,7 @@ // Asgeir Sognefest // Donam Kim // Doug Kent +// Daniel Zhou // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 diff --git a/types/web3/tslint.json b/types/web3/tslint.json index dc6622bc53..99ea174f67 100644 --- a/types/web3/tslint.json +++ b/types/web3/tslint.json @@ -1,5 +1,6 @@ -{ "extends": "dtslint/dt.json", -"rules": { - "strict-export-declare-modifiers": false - } +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false + } } diff --git a/types/web3/types.d.ts b/types/web3/types.d.ts index c3d681d60f..87e6eee21b 100644 --- a/types/web3/types.d.ts +++ b/types/web3/types.d.ts @@ -36,7 +36,7 @@ export interface TransactionReceipt { events?: { [eventName: string]: EventLog; }; - status: string; + status: boolean; } export interface EncodedTransaction { diff --git a/types/web3/web3-tests.ts b/types/web3/web3-tests.ts index ed30d4fce4..170a8b22c3 100644 --- a/types/web3/web3-tests.ts +++ b/types/web3/web3-tests.ts @@ -28,7 +28,9 @@ const sendSignedTransactionTxReceipt0: PromiEvent = web3.eth const sendSignedTransactionTxReceipt1: PromiEvent = web3.eth.sendSignedTransaction("") .on("transactionHash", (txHash: string) => { }); const sendSignedTransactionTxReceipt2: PromiEvent = web3.eth.sendSignedTransaction("") - .on("receipt", (txReceipt: TransactionReceipt) => { }); + .on("receipt", (txReceipt: TransactionReceipt) => { + const { status }: { status: boolean } = txReceipt; + }); const sendSignedTransactionTxReceipt3: PromiEvent = web3.eth.sendSignedTransaction("") .on("confirmation", (confNumber: number, receipt: TransactionReceipt) => { }); const sendSignedTransactionTxReceipt4: PromiEvent = web3.eth.sendSignedTransaction("") diff --git a/types/webdriverio/index.d.ts b/types/webdriverio/index.d.ts index 27be7e973f..48fb31af47 100644 --- a/types/webdriverio/index.d.ts +++ b/types/webdriverio/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for WebdriverIO 4.10 +// Type definitions for WebdriverIO 4.13 // Project: http://www.webdriver.io/ // Definitions by: Nick Malaguti // Tim Brust @@ -327,6 +327,7 @@ declare namespace WebdriverIO { httpOnly?: boolean; expiry?: number; secure?: boolean; + domain?: string; } interface Suite { diff --git a/types/webgl-ext/index.d.ts b/types/webgl-ext/index.d.ts index 3f0da0c679..e8e2e94e2f 100644 --- a/types/webgl-ext/index.d.ts +++ b/types/webgl-ext/index.d.ts @@ -2,213 +2,81 @@ // Project: http://webgl.org/ // Definitions by: Arthur Langereis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/webgl-ext +// TypeScript Version: 2.7 -// These definitions go beyond those already defined in TS 1.6.2 stdlib -// All non-draft WebGL 1.0 extensions and prefixed extension names are -// covered. +// render-gl1/declarations - WebGL 1 extension definitions (beyond TS lib) +// Extracted from Stardazed - https://github.com/stardazed/stardazed interface HTMLCanvasElement { - getContext(contextId: "webgl"): WebGLRenderingContext; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): (WebGLRenderingContext & WebGL1Extensions) | null; } -interface WebGLRenderingContext { - getExtension(name: "ANGLE_instanced_arrays"): ANGLEInstancedArrays; +interface WebGL1Extensions { + getExtension(name: "EXT_color_buffer_half_float"): EXT_color_buffer_half_float; - getExtension(name: "EXT_blend_minmax"): EXTBlendMinMax; - getExtension(name: "EXT_color_buffer_half_float"): EXTColorBufferHalfFloat; - getExtension(name: "EXT_frag_depth"): EXTFragDepth; - getExtension(name: "EXT_sRGB"): EXTsRGB; - getExtension(name: "EXT_shader_texture_lod"): EXTShaderTextureLOD; - getExtension(name: "EXT_texture_filter_anisotropic"): EXTTextureFilterAnisotropic; + getExtension(name: "WEBGL_compressed_texture_atc"): WEBGL_compressed_texture_atc; + getExtension(name: "WEBGL_compressed_texture_etc1"): WEBGL_compressed_texture_etc1; + getExtension(name: "WEBGL_compressed_texture_pvrtc"): WEBKIT_WEBGL_compressed_texture_pvrtc; - getExtension(name: "OES_element_index_uint"): OESElementIndexUint; - getExtension(name: "OES_standard_derivatives"): OESStandardDerivatives; - getExtension(name: "OES_texture_float"): OESTextureFloat; - getExtension(name: "OES_texture_float_linear"): OESTextureFloatLinear; - getExtension(name: "OES_texture_half_float"): OESTextureHalfFloat; - getExtension(name: "OES_texture_half_float_linear"): OESTextureHalfFloatLinear; - getExtension(name: "OES_vertex_array_object"): OESVertexArrayObject; - - getExtension(name: "WEBGL_color_buffer_float"): WebGLColorBufferFloat; - getExtension(name: "WEBGL_compressed_texture_atc"): WebGLCompressedTextureATC; - getExtension(name: "WEBGL_compressed_texture_etc1"): WebGLCompressedTextureETC1; - getExtension(name: "WEBGL_compressed_texture_pvrtc"): WebGLCompressedTexturePVRTC; - getExtension(name: "WEBGL_compressed_texture_s3tc"): WebGLCompressedTextureS3TC; - getExtension(name: "WEBGL_debug_renderer_info"): WebGLDebugRendererInfo; - getExtension(name: "WEBGL_debug_shaders"): WebGLDebugShaders; - getExtension(name: "WEBGL_depth_texture"): WebGLDepthTexture; - getExtension(name: "WEBGL_draw_buffers"): WebGLDrawBuffers; - getExtension(name: "WEBGL_lose_context"): WebGLLoseContext; - - // Prefixed versions appearing in the wild as per September 2015 - - getExtension(name: "WEBKIT_EXT_texture_filter_anisotropic"): EXTTextureFilterAnisotropic; - getExtension(name: "WEBKIT_WEBGL_compressed_texture_atc"): WebGLCompressedTextureATC; - getExtension(name: "WEBKIT_WEBGL_compressed_texture_pvrtc"): WebGLCompressedTexturePVRTC; - getExtension(name: "WEBKIT_WEBGL_compressed_texture_s3tc"): WebGLCompressedTextureS3TC; - getExtension(name: "WEBKIT_WEBGL_depth_texture"): WebGLDepthTexture; - getExtension(name: "WEBKIT_WEBGL_lose_context"): WebGLLoseContext; - - getExtension(name: "MOZ_WEBGL_compressed_texture_s3tc"): WebGLCompressedTextureS3TC; - getExtension(name: "MOZ_WEBGL_depth_texture"): WebGLDepthTexture; - getExtension(name: "MOZ_WEBGL_lose_context"): WebGLLoseContext; + // Prefixed versions appearing in the wild as per February 2018 + getExtension(name: "WEBKIT_EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic; // Chrome + getExtension(name: "WEBKIT_WEBGL_compressed_texture_atc"): WEBGL_compressed_texture_atc; // Android + getExtension(name: "WEBKIT_WEBGL_compressed_texture_pvrtc"): WEBKIT_WEBGL_compressed_texture_pvrtc; // Safari iOS + getExtension(name: "WEBKIT_WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc; // Chrome + getExtension(name: "WEBKIT_WEBGL_depth_texture"): WEBGL_depth_texture; // Chrome + getExtension(name: "WEBKIT_WEBGL_lose_context"): WEBGL_lose_context; // Chrome } -interface ANGLEInstancedArrays { - VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; - drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; - drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; - vertexAttribDivisorANGLE(index: number, divisor: number): void; +// WebGL 1 Type Branding +interface WebGLObject { readonly __WebGLObject: void; } +interface WebGLBuffer { readonly __WebGLBuffer: void; } +interface WebGLFramebuffer { readonly __WebGLFramebuffer: void; } +interface WebGLProgram { readonly __WebGLProgram: void; } +interface WebGLRenderbuffer { readonly __WebGLRenderbuffer: void; } +interface WebGLShader { readonly __WebGLShader: void; } +interface WebGLTexture { readonly __WebGLTexture: void; } +interface WebGLUniformLocation { readonly __WebGLUniformLocation: void; } +interface WebGLVertexArrayObjectOES extends WebGLObject { readonly __WebGLVertexArrayObjectOES: void; } + +interface EXT_frag_depth { readonly __EXT_frag_depth: void; } +interface EXT_shader_texture_lod { readonly __EXT_shader_texture_lod: void; } + +interface OES_element_index_uint { readonly __OESElementIndexUint: void; } +interface OES_texture_float { readonly __OES_texture_float: void; } +interface OES_texture_float_linear { readonly __OES_texture_float_linear: void; } +interface OES_texture_half_float_linear { readonly __OES_texture_half_float_linear: void; } + + +// WebGL 1 Extensions +interface EXT_color_buffer_half_float { + readonly RGBA16F_EXT: number; + readonly RGB16F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; } -interface EXTBlendMinMax { - MIN_EXT: number; - MAX_EXT: number; -} - -interface EXTColorBufferHalfFloat { - RGBA16F_EXT: number; - RGB16F_EXT: number; - FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; - UNSIGNED_NORMALIZED_EXT: number; -} - -interface EXTFragDepth { -} - -interface EXTsRGB { - SRGB_EXT: number; - SRGB_ALPHA_EXT: number; - SRGB8_ALPHA8_EXT: number; - FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; -} - -interface EXTShaderTextureLOD { -} - -interface EXTTextureFilterAnisotropic { - TEXTURE_MAX_ANISOTROPY_EXT: number; - MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; -} - -interface OESElementIndexUint { -} - -interface OESStandardDerivatives { - FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; -} - -interface OESTextureFloat { -} - -interface OESTextureFloatLinear { -} - -interface OESTextureHalfFloat { - HALF_FLOAT_OES: number; -} - -interface OESTextureHalfFloatLinear { -} - -interface WebGLVertexArrayObjectOES extends WebGLObject { -} - -interface OESVertexArrayObject { - VERTEX_ARRAY_BINDING_OES: number; - +interface OES_vertex_array_object { + // TS's lib.dom (as of v3.1.3) does not specify the nulls createVertexArrayOES(): WebGLVertexArrayObjectOES | null; deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; isVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): boolean; bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; } -interface WebGLColorBufferFloat { - RGBA32F_EXT: number; - FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; - UNSIGNED_NORMALIZED_EXT: number; +interface WEBGL_compressed_texture_atc { + readonly COMPRESSED_RGB_ATC_WEBGL: number; + readonly COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: number; + readonly COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: number; } -interface WebGLCompressedTextureATC { - COMPRESSED_RGB_ATC_WEBGL: number; - COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: number; - COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: number; +interface WEBGL_compressed_texture_etc1 { + readonly COMPRESSED_RGB_ETC1_WEBGL: number; } -interface WebGLCompressedTextureETC1 { - COMPRESSED_RGB_ETC1_WEBGL: number; -} - -interface WebGLCompressedTexturePVRTC { - COMPRESSED_RGB_PVRTC_4BPPV1_IMG: number; - COMPRESSED_RGB_PVRTC_2BPPV1_IMG: number; - COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: number; - COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: number; -} - -interface WebGLCompressedTextureS3TC { - COMPRESSED_RGB_S3TC_DXT1_EXT: number; - COMPRESSED_RGBA_S3TC_DXT1_EXT: number; - COMPRESSED_RGBA_S3TC_DXT3_EXT: number; - COMPRESSED_RGBA_S3TC_DXT5_EXT: number; -} - -interface WebGLDebugRendererInfo { - UNMASKED_VENDOR_WEBGL: number; - UNMASKED_RENDERER_WEBGL: number; -} - -interface WebGLDebugShaders { - getTranslatedShaderSource(shader: WebGLShader): string; -} - -interface WebGLDepthTexture { - UNSIGNED_INT_24_8_WEBGL: number; -} - -interface WebGLDrawBuffers { - COLOR_ATTACHMENT0_WEBGL: number; - COLOR_ATTACHMENT1_WEBGL: number; - COLOR_ATTACHMENT2_WEBGL: number; - COLOR_ATTACHMENT3_WEBGL: number; - COLOR_ATTACHMENT4_WEBGL: number; - COLOR_ATTACHMENT5_WEBGL: number; - COLOR_ATTACHMENT6_WEBGL: number; - COLOR_ATTACHMENT7_WEBGL: number; - COLOR_ATTACHMENT8_WEBGL: number; - COLOR_ATTACHMENT9_WEBGL: number; - COLOR_ATTACHMENT10_WEBGL: number; - COLOR_ATTACHMENT11_WEBGL: number; - COLOR_ATTACHMENT12_WEBGL: number; - COLOR_ATTACHMENT13_WEBGL: number; - COLOR_ATTACHMENT14_WEBGL: number; - COLOR_ATTACHMENT15_WEBGL: number; - - DRAW_BUFFER0_WEBGL: number; - DRAW_BUFFER1_WEBGL: number; - DRAW_BUFFER2_WEBGL: number; - DRAW_BUFFER3_WEBGL: number; - DRAW_BUFFER4_WEBGL: number; - DRAW_BUFFER5_WEBGL: number; - DRAW_BUFFER6_WEBGL: number; - DRAW_BUFFER7_WEBGL: number; - DRAW_BUFFER8_WEBGL: number; - DRAW_BUFFER9_WEBGL: number; - DRAW_BUFFER10_WEBGL: number; - DRAW_BUFFER11_WEBGL: number; - DRAW_BUFFER12_WEBGL: number; - DRAW_BUFFER13_WEBGL: number; - DRAW_BUFFER14_WEBGL: number; - DRAW_BUFFER15_WEBGL: number; - - MAX_COLOR_ATTACHMENTS_WEBGL: number; - MAX_DRAW_BUFFERS_WEBGL: number; - - drawBuffersWEBGL(buffers: number[]): void; -} - -interface WebGLLoseContext { - loseContext(): void; - restoreContext(): void; +interface WEBKIT_WEBGL_compressed_texture_pvrtc { + readonly COMPRESSED_RGB_PVRTC_4BPPV1_IMG: number; + readonly COMPRESSED_RGB_PVRTC_2BPPV1_IMG: number; + readonly COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: number; + readonly COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: number; } diff --git a/types/webgl-ext/webgl-ext-tests.ts b/types/webgl-ext/webgl-ext-tests.ts index 6e0580643b..6d7739cf32 100644 --- a/types/webgl-ext/webgl-ext-tests.ts +++ b/types/webgl-ext/webgl-ext-tests.ts @@ -5,66 +5,10 @@ var gl = canvas.getContext("webgl"); var ext: any; var t: any; -if (ext = gl.getExtension("ANGLE_instanced_arrays")) { - t = ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE; -} - -if (ext = gl.getExtension("EXT_blend_minmax")) { - t = ext.MIN_EXT; -} - if (ext = gl.getExtension("EXT_color_buffer_half_float")) { t = ext.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT; } -if (ext = gl.getExtension("EXT_frag_depth")) { - // no fields -} - -if (ext = gl.getExtension("EXT_sRGB")) { - t = ext.SRGB8_ALPHA8_EXT; -} - -if (ext = gl.getExtension("EXT_shader_texture_lod")) { - // no fields -} - -if (ext = gl.getExtension("EXT_texture_filter_anisotropic")) { - t = ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT; -} - -if (ext = gl.getExtension("OES_element_index_uint")) { - // no fields -} - -if (ext = gl.getExtension("OES_standard_derivatives")) { - t = ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES; -} - -if (ext = gl.getExtension("OES_texture_float")) { - // no fields -} - -if (ext = gl.getExtension("OES_texture_float_linear")) { - // no fields -} - -if (ext = gl.getExtension("OES_texture_half_float")) { - t = ext.HALF_FLOAT_OES; -} - -if (ext = gl.getExtension("OES_texture_half_float_linear")) { - // no fields -} - -if (ext = gl.getExtension("OES_vertex_array_object")) { - t = ext.createVertexArrayOES; // just get fn ref, don't call -} - -if (ext = gl.getExtension("WEBGL_color_buffer_float")) { - t = ext.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT; -} - if (ext = gl.getExtension("WEBGL_compressed_texture_atc")) { t = ext.COMPRESSED_RGB_ATC_WEBGL; } @@ -76,27 +20,3 @@ if (ext = gl.getExtension("WEBGL_compressed_texture_etc1")) { if (ext = gl.getExtension("WEBGL_compressed_texture_pvrtc")) { t = ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; } - -if (ext = gl.getExtension("WEBGL_compressed_texture_s3tc")) { - t = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT; -} - -if (ext = gl.getExtension("WEBGL_debug_renderer_info")) { - t = ext.UNMASKED_VENDOR_WEBGL; -} - -if (ext = gl.getExtension("WEBGL_debug_shaders")) { - t = ext.getTranslatedShaderSource; // just get fn ref, don't call -} - -if (ext = gl.getExtension("WEBGL_depth_texture")) { - t = ext.UNSIGNED_INT_24_8_WEBGL; -} - -if (ext = gl.getExtension("WEBGL_draw_buffers")) { - t = ext.MAX_COLOR_ATTACHMENTS_WEBGL; -} - -if (ext = gl.getExtension("WEBGL_lose_context")) { - t = ext.loseContext; // just get fn ref, don't call -} diff --git a/types/webidl2/index.d.ts b/types/webidl2/index.d.ts index 90a938b22a..2e04cc413c 100644 --- a/types/webidl2/index.d.ts +++ b/types/webidl2/index.d.ts @@ -96,7 +96,7 @@ export interface CallbackType { name: string; /** An IDL Type describing what the callback returns. */ idlType: IDLTypeDescription; - /** A list of arguments, as in function paramters. */ + /** A list of arguments, as in function parameters. */ arguments: Argument[]; /** A list of extended attributes. */ extAttrs: ExtendedAttributes[]; diff --git a/types/webpack-subresource-integrity/index.d.ts b/types/webpack-subresource-integrity/index.d.ts new file mode 100644 index 0000000000..d47d7d2275 --- /dev/null +++ b/types/webpack-subresource-integrity/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for webpack-subresource-integrity 1.2 +// Project: https://github.com/waysact/webpack-subresource-integrity +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/webpack-subresource-integrity-typings +// TypeScript Version: 2.3 + +import { Plugin } from 'webpack'; + +declare namespace WebpackSubresourceIntegrityPlugin { + interface Options { + /** + * Default value: true + * When this value is falsy, the plugin doesn't run and no integrity values are calculated. It is recommended to disable the plugin in development mode. + */ + enabled?: boolean; + + /** + * An array of strings, each specifying the name of a hash function to be used for calculating integrity hash values. For example, ['sha256', 'sha512']. + */ + hashFuncNames: string[]; + } +} + +declare class WebpackSubresourceIntegrityPlugin extends Plugin { + constructor(options?: WebpackSubresourceIntegrityPlugin.Options); +} + +export = WebpackSubresourceIntegrityPlugin; diff --git a/types/webpack-subresource-integrity/tsconfig.json b/types/webpack-subresource-integrity/tsconfig.json new file mode 100644 index 0000000000..5461016c11 --- /dev/null +++ b/types/webpack-subresource-integrity/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", + "webpack-subresource-integrity-tests.ts" + ] +} diff --git a/types/webpack-subresource-integrity/tslint.json b/types/webpack-subresource-integrity/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/webpack-subresource-integrity/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/webpack-subresource-integrity/webpack-subresource-integrity-tests.ts b/types/webpack-subresource-integrity/webpack-subresource-integrity-tests.ts new file mode 100644 index 0000000000..810893429c --- /dev/null +++ b/types/webpack-subresource-integrity/webpack-subresource-integrity-tests.ts @@ -0,0 +1,15 @@ +import * as webpack from 'webpack'; +import SriPlugin = require('webpack-subresource-integrity'); + +const config: webpack.Configuration = { + plugins: [ + new SriPlugin(), + new SriPlugin({ + hashFuncNames: ['sha256', 'sha384'] + }), + new SriPlugin({ + enabled: false, + hashFuncNames: ['sha256'] + }) + ] +}; diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index df1263f1b2..94974500eb 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -289,9 +289,7 @@ declare namespace wx { * 需要用户授权 scope.writePhotosAlbum * @version 1.2.0 */ - function saveImageToPhotosAlbum( - options: SaveImageToPhotosAlbumOptions - ): void; + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; // 媒体-----录音 interface StartRecordAudioOptions extends BaseOptions { /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ @@ -387,13 +385,9 @@ declare namespace wx { /** 录音恢复事件 */ onResume(callback?: () => void): void; /** 录音停止事件,会回调文件地址 */ - onStop( - callback?: (options: OnRecorderManagerStopOptions) => void - ): void; + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ - onFrameRecorded( - callback?: (options: OnFrameRecordedOptions) => void - ): void; + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; /** 录音错误事件, 会回调错误信息 */ onError(callback?: (err: ErrMsgResponse) => void): void; } @@ -974,7 +968,7 @@ declare namespace wx { * 异步获取当前storage的相关信息 */ function getStorageInfo(options: GetStorageInfoOptions): void; - function getStorageInfoSync(): GetStorageInfoOptions; + function getStorageInfoSync(): StorageInfo; interface RemoveStorageOptions extends BaseOptions { key: string; success?(res: DataResponse): void; @@ -1066,9 +1060,7 @@ declare namespace wx { /** * 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 wx.openLocation */ - getCenterLocation( - options: GetCenterLocationOptions - ): OpenLocationOptions; + getCenterLocation(options: GetCenterLocationOptions): OpenLocationOptions; /** * 将地图中心移动到当前定位点,需要配合map组件的show-location使用 */ @@ -2611,6 +2603,9 @@ declare namespace wx { } type LineCapType = "butt" | "round" | "square"; type LineJoinType = "bevel" | "round" | "miter"; + interface CanvasGradient { + addColorStop(index: number, color: string): void; + } /** * context只是一个记录方法调用的容器,用于生成记录绘制行为的actions数组。context跟不存在对应关系,一个context生成画布的绘制动作数组可以应用于多个。 */ @@ -2873,7 +2868,7 @@ declare namespace wx { y0: number, x1: number, y1: number - ): void; + ): CanvasGradient; /** * 创建一个颜色的渐变点。 * Tip: 小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染。 @@ -3613,6 +3608,30 @@ declare namespace wx { enableDebug: boolean; } // #region App里的onLaunch、onShow回调参数 + + // #region Account + interface AccountInfo { + /* 小程序账号信息 */ + miniProgram: { + /*小程序 appId */ + appId: string; + }; + /* 插件账号信息(仅在插件中调用时包含这一项) */ + plugin?: { + /* 插件 appId */ + appId: string; + /* 插件版本号 */ + version: string; + }; + } + + /** + * 获取当前账号信息 + * @version >= 2.2.2 + */ + function getAccountInfoSync(): AccountInfo; + // #endregion + /** * App 实现的接口对象 * 开发者可以添加任意的函数或数据到 Object 参数中,用 this 可以访问 @@ -3670,8 +3689,7 @@ declare namespace wx { Data, Methods, Props - > = CombinedInstance & - Component; + > = CombinedInstance & Component; // CombinedInstance models the `this`, i.e. instance type for (user defined) component type CombinedInstance< @@ -3702,9 +3720,7 @@ declare namespace wx { type ArrayPropsDefinition = Array; - type PropsDefinition = - | ArrayPropsDefinition - | RecordPropsDefinition; + type PropsDefinition = ArrayPropsDefinition | RecordPropsDefinition; interface ComponentRelation { /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ @@ -3838,9 +3854,7 @@ declare namespace wx { * 类似于mixins和traits的组件间代码复用机制 * 参见 [behaviors](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/behaviors.html) */ - behaviors?: Array< - (ComponentOptions>) | string - >; + behaviors?: Array<(ComponentOptions>) | string>; /** * 组件生命周期声明对象,组件的生命周期:created、attached、ready、moved、detached将收归到lifetimes字段内进行声明, @@ -4084,25 +4098,22 @@ declare namespace wx { /** * 当场景为由从另一个小程序或公众号或App打开时,返回此字段 */ - referrerInfo: object; - /** - * 来源小程序或公众号或App的 appId,详见下方说明 - */ - "referrerInfo.appId": string; - /** - * 来源小程序传过来的数据,scene=1037或1038时支持 - */ - "referrerInfo.extraData": object; + referrerInfo: { + /* 来源小程序或公众号或App的 appId,详见下方说明 */ + appId: string; + /* 来源小程序传过来的数据,scene=1037或1038时支持 */ + extraData: object; + }; // #endregion } // 云开发 // 文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html - interface cloud { + interface Cloud { /** * 初始化方法(全局只需一次) */ - init: (options: initCloudOptions) => void; + init: (options: InitCloudOptions) => void; /** * 接受一个可选对象参数 env:环境 ID,获取数据库的引用 */ @@ -4115,12 +4126,12 @@ declare namespace wx { /** * 定义了云开发的默认配置,该配置会作为之后调用其他所有云 API 的默认配置 */ - interface initCloudOptions { + interface InitCloudOptions { /** * 默认环境配置,传入字符串形式的环境 ID 可以指定所有服务的默认环境,传入对象 initCloudEnvOptions 可以分别指定各个服务的默认环境 * 默认值: default */ - env?: string | initCloudEnvOptions; + env?: string | InitCloudEnvOptions; /** * 是否在将用户访问记录到用户管理中,在控制台中可见 * 默认值: false @@ -4130,7 +4141,7 @@ declare namespace wx { /** * initCloudOptions 的 env 参数,可以指定各个服务的默认环境 */ - interface initCloudEnvOptions { + interface InitCloudEnvOptions { /** * 数据库 API 默认环境配置 * 默认值: default diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index cacdeaee70..7333dce911 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -469,3 +469,8 @@ wx.getSystemInfo({ } = res; } }); + +function testAccountInfo(): string { + const accountInfo: wx.AccountInfo = wx.getAccountInfoSync(); + return accountInfo.miniProgram.appId; +} 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"); }); diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 3fc9a33fcd..6e037366ed 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -163,7 +163,7 @@ export interface ArraySchema extends Schema { min(limit: number | Ref, message?: string): ArraySchema; max(limit: number | Ref, message?: string): ArraySchema; ensure(): ArraySchema; - compact(rejector: (value: any) => boolean): ArraySchema; + compact(rejector?: (value: any) => boolean): ArraySchema; } export interface ObjectSchemaConstructor {