diff --git a/.editorconfig b/.editorconfig index 404ff0701c..fc4ed3486f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,5 +5,5 @@ indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true -[{*.json,*.yml,*.ts}] +[{*.json,*.yml,*.ts,*.tsx,*.md}] indent_style = space diff --git a/README.md b/README.md index 026994fdd5..125b897e42 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@ -# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) - -[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +# DefinitelyTyped > The repository for *high quality* TypeScript type definitions. @@ -8,6 +6,19 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although *You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!* +## Current status + +This section tracks the health of the repository and publishing process. +It may be helpful for contributors experiencing any issues with their PRs and packages. + +* All packages are type-checking/linting cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) +* All packages are being published to npm in under 10,000 seconds: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) +* [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) + +If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped). + +[![Join the chat at https://gitter.im/DefinitelyTyped/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/DefinitelyTyped/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + ## What are declaration files? See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). @@ -342,6 +353,3 @@ This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file. [![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) - -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average? -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours? diff --git a/README.ru.md b/README.ru.md index b90bdeac7c..9186c2ddd5 100644 --- a/README.ru.md +++ b/README.ru.md @@ -8,7 +8,7 @@ Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая. -*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).* +*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) и [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).* ## Что такое файлы декларации (файлы описания/объявления типов)? @@ -101,9 +101,9 @@ DefinitelyTyped работает только благодаря вкладу т // John ``` -* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` in в директории пакета. +* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` в директории пакета. -Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить previous authors. +Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR. @@ -124,7 +124,7 @@ DefinitelyTyped работает только благодаря вкладу т | tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. | | tslint.json | Включает linting. | -Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае. +Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас npm ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае. Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen). Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`. @@ -283,7 +283,7 @@ f("one"); "typeRoots": ["../../"], "paths": { "history": [ "history/v2" ] - }, + } }, "files": [ "index.d.ts", diff --git a/notNeededPackages.json b/notNeededPackages.json index 4acd790e24..11bef06fb9 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1068,6 +1068,12 @@ "sourceRepoURL": "https://github.com/paularmstrong/normalizr", "asOfVersion": "2.0.18" }, + { + "libraryName": "Nuka Carousel", + "typingsPackageName": "nuka-carousel", + "sourceRepoURL": "https://github.com/FormidableLabs/nuka-carousel/", + "asOfVersion": "4.4.6" + }, { "libraryName": "Numbro", "typingsPackageName": "numbro", diff --git a/types/accept/accept-tests.ts b/types/accept/accept-tests.ts index 011216ede4..659d05c174 100644 --- a/types/accept/accept-tests.ts +++ b/types/accept/accept-tests.ts @@ -14,6 +14,8 @@ accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB" const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"] languages.lastIndexOf(''); +accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1"); +accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]); const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1"); // mediaTypes === ["text/plain", "text/html", "application/json", "*/*"] mediaTypes.lastIndexOf(''); diff --git a/types/accept/index.d.ts b/types/accept/index.d.ts index b067ea4306..886193a01e 100644 --- a/types/accept/index.d.ts +++ b/types/accept/index.d.ts @@ -10,6 +10,7 @@ export function encoding(encodingHeader?: string, preferences?: string[]): strin export function encodings(encodingHeader?: string): string[]; export function language(languageHeader?: string, preferences?: string[]): string; export function languages(languageHeader?: string): string[]; +export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string; export function mediaTypes(mediaTypeHeader?: string): string[]; export function parseAll( headers: Record diff --git a/types/activestorage/activestorage-tests.ts b/types/activestorage/activestorage-tests.ts new file mode 100644 index 0000000000..ac9622e2d8 --- /dev/null +++ b/types/activestorage/activestorage-tests.ts @@ -0,0 +1,28 @@ +import * as ActiveStorage from 'activestorage'; + +ActiveStorage.start(); + +const delegate: ActiveStorage.DirectUploadDelegate = { + directUploadWillCreateBlobWithXHR(xhr) { + console.log(xhr.status); + }, + + directUploadWillStoreFileWithXHR(xhr) { + console.log(xhr.status); + }, +}; + +const d = new ActiveStorage.DirectUpload( + new File([], 'blank.txt'), + '/rails/active_storage/direct_uploads', + delegate +); + +d.create((error, blob) => { + if (error) { + console.log(error.message); + } else { + const { byte_size, checksum, content_type, filename, signed_id } = blob; + console.log({ byte_size, checksum, content_type, filename, signed_id }); + } +}); diff --git a/types/activestorage/index.d.ts b/types/activestorage/index.d.ts new file mode 100644 index 0000000000..2d749c84ec --- /dev/null +++ b/types/activestorage/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for ActiveStorage 5.2 +// Project: https://github.com/rails/rails/tree/master/activestorage/app/javascipt +// Definitions by: Cameron Bothner +// Definitions: https://github.com/cbothner/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace ActiveStorage + +export function start(): void; + +export class DirectUpload { + id: number; + file: File; + url: string; + + constructor(file: File, url: string, delegate: DirectUploadDelegate) + + create(callback: (error: Error, blob: Blob) => void): void; +} + +export interface DirectUploadDelegate { + directUploadWillCreateBlobWithXHR?: (xhr: XMLHttpRequest) => void; + + directUploadWillStoreFileWithXHR?: (xhr: XMLHttpRequest) => void; +} + +export interface Blob { + byte_size: number; + checksum: string; + content_type: string; + filename: string; + signed_id: string; +} diff --git a/types/activestorage/tsconfig.json b/types/activestorage/tsconfig.json new file mode 100644 index 0000000000..326c2c7401 --- /dev/null +++ b/types/activestorage/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", "activestorage-tests.ts"] +} diff --git a/types/activestorage/tslint.json b/types/activestorage/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/activestorage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/adlib/adlib-tests.ts b/types/adlib/adlib-tests.ts new file mode 100644 index 0000000000..1f745d071a --- /dev/null +++ b/types/adlib/adlib-tests.ts @@ -0,0 +1,40 @@ +/* + | Copyright 2018 Esri + | + | Licensed under the Apache License, Version 2.0 (the "License"); + | you may not use this file except in compliance with the License. + | You may obtain a copy of the License at + | + | http://www.apache.org/licenses/LICENSE-2.0 + | + | Unless required by applicable law or agreed to in writing, software + | distributed under the License is distributed on an "AS IS" BASIS, + | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + | See the License for the specific language governing permissions and + | limitations under the License. + */ + +import * as adlib from "adlib"; + +const transform1: adlib.TransformFunction = + (key: string, value: any, settings: any, param?: any): any => { + return null; + }; + +const transformsList: adlib.TransformsList = { + firstXform: transform1 +}; + +const template = { + value: '{{ instance.color }}' +}; + +const settings = { + instance: { + color: 'red' + } +}; + +const interpolated = adlib.adlib(template, settings, transformsList); + +const list: string[] = adlib.listDependencies(template); diff --git a/types/adlib/index.d.ts b/types/adlib/index.d.ts new file mode 100644 index 0000000000..8866ab7809 --- /dev/null +++ b/types/adlib/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for adlib 3.0 +// Project: https://github.com/Esri/adlib +// Definitions by: Esri +// Mike Tschudi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/* + | Copyright 2018 Esri + | + | Licensed under the Apache License, Version 2.0 (the "License"); + | you may not use this file except in compliance with the License. + | You may obtain a copy of the License at + | + | http://www.apache.org/licenses/LICENSE-2.0 + | + | Unless required by applicable law or agreed to in writing, software + | distributed under the License is distributed on an "AS IS" BASIS, + | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + | See the License for the specific language governing permissions and + | limitations under the License. + */ + +/** + * Transform function to apply to interpolated value. + * + * @param key Path within a handlebar-style expression to attempt to replace; e.g., `s.animal.type` in + * https://github.com/Esri/adlib#transforms + * @param value Value to replace expression with + * @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern + * @param param Parameter for transform function; e.g., the `optional` transform accepts a count of levels + * to delete if the value is not found (default is 0--just the current level); + * see https://github.com/Esri/adlib#optional-transform + */ +export interface TransformFunction { + ( + key: string, + value: any, + settings: any, + param?: any + ): any; +} + +/** + * Set of transformation functions keyed by the transform function's name. + */ +export interface TransformsList { + [ transformFnName: string ]: TransformFunction; +} + +/** + * A JavaScript library for interpolating property values in JSON Objects. + * + * @param template A template that possibly containing handlebar-style property values to replace; + * see https://github.com/Esri/adlib#general-pattern + * @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern + * @param transforms Set of transformation functions + * @return Copy of template with replacements performed + */ +export function adlib( + template: any, + settings: any, + transforms?: TransformsList +): any; + +/** + * Reads a template and spits out unique handlebar-style property values. + * + * @param template A template that possibly containing handlebar-style property values to replace; + * see https://github.com/Esri/adlib#general-pattern + * @return List of unique property values in template + */ +export function listDependencies( + template: any +): string []; diff --git a/types/adlib/tsconfig.json b/types/adlib/tsconfig.json new file mode 100644 index 0000000000..570be96b8d --- /dev/null +++ b/types/adlib/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", + "adlib-tests.ts" + ] +} diff --git a/types/adlib/tslint.json b/types/adlib/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/adlib/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/aes-js/aes-js-tests.ts b/types/aes-js/aes-js-tests.ts new file mode 100644 index 0000000000..4f9d582630 --- /dev/null +++ b/types/aes-js/aes-js-tests.ts @@ -0,0 +1,10 @@ +import * as aesjs from 'aes-js'; + +const key = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + +const data: Uint8Array = aesjs.utils.utf8.toBytes('hello world'); + +const ecb = new aesjs.ModeOfOperation.ecb(key); +ecb.decrypt(ecb.encrypt(data)); + +const hex: string = aesjs.utils.hex.fromBytes(data); diff --git a/types/aes-js/index.d.ts b/types/aes-js/index.d.ts new file mode 100644 index 0000000000..142e03f7d9 --- /dev/null +++ b/types/aes-js/index.d.ts @@ -0,0 +1,134 @@ +// Type definitions for aes-js 3.1 +// Project: https://github.com/ricmoo/aes-js +// Definitions by: Federico Bond +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type ByteSource = ArrayBuffer | Uint8Array | number[]; + +export class AES { + /** + * Create a new AES block cipher. + * @param key The cipher key. + */ + constructor(key: ByteSource) + encrypt(v: ByteSource): ByteSource; +} + +/** + * Create a new Counter state for CTR cipher mode. + * @param initialValue The Counter initial value. + */ +export class Counter { + constructor(initialValue: number) + setValue(value: number): void; + setBytes(bytes: ByteSource): void; + increment(): void; +} + +export namespace ModeOfOperation { + class ModeOfOperationECB { + /** + * Create a new ECB stream cipher. + * @param key The cipher key. + */ + constructor(key: ByteSource) + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationCBC { + /** + * Create a new CBC stream cipher. + * @param key The cipher key. + * @param iv The cipher initialization vector. + */ + constructor(key: ByteSource, iv: ByteSource); + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationCFB { + /** + * Create a new CFB stream cipher. + * @param key The cipher key. + * @param iv The cipher initialization vector. + * @param segmentSize The cipher segment size. + */ + constructor(key: ByteSource, iv: ByteSource, segmentSize: number); + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationOFB { + /** + * Create a new OFB stream cipher. + * @param key The cipher key. + * @param iv The cipher initialization vector. + */ + constructor(key: ByteSource, iv: ByteSource); + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationCTR { + /** + * Create a new CTR stream cipher. + * @param key The cipher key. + * @param counter The cipher counter state. + */ + constructor(key: ByteSource, counter?: Counter) + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + const ecb: typeof ModeOfOperationECB; + const cbc: typeof ModeOfOperationCBC; + const cfb: typeof ModeOfOperationCFB; + const ofb: typeof ModeOfOperationOFB; + const ctr: typeof ModeOfOperationCTR; +} + +export namespace utils { + namespace utf8 { + /** + * Convert a UTF8 encoded string to a Uint8Array. + * @param data The input string. + */ + function toBytes(data: string): Uint8Array; + + /** + * Convert an array-like object containing UTF8 data to a string. + * @param data The input data. + */ + function fromBytes(data: ByteSource): string; + } + namespace hex { + /** + * Convert a hexadecimal string to a Uint8Array. + * @param data The input string. + */ + function toBytes(data: string): Uint8Array; + + /** + * Convert an array-like object to a hexadecimal string. + * @param data The input data. + */ + function fromBytes(data: ByteSource): string; + } +} + +export namespace padding { + namespace pkcs7 { + /** + * Add standard PKCS7 padding to an array. + * @param data The input data. + */ + function pad(data: ByteSource): Uint8Array; + + /** + * Remove standard PKCS7 padding from an array. + * @param data The input data. + */ + function strip(data: ByteSource): Uint8Array; + } +} diff --git a/types/aes-js/tsconfig.json b/types/aes-js/tsconfig.json new file mode 100644 index 0000000000..10f3720c1e --- /dev/null +++ b/types/aes-js/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", + "aes-js-tests.ts" + ] +} diff --git a/types/aes-js/tslint.json b/types/aes-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/aes-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index 0a3ba3c133..67257c6f65 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -358,7 +358,7 @@ export interface Utils { // Definitions // used as mixins to register functions to create classes (newable functions) in A-Frame -export type ComponentDefinition = T & Partial; +export type ComponentDefinition = T & Partial & ThisType; export type GeometryDefinition = T & Partial>; export type NodeDefinition = T & Partial; export interface PrimitiveDefinition { diff --git a/types/aframe/test/aframe-io-tests.ts b/types/aframe/test/aframe-io-tests.ts index 1120b50be8..a846976b80 100644 --- a/types/aframe/test/aframe-io-tests.ts +++ b/types/aframe/test/aframe-io-tests.ts @@ -30,7 +30,7 @@ AFRAME.registerComponent('set-image', { init: function() { var data = this.data; - var el = this.el!; + var el = this.el; this.setupFadeAnimation(); @@ -133,14 +133,14 @@ AFRAME.registerComponent('arrow-key-rotation', { if (!this.data.enabled) { return; } - var rotation = this.el!.getAttribute('rotation'); + var rotation = this.el.getAttribute('rotation'); if (!rotation) { return; } if (this.directionX || this.directionY) { rotation.x += this.data.dx * this.directionY; rotation.y += this.data.dy * this.directionX; - this.el!.setAttribute('rotation', rotation); + this.el.setAttribute('rotation', rotation); } } }); @@ -164,10 +164,10 @@ AFRAME.registerComponent('hide-once-playing', { } }, onPlaying: function() { - this.el!.setAttribute('visible', false); + this.el.setAttribute('visible', false); }, onPause: function() { - this.el!.setAttribute('visible', true); + this.el.setAttribute('visible', true); } }); @@ -178,10 +178,10 @@ AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', { }, play: function() { window.addEventListener('vrdisplayactivate', this.playVideo); - this.el!.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick); + this.el.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick); }, pause: function() { - this.el!.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick); + this.el.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick); window.removeEventListener('vrdisplayactivate', this.playVideo); }, playVideoNextTick: function() { @@ -189,7 +189,7 @@ AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', { }, playVideo: function() { // TODO improve type - var video = (this.el! as Entity).components.material.material.map.image; + var video = (this.el as Entity).components.material.material.map.image; if (!video) { return; } @@ -208,7 +208,7 @@ AFRAME.registerComponent('play-on-window-click', { window.removeEventListener('click', this.onClick); }, onClick: function() { - var video = (this.el! as Entity).components.material.material.map.image; + var video = (this.el as Entity).components.material.material.map.image; if (!video) { return; } @@ -227,7 +227,7 @@ AFRAME.registerComponent('toggle-play-on-window-click', { window.removeEventListener('click', this.onClick); }, onClick: function() { - var video = (this.el! as Entity).components.material.material.map.image; + var video = (this.el as Entity).components.material.material.map.image; if (!video) { return; } @@ -359,7 +359,7 @@ AFRAME.registerComponent('audioanalyser-levels-scale', { return; } - children = this.el!.children; + children = this.el.children; for (var i = 0; i < children.length; i++) { (children[i] as ANode).setAttribute('scale', { x: 1, @@ -382,7 +382,7 @@ AFRAME.registerComponent('audioanalyser-volume-bind', { tick: function() { var analyserComponent; var data = this.data; - var el = this.el!; + var el = this.el; var value; analyserComponent = data.analyserEl.components.audioanalyser; @@ -404,7 +404,7 @@ AFRAME.registerComponent('audioanalyser-volume-scale', { tick: function() { var analyserEl = this.data.analyserEl || this.el; var analyserComponent; - var el = this.el!; + var el = this.el; var volume; analyserComponent = analyserEl.components.audioanalyser; @@ -542,7 +542,7 @@ AFRAME.registerComponent('audioanalyser-waveform', { }, remove: function() { - this.el!.removeObject3D('waveformContainer'); + this.el.removeObject3D('waveformContainer'); } }); @@ -874,7 +874,7 @@ AFRAME.registerComponent('color-on-beat', { init: function() { var analyserEl = this.data.analyserEl || this.el; - var el = this.el!; + var el = this.el; analyserEl.addEventListener('audioanalyser-beat', function() { el.setAttribute( @@ -909,12 +909,12 @@ AFRAME.registerComponent('remove-on-event', { removeEventListener: function() { var data = this.data; - var el = this.el!; + var el = this.el; el.removeEventListener(data.event, this._removeEntity); }, _removeEntity: function() { - var el = this.el!; + var el = this.el; if ((el as any).parentEl) { (el as any).parentEl.removeChild(el); } @@ -1016,7 +1016,7 @@ function rgbToHex(r: number, g: number, b: number) { AFRAME.registerComponent('random-material', { init: function() { - this.el!.setAttribute('material', { + this.el.setAttribute('material', { color: this.getRandomColor(), metalness: Math.random(), roughness: Math.random() @@ -1034,7 +1034,7 @@ AFRAME.registerComponent('random-material', { AFRAME.registerComponent('random-torus-knot', { init: function() { - this.el!.setAttribute('geometry', { + this.el.setAttribute('geometry', { primitive: 'torusKnot', radius: Math.random() * 10, radiusTubular: Math.random() * 0.75, diff --git a/types/aframe/test/aframe-tests.ts b/types/aframe/test/aframe-tests.ts index 2d6ff5bb7e..ac61f7f806 100644 --- a/types/aframe/test/aframe-tests.ts +++ b/types/aframe/test/aframe-tests.ts @@ -75,6 +75,7 @@ const Component = registerComponent('test-component', { }, init() { this.data.num = 0; + this.el.setAttribute('custom-attribute', 'custom-value'); }, update() {}, tick() {}, diff --git a/types/airbnb-prop-types/airbnb-prop-types-tests.ts b/types/airbnb-prop-types/airbnb-prop-types-tests.ts new file mode 100644 index 0000000000..7b79086848 --- /dev/null +++ b/types/airbnb-prop-types/airbnb-prop-types-tests.ts @@ -0,0 +1,206 @@ +import * as React from 'react'; +import * as PropTypes from 'prop-types'; +import * as AirbnbPropTypes from 'airbnb-prop-types'; + +class ClassComp extends React.Component { + render() { + return null; + } +} + +function FuncComp() { + return null; +} + +// $ExpectType Requireable +AirbnbPropTypes.and([PropTypes.number]); +// $ExpectType Requireable +AirbnbPropTypes.and([PropTypes.number, AirbnbPropTypes.nonNegativeInteger]); +// $ExpectType Validator +AirbnbPropTypes.and([PropTypes.number, AirbnbPropTypes.integer()], 'foo').isRequired; + +// $ExpectType Requireable +AirbnbPropTypes.between({ lt: 1 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ lte: 2 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ gt: 3 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ gte: 4 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ lt: 1, gt: 0 }); + +// $ExpectType Requireable +AirbnbPropTypes.booleanSome('foo', 'bar', 'baz'); + +// $ExpectType Requireable +AirbnbPropTypes.childrenHavePropXorChildren('foo'); + +// $ExpectType Requireable +AirbnbPropTypes.childrenOf(PropTypes.string); + +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType(ClassComp); +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType(FuncComp); +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType('div'); +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType(ClassComp, FuncComp, 'div'); + +// $ExpectType Requireable +AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.number }); +// $ExpectType Requireable +AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.string, max: 100 }); +// $ExpectType Requireable +AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.bool, min: 0 }); + +// $ExpectType Requireable +AirbnbPropTypes.componentWithName('Foo'); +// $ExpectType Requireable +AirbnbPropTypes.componentWithName(/Foo/); +// $ExpectType Requireable +AirbnbPropTypes.componentWithName('Foo', { stripHOCs: ['connect'] }); + +// $ExpectType Requireable +AirbnbPropTypes.disallowedIf(PropTypes.number, 'foo', PropTypes.string); + +// $ExpectType Requireable +AirbnbPropTypes.elementType(ClassComp); +// $ExpectType Requireable +AirbnbPropTypes.elementType(FuncComp); +// $ExpectType Requireable +AirbnbPropTypes.elementType('div'); +// $ExpectType Requireable +AirbnbPropTypes.elementType('*'); +// $ExpectError +AirbnbPropTypes.elementType(ClassComp, FuncComp, 'div'); + +// $ExpectType Requireable +AirbnbPropTypes.explicitNull(); +// $ExpectType Validator +AirbnbPropTypes.explicitNull().isRequired; + +interface ForbidShape { + foo: string; + bar: number; + baz?: boolean | null; +} + +// $ExpectType ValidationMap<{ foo: string | null; bar: number; baz: boolean | null; }> +AirbnbPropTypes.forbidExtraProps({ + foo: PropTypes.string, + bar: PropTypes.number.isRequired, + baz: PropTypes.bool, +}); + +// $ExpectType ValidationMap +AirbnbPropTypes.forbidExtraProps({ + foo: PropTypes.string.isRequired, + bar: PropTypes.number.isRequired, + baz: PropTypes.bool, +}); + +// $ExpectType Requireable +AirbnbPropTypes.integer(); + +// $ExpectType Requireable<{}> +AirbnbPropTypes.keysOf(PropTypes.number); +// $ExpectType Requireable<{}> +AirbnbPropTypes.keysOf(PropTypes.number, 'foo'); +// $ExpectType Requireable<{}> +AirbnbPropTypes.keysOf(PropTypes.oneOf(['foo', 'bar'])); + +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.number); +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.number, 'foo'); +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.string, 'foo', 'bar'); + +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveTrueProps('foo'); +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveTrueProps('foo', 'bar'); + +// $ExpectType Requireable +AirbnbPropTypes.nChildren(1, PropTypes.number); +// $ExpectType Requireable +AirbnbPropTypes.nChildren(1, AirbnbPropTypes.childrenOfType('span')); + +// $ExpectType Requireable +AirbnbPropTypes.nonNegativeInteger; + +// $ExpectType Requireable +AirbnbPropTypes.nonNegativeNumber(); + +// $ExpectType Requireable +AirbnbPropTypes.numericString(); + +// $ExpectType Requireable<{}> +AirbnbPropTypes.object(); +// $ExpectType Requireable<{ foo: string; }> +AirbnbPropTypes.object<{ foo: string }>(); + +AirbnbPropTypes.or([PropTypes.bool.isRequired, AirbnbPropTypes.explicitNull().isRequired]); +AirbnbPropTypes.or([PropTypes.bool, PropTypes.number, PropTypes.arrayOf(PropTypes.string)]); +AirbnbPropTypes.or([PropTypes.number, PropTypes.string, PropTypes.bool], 'foo'); + +// $ExpectType Requireable +AirbnbPropTypes.range(0, 10); +// $ExpectType Requireable<5> +AirbnbPropTypes.range<5>(0, 10); + +// $ExpectType Requireable +AirbnbPropTypes.requiredBy('foo', PropTypes.string); +// $ExpectType Validator +AirbnbPropTypes.requiredBy('bar', PropTypes.number, 42).isRequired; + +// $ExpectType Requireable<{}> +AirbnbPropTypes.restrictedProp(); +// $ExpectType Requireable<{}> +AirbnbPropTypes.restrictedProp(() => 'Error'); +// $ExpectType Requireable<{}> +AirbnbPropTypes.restrictedProp(() => new Error('Error')); + +// $ExpectType Requireable<{}> +AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }); +// $ExpectType Requireable<{}> +AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }, { validator: PropTypes.string }); +// $ExpectType Requireable<{}> +AirbnbPropTypes.sequenceOf( + { validator: PropTypes.number, min: 0, max: 10 }, + { validator: PropTypes.string }, + { validator: PropTypes.bool }, +); + +interface ShapeShape { + foo: string; + bar?: number | null; +} + +// $ExpectType Requireable<{ foo: string | null; }> +AirbnbPropTypes.shape({ + foo: PropTypes.string, +}); +// $ExpectType Requireable<{ foo: string | null; bar: number | null; }> +AirbnbPropTypes.shape({ + foo: PropTypes.string, + bar: PropTypes.number, +}); +// $ExpectType Requireable +AirbnbPropTypes.shape({ + foo: PropTypes.string.isRequired, + bar: PropTypes.number, +}); + +// $ExpectType Requireable +AirbnbPropTypes.stringStartsWith('foo'); + +// $ExpectType Requireable +AirbnbPropTypes.uniqueArray(); +// $ExpectType Requireable +AirbnbPropTypes.uniqueArray(); + +// $ExpectType Requireable<{ [key: string]: number | null; }> +AirbnbPropTypes.valuesOf(PropTypes.number); diff --git a/types/airbnb-prop-types/index.d.ts b/types/airbnb-prop-types/index.d.ts new file mode 100644 index 0000000000..10c58556c7 --- /dev/null +++ b/types/airbnb-prop-types/index.d.ts @@ -0,0 +1,198 @@ +// Type definitions for airbnb-prop-types 2.11 +// Project: https://github.com/airbnb/prop-types +// Definitions by: Miles Johnson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import * as PropTypes from 'prop-types'; + +export interface ReactComponentLike { + setState(...args: any[]): any; + forceUpdate(...args: any[]): any; + render(): PropTypes.ReactNodeLike; + props: any; + state: any; + context: any; + refs: any; +} + +export interface ReactClassComponentLike { + new (...args: any[]): ReactComponentLike; +} + +export type ReactFunctionComponentLike = (...args: any[]) => PropTypes.ReactNodeLike; + +export type ReactTypeLike = string | ReactClassComponentLike | ReactFunctionComponentLike; + +export interface Specifier { + max?: number; + min?: number; + validator: PropTypes.Validator; +} + +export function and( + propTypes: [PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function and( + propTypes: [PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function and( + propTypes: [PropTypes.Validator, PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function and( + propTypes: Array>, + name?: string, +): PropTypes.Requireable; + +export function between(options: { + lt?: number; + lte?: number; + gt?: number; + gte?: number; +}): PropTypes.Requireable; + +export function booleanSome(...props: string[]): PropTypes.Requireable; + +export function childrenHavePropXorChildren( + prop: string | symbol, +): PropTypes.Requireable; + +export function childrenOf( + propType: PropTypes.Validator

, +): PropTypes.Requireable; + +export function childrenOfType( + ...types: ReactTypeLike[] +): PropTypes.Requireable; + +export function childrenSequenceOf( + ...specifiers: Specifier[] +): PropTypes.Requireable; + +export function componentWithName( + name: string | RegExp, + options?: { stripHOCs: ReadonlyArray }, +): PropTypes.Requireable; + +export function disallowedIf( + propType: PropTypes.Requireable, + otherPropName: string, + otherPropType: PropTypes.Validator, +): PropTypes.Requireable; + +export function elementType( + type: ReactTypeLike, +): PropTypes.Requireable; + +export function explicitNull(): PropTypes.Requireable; + +export function forbidExtraProps( + propTypes: PropTypes.ValidationMap, +): PropTypes.ValidationMap; + +export function integer(): PropTypes.Requireable; + +export function keysOf( + propType: PropTypes.Validator

, + name?: string, +): PropTypes.Requireable; + +export function mutuallyExclusiveProps( + propType: PropTypes.Requireable, + ...propNames: string[] +): PropTypes.Requireable; + +export function mutuallyExclusiveProps( + // tslint:disable-next-line:unified-signatures + propType: PropTypes.Validator, + ...propNames: string[] +): PropTypes.Requireable; + +export function mutuallyExclusiveTrueProps(...propNames: string[]): PropTypes.Requireable; + +export function nChildren( + n: number, + propType?: PropTypes.Validator

, +): PropTypes.Requireable; + +export const nonNegativeInteger: PropTypes.Requireable; + +export function nonNegativeNumber(): PropTypes.Requireable; + +export function numericString(): PropTypes.Requireable; + +export function object(): PropTypes.Requireable; + +export function or(propTypes: [PropTypes.Validator], name?: string): PropTypes.Requireable; + +export function or( + propTypes: [PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function or( + propTypes: [PropTypes.Validator, PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function or( + propTypes: Array>, + name?: string, +): PropTypes.Requireable; + +export function or( + // tslint:disable-next-line:unified-signatures + propTypes: Array>, + name?: string, +): PropTypes.Requireable; + +export function range(min?: number, max?: number): PropTypes.Requireable; + +export function range(min?: number, max?: number): PropTypes.Requireable; + +export function requiredBy

( + requiredByPropName: string, + propType: PropTypes.Validator

, + defaultValue?: any, +): PropTypes.Requireable

; + +export function restrictedProp( + messageFunction?: ( + props: object, + propName: string, + componentName: string, + location: string, + propFullName: string, + ) => string | Error | undefined, +): PropTypes.Requireable; + +export function sequenceOf(...specifiers: Specifier[]): PropTypes.Requireable; + +export function shape( + propTypes: PropTypes.ValidationMap, +): PropTypes.Requireable; + +export function stringStartsWith(string: string): PropTypes.Requireable; + +export function uniqueArray(): PropTypes.Requireable; + +export function uniqueArrayOf( + propType: PropTypes.Validator

, + mapperOrName: ((value: any) => any) | string, + name?: string, +): PropTypes.Requireable; + +export function valuesOf( + propType: PropTypes.Validator, +): PropTypes.Requireable<{ [key: string]: T }>; + +export function withShape( + propType: PropTypes.Validator

, + propTypes: PropTypes.ValidationMap, +): PropTypes.Requireable; diff --git a/types/airbnb-prop-types/tsconfig.json b/types/airbnb-prop-types/tsconfig.json new file mode 100644 index 0000000000..ccefe4943c --- /dev/null +++ b/types/airbnb-prop-types/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", "airbnb-prop-types-tests.ts"] +} diff --git a/types/airbnb-prop-types/tslint.json b/types/airbnb-prop-types/tslint.json new file mode 100644 index 0000000000..71ee04c4e1 --- /dev/null +++ b/types/airbnb-prop-types/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/all-keys/all-keys-tests.ts b/types/all-keys/all-keys-tests.ts new file mode 100644 index 0000000000..6bbb6021c7 --- /dev/null +++ b/types/all-keys/all-keys-tests.ts @@ -0,0 +1,5 @@ +import allKeys = require('all-keys'); + +allKeys(Symbol.prototype); // $ExpectType Set +allKeys(Symbol.prototype, { includeObjectPrototype: false }); // $ExpectType Set +allKeys(Symbol.prototype, { includeSymbols: false }); // $ExpectType Set diff --git a/types/all-keys/index.d.ts b/types/all-keys/index.d.ts new file mode 100644 index 0000000000..9301c8f929 --- /dev/null +++ b/types/all-keys/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for all-keys 2.0 +// Project: https://github.com/sindresorhus/all-keys#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = allKeys; + +/** + * Get all property keys of an object including non-enumerable and inherited ones. + * Like [Reflect.ownKeys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys) + * but traverses up the prototype-chain. + */ +declare function allKeys(obj: object, options?: allKeys.Options): Set; + +declare namespace allKeys { + interface Options { + /** + * Include `Object.prototype` properties like `isPrototypeOf`. + * @default true + */ + includeObjectPrototype?: boolean; + /** + * Include [Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) keys. + * @default true + */ + includeSymbols?: boolean; + } +} diff --git a/types/all-keys/tsconfig.json b/types/all-keys/tsconfig.json new file mode 100644 index 0000000000..a6f20f786f --- /dev/null +++ b/types/all-keys/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", + "all-keys-tests.ts" + ] +} diff --git a/types/all-keys/tslint.json b/types/all-keys/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/all-keys/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/amap-js-sdk/amap-js-sdk-tests.ts b/types/amap-js-sdk/amap-js-sdk-tests.ts new file mode 100644 index 0000000000..f09bca3760 --- /dev/null +++ b/types/amap-js-sdk/amap-js-sdk-tests.ts @@ -0,0 +1,22 @@ +const aMap = new AMap.Map('id', { + resizeEnable: true, + animateEnable: true +}); + +aMap.setCenter(new AMap.LngLat(0, 0)); + +AMap.plugin(['someplugin'], () => { + console.log('plugin loaded'); +}); + +AMap.convertFrom([116.3, 39.9], 'gps', (status, result) => { + if (result.info === 'ok') { + const _ = result.locations; + } +}); + +new AMap.Marker({ + map: aMap, + title: '', + position: new AMap.LngLat(0, 0), +}); diff --git a/types/amap-js-sdk/index.d.ts b/types/amap-js-sdk/index.d.ts new file mode 100644 index 0000000000..a1b93e6cb3 --- /dev/null +++ b/types/amap-js-sdk/index.d.ts @@ -0,0 +1,1392 @@ +// Type definitions for amap-js-sdk 1.4 +// Project: http://lbs.amap.com/api/javascript-api/summary/ +// Definitions by: Bian Zhongjie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace AMap { + type EventCallback = (...args: any[]) => void; + type GenericEventCallback = (res: T) => void; + + /** + * 加载插件 + * @param pluginNames + * @param ready + */ + function plugin(pluginNames: string[], ready?: () => void): void; + + /** + * 加载服务 + * @param serviceName + * @param ready + */ + function service(serviceName: string, ready?: () => void): void; + + namespace event { + /** + * 注册DOM对象事件:给DOM对象注册事件,并返回eventListener。运行AMap.event.removeListener(eventListener)可以删除该事件的监听器。 + * @param instance:需注册事件的DOM对象(必填) + * @param eventName:事件名称(必填) + * @param handler:事件功能函数(必填) + * @param context:事件上下文(可选,缺省时,handler中this指向参数instance引用的对象,否则this指向context引用的对象) + */ + const addDomListener: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener; + + /** + * 注册对象事件:给对象注册事件,并返回eventListener。运行AMap.event.removeListener(eventListener)可以删除该事件的监听器。 + * @param instance:需注册事件的对象(必填) + * @param eventName:事件名称(必填) + * @param handler:事件功能函数(必填) + * @param context:事件上下文(可选,缺省时,handler中this指向参数instance引用的对象,否则this指向context引用的对象) + */ + const addListener: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener; + + /** + * 类似于addListener,但处理程序会在处理完第一个事件后将自已移除。 + */ + const addListenerOnce: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener; + + /** + * 删除由上述 event.addDomListener 和 event.addListener 传回的指定侦听器。 + */ + const removeListener: (listener: EventListener) => void; + + /** + * 触发非DOM事件:触发非DOM事件eventName,extArgs将扩展到事件监听函数(handler)接受到的event参数中。如:在extArgs内写入{m:10,p:2},eventName监听函数(handler)可以接收到包含m,p两个key值的event对象。 + */ + const trigger: (instance: any, eventName: string, extArgs: any) => void; + } + + /** + * 此对象用于表示地图、覆盖物、叠加层上的各种鼠标事件返回,包含以下字段: + */ + interface MapsEventOptions { + lnglat: LngLat; + pixel: Pixel; + type: string; + target: any; + } + + abstract class EventBindable { + on(eventName: string, callback: EventCallback): void; + off(eventName: string, callback: EventCallback): void; + } + + /* --------------------------- 基础类 --------------------------- */ + /* 参考地址:http://lbs.amap.com/api/javascript-api/reference/core */ + + /** + * 像素坐标,确定地图上的一个像素点。 + */ + class Pixel { + /** + * 构造一个像素坐标对象。 + */ + constructor(x: number, y: number); + /** + * 获得X方向像素坐标 + */ + getX(): number; + + /** + * 获得Y方向像素坐标 + */ + getY(): number; + + /** + * 当前像素坐标与传入像素坐标是否相等 + */ + equals(point: Pixel): boolean; + + /** + * 以字符串形式返回像素坐标对象 + */ + toString(): string; + } + + /** + * 地物对象的像素尺寸 + */ + class Size { + /** + * 构造尺寸对象 + * @param width 宽度,单位:像素 + * @param height 高度,单位:像素 + */ + constructor(width: number, height: number); + + /** + * 获得宽度 + */ + getWidth(): number; + + /** + * 获得高度 + */ + getHeight(): number; + + /** + * 以字符串形式返回尺寸大小对象 + */ + toString(): string; + } + + /** + * 经纬度坐标,确定地图上的一个点 + */ + class LngLat { + /** + * 构造一个地理坐标对象 + * @param lng 经度 + * @param lat 纬度 + */ + constructor(lng: number, lat: number); + + /** + * 当前经纬度坐标值经度移动w,纬度移动s,得到新的坐标。 + * + * @param w 经度,向右移为正值,单位:米 + * @param s 纬度,向上移为正值,单位:米 + */ + offset(w: number, s: number): LngLat; + + /** + * 计算当前经纬度和传入经纬度或者经纬度数组连线之间的地面距离,单位为米 + * + * @param lnglat 传入的经纬度 + */ + distance(lnglat: LngLat | [number, number]): number; + + /** + * 获取经度值 + */ + getLng(): number; + + /** + * 获取纬度值 + */ + getLat(): number; + + /** + * 判断当前坐标对象与传入坐标对象是否相等 + * + * @param lnglat 传入坐标对象 + */ + equals(lnglat: LngLat): boolean; + + /** + * LngLat对象以字符串的形式返回 + */ + toString(): string; + } + + /** + * 地物对象的经纬度矩形范围 + */ + class Bounds { + /** + * 构造一个矩形范围 + * @param southWest 西南角经纬度坐标 + * @param northEast 东北角经纬度坐标 + */ + constructor(southWest: LngLat, northEast: LngLat); + + /** + * 判断指定点坐标是否在矩形范围内 + * @param point 指定点 + */ + contains(point: LngLat): boolean; + + /** + * 获取当前Bounds的中心点经纬度坐标 + */ + getCenter(): LngLat; + + /** + * 获取西南角坐标 + */ + getSouthWest(): LngLat; + + /** + * 获取东北角坐标 + */ + getNorthEast(): LngLat; + + /** + * 以字符串形式返回地物对象的矩形范围 + */ + toString(): string; + } + + interface TileLayerOptions { + map: Map; + tileSize: number; + tileUrl: string; + errorUrl: string; + getTileUrl: (x: number, y: number, z: number) => string; + zIndex: number; + opacity: number; + zooms: number[]; + detectRetina: boolean; + } + + abstract class Layer extends EventBindable { + setOpacity(alpha: number): void; + show(): void; + hide(): void; + getTiles(): string[]; + reload(): void; + setTileUrl(): void; + getZooms(): number[]; + setzIndex(index: number): void; + setMap(map: Map): void; + } + + class TileLayer extends Layer { + constructor(tileOpt?: { + map: Map, + tileSize?: number, + tileUrl?: string, + errorUrl?: string, + getTileUrl?: (x: number, y: number, z: number) => string, + zIndex?: number, + opacity?: number, + zooms?: number[], + detectRetina?: boolean + }); + } + + namespace TileLayer { + abstract class MapTypeLayer extends Layer { + constructor(options?: { + map: Map, + zIndex?: number, + opacity?: number, + zooms?: number[], + detectRetina?: boolean + }); + } + + class Satellite extends MapTypeLayer { + } + + class RoadNet extends MapTypeLayer { + } + + class Traffic extends MapTypeLayer { + constructor(options?: { + map: Map, + zIndex?: number, + opacity?: number, + zooms?: number[], + detectRetina?: boolean, + autoRefresh?: boolean, + interval?: number + }); + + interval: number; + autoRefresh: boolean; + } + } + + class IndoorMap { + constructor(opts: { + zIndex?: number, + opacity?: number, + cursor?: string, + hideFloorBar?: boolean, + alwaysShow?: boolean + }); + + showIndoorMap(indoorid: string, floor: number, shopid: string): void; + + showFloor(floor: number, noMove: boolean): void; + + setMap(map: Map): void; + + show(): void; + + hide(): void; + + setzIndex(): void; + + showFloorBar(): void; + + hideFloorBar(): void; + + setOpacity(alpha: number): void; + + getOpacity(): number; + + showLabels(): void; + + hideLabels(): void; + + getSelectedBuildingId(): string; + + getSelectedBuilding(): string; + } + + interface MapOptions { + view?: View2D; + layers?: TileLayer[]; + level?: number; + center?: LngLat; + labelzIndex?: number; + zooms?: number[]; + lang?: string; + cursor?: string; + crs?: string; + animateEnable?: boolean; + isHotspot?: boolean; + defaultLayer?: TileLayer; + rotateEnable?: boolean; + resizeEnable?: boolean; + showIndoorMap?: boolean; + indoorMap?: IndoorMap; + expandZoomRange?: boolean; + dragEnable?: boolean; + zoomEnable?: boolean; + doubleClickZoom?: boolean; + keyboardEnable?: boolean; + jogEnable?: boolean; + scrollWheel?: boolean; + touchZoom?: boolean; + mapStyle?: string; + features?: string[]; + } + + class View2D { + constructor(opt: { + center?: LngLat, + rotation?: number, + zoom?: number, + crs?: 'EPSG3857'|'EPSG3395'|'EPSG4326' + }); + + /** + * To silence lint error, this class has to be exists. + */ + toString(): string; + } + + class Map extends EventBindable { + constructor(mapDiv: string, opts?: MapOptions); + + getZoom(): number; + + getLayers(): TileLayer[]; + + getCenter(): LngLat; + + getCity(callback: (result: { + provice: string, + city: string, + citycode: string, + district: string + }) => void): void; + + getBounds(): Bounds; + getlabelzIndex(): number; + getLimitBounds(): Bounds; + getLang(): string; + getSize(): Size; + getRotation(): number; + getStatus(): any; + getDefaultCursor(): string; + getResolution(point: LngLat): number; + getScale(dpi: number): number; + setZoom(level: number): void; + setlabelzIndex(index: number): void; + setLayers(layers: TileLayer[]): void; + add(overlayers: any[]): void; + remove(overlayers: any[]): void; + getAllOverlays(type: string): Marker[] | Circle[] | Polygon[] | Polyline[]; + setCenter(position: LngLat): void; + setZoomAndCenter(zoomLevel: number, center: LngLat): void; + setCity(city: string, callback: () => void): void; + setBounds(bound: Bounds): void; + setLimitBounds(bound: Bounds): void; + clearLimitBounds(): void; + setLang(lang: string): void; + setRotation(rotation: number): void; + setStatus(status: any): void; + setDefaultCursor(cursor: string): void; + zoomIn(): void; + zoomOut(): void; + panTo(position: LngLat): void; + panBy(x: number, y: number): void; + setFitView(overlayList?: any[]): void; + clearMap(): void; + destroy(): void; + plugin(name: string| string[], callback: () => void): void; + addControl(obj: any): void; + removeControl(obj: any): void; + clearInfoWindow(): void; + pixelToLngLat(pixel: Pixel, level: number): LngLat; + lnglatToPixel(lnglat: LngLat, level: number): Pixel; + containerToLngLat(pixel: Pixel, level: number): LngLat; + lngLatToContainer(lnglat: LngLat, level: number): Pixel; + setMapStyle(style: string): void; + getMapStyle(): string; + setFeatures(features: string[]): void; + getFeatures(): string[]; + setDefaultLayer(layer: TileLayer): void; + } + + class Icon { + constructor(options?: { + size?: Size, + imageOffset?: Pixel, + image?: string, + imageSize?: Size + }); + + getImageSize(): Size; + setImageSize(size: Size): void; + } + + /** + * MarkerShape用于划定Marker的可点击区域范围。需要注意的是,在IE浏览器中图标透明区域默认为不触发事件,因此MarkerShape在IE中不起作用。 + */ + class MarkerShape { + constructor(options: { + /** + * + * 可点击区域组成元素数组,存放图形的像素坐标等信息,该数组元素由type决定: + * - circle:coords格式为 [x1, y1, r],x1,y1为圆心像素坐标,r为圆半径 + * - poly: coords格式为 [x1, y1, x2, y2 … xn, yn],各x,y表示多边形边界像素坐标 + * - rect: coords格式为 [x1, y1, x2, y2],x1,y1为矩形左上角像素坐标,x2,y2为矩形右下角像素坐标 + * Markshape的像素坐标是指相对于marker的左上角的像素坐标偏移量 + */ + coords?: number[], + + /** + * 可点击区域类型,可选值: + * - circle:圆形 + * - poly:多边形 + * - rect:矩形 + */ + type?: string + }); + + /** + * To silence lint error, this class has to be exists. + */ + toString(): string; + } + + interface MarkerOptions { + map?: Map; + position?: LngLat; + offset?: Pixel; + icon?: string|Icon; + content?: string| HTMLElement; + topWhenClick?: boolean; + topWhenMouseOver?: boolean; + draggable?: boolean; + raiseOnDrag?: boolean; + cursor?: string; + visible?: boolean; + zIndex?: number; + angle?: number; + autoRotation?: boolean; + animation?: string; + shadow?: Icon; + title?: string; + clickable?: boolean; + shape?: MarkerShape; + extData?: any; + label?: { content: string, offset: Pixel }; + } + + /** + * 点标记。 + */ + class Marker extends EventBindable { + constructor(options?: MarkerOptions); + + markOnAMAP(obj: { + name: string, + position: LngLat + }): void; + + getOffset(): Pixel; + setOffset(offset: Pixel): void; + + setAnimation(animate: string): void; + getAnimation(): string; + + setClickable(clickable: boolean): void; + getClickable(): boolean; + + getPosition(): LngLat; + setPosition(lnglat: LngLat): void; + + setAngle(angle: number): void; + getAngle(): number; + + setLabel(label: { + content?: string, + offset?: Pixel + }): void; + getLabel(): { + content?: string, + offset?: Pixel + }; + + setzIndex(index: number): void; + + getIcon(): string|Icon; + setIcon(content: string|Icon): void; + + setDraggable(draggable: boolean): void; + getDraggable(): boolean; + + hide(): void; + show(): void; + + setCursor(cursor: string): void; + + setContent(content: string| HTMLElement): void; + getContent(): string; + + moveAlong(lnglatlist: LngLat[], speed?: number, f?: (k: number) => number, circlable?: boolean): void; + moveTo(lnglat: LngLat, speed?: number, f?: (k: number) => number): void; + stopMove(): void; + setMap(map: Map): void; + getMap(): Map; + setTitle(title: string): void; + getTitle(): string; + setTop(isTop: boolean): void; + getTop(): boolean; + setShadow(icon: Icon): void; + getShadow(): Icon; + setShape(shape: MarkerShape): void; + getShape(): MarkerShape; + setExtData(ext: any): void; + getExtData(): any; + } + + interface MarkerClustererOptions { + gridSize?: number; + minClusterSize?: number; + maxZoom?: number; + averageCenter?: boolean; + styles?: any[]; + renderCluserMarker?: (obj: any) => void; + zoomOnClick?: boolean; + } + + /** + * 用于地图上加载大量点标记,提高地图的绘制和显示性能。 + */ + class MarkerClusterer extends EventBindable { + constructor(map: Map, markers: Marker[], opt?: MarkerClustererOptions); + + /** + * 添加一个需进行聚合的点标记 + * @param marker + */ + addMarker(marker: Marker): void; + + /** + * 删除一个聚合的点标记 + * @param marker 点标记 + */ + removeMarker(marker: Marker): void; + + /** + * 获取聚合点的总数量 + */ + getClustersCount(): number; + + /** + * 获取聚合网格的像素大小 + */ + getGridSize(): number; + + /** + * 获取地图中点标记的最大聚合级别 + */ + getMaxZoom(): number; + + /** + * 获取单个聚合的最小数量 + */ + getMinClusterSize(): number; + + /** + * 获取聚合的样式风格集合 + */ + getStyles(): any[]; + + /** + * 设置聚合网格的像素大小 + * @param size + */ + setGridSize(size: number): void; + + /** + * 设置地图中点标记的最大聚合级别 + * @param zoom + */ + setMaxZoom(zoom: number): void; + + /** + * 设置单个聚合的最小数量 + * @param size + */ + setMinClusterSize(size: number): void; + + /** + * 设置聚合的样式风格 + * @param styles + */ + setStyles(styles: any[]): void; + + /** + * 从地图上彻底清除所有聚合点标记 + */ + clearMarkers(): void; + + /** + * 设置将进行点聚合的地图对象 + * @param map + */ + setMap(map: Map): void; + + /** + * 设置将进行点聚合显示的点标记集合 + * @param markers + */ + setMarkers(markers: Marker[]): void; + + /** + * 获取该点聚合的地图对象 + */ + getMap(): Map; + + /** + * 获取该点聚合中的点标记集合 + */ + getMarkers(): Marker[]; + + /** + * 添加一组需进行聚合的点标记 + */ + addMarkers(markers: Marker[]): void; + + /** + * 删除一组聚合的点标记 + * @param markers + */ + removeMarkers(markers: Marker[]): void; + + /** + * 获取单个聚合点位置是否是聚合内所有标记的平均中心 + */ + isAverageCenter(): boolean; + + /** + * 设置单个聚合点位置是否是聚合内所有标记的平均中心 + * @param averageCenter + */ + setAverageCenter(averageCenter: boolean): void; + } + + interface CircleOptions { + map: Map; + zIndex?: number; + center: LngLat; + radius?: number; + strokeColor?: string; + strokeOpacity?: number; + fillColor?: string; + fillOpacity?: string; + strokeStyle?: string; + extData?: any; + strokeDasharray?: number[]; + } + + class Circle { + constructor(options?: CircleOptions); + setCenter(lnglat: LngLat): void; + getCenter(): LngLat; + getBounds(): Bounds; + setRadius(radius: number): void; + getRadius(): number; + setOptions(circleopt: CircleOptions): void; + getOptions(): CircleOptions; + hide(): void; + show(): void; + setMap(map: Map): void; + setExtData(ext: any): void; + getExtData(): any; + contains(point: LngLat): boolean; + } + + interface PolygonOptions { + map?: Map; + zIndex?: number; + path?: LngLat[]|LngLat[][]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + fillColor?: string; + fillOpacity?: number; + extData?: any; + strokeStyle?: string; + strokeDasharray?: number[]; + } + + class Polygon extends EventBindable { + constructor(options?: PolygonOptions); + + setPath(path: LngLat[]|LngLat[][]): void; + getPath(): LngLat[]|LngLat[][]; + setOptions(opt: PolygonOptions): void; + getOptions(): PolygonOptions; + getBounds(): Bounds; + getArea(): number; + hide(): void; + show(): void; + setMap(map: Map): void; + setExtData(ext: any): void; + getExtData(): any; + contains(point: LngLat): boolean; + } + + interface PolylineOptions { + map?: Map; + zIndex?: number; + geodesic?: boolean; + isOutline?: boolean; + outlineColor?: string; + path?: LngLat[]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + strokeStyle?: string; + strokeDasharray?: number[]; + extData?: any; + } + + class Polyline extends EventBindable { + constructor(options?: PolylineOptions); + + setPath(path: LngLat[]): void; + getPath(): LngLat[]; + + setOptions(opt: PolylineOptions): void; + getOptions(): PolylineOptions; + + getLength(): number; + getBounds(): Bounds; + hide(): void; + show(): void; + + setMap(map: Map): void; + setExtData(ext: any): void; + getExtData(): any; + } + + interface MapControl { + show(): void; + hide(): void; + } + + class MapType implements MapControl { + constructor(options?: { + defaultType?: number; + showTraffic?: boolean; + showRoad?: boolean; + }); + + show(): void; + hide(): void; + } + + class OverView extends EventBindable implements MapControl { + constructor(options?: { + tileLayer?: TileLayer[], + isOpen?: boolean, + visible?: boolean + }); + + open(): void; + close(): void; + setTileLayer(layer: TileLayer): void; + getTileLayer(): TileLayer; + show(): void; + hide(): void; + } + + class Scale extends EventBindable implements MapControl { + offset: Pixel; + position: string; + + show(): void; + hide(): void; + } + + class ToolBar extends EventBindable implements MapControl { + constructor(options?: { + offset?: Pixel, + position?: string, + ruler?: boolean, + noIpLocate?: boolean, + locate?: boolean, + liteStyle?: boolean, + direction?: boolean, + autoPosition?: boolean, + locationMarker?: Marker, + useNative?: boolean + }); + + getOffset(): Pixel; + setOffset(offset: Pixel): void; + hideRuler(): void; + showRuler(): void; + hideDirection(): void; + showDirection(): void; + hideLocation(): void; + showLocation(): void; + doLocation(): void; + getLocation(): { lng: number, lat: number }; + show(): void; + hide(): void; + } + + class InfoWindow extends EventBindable { + constructor(options?: { + isCustom?: boolean, + autoMove?: boolean, + closeWhenClickMap?: boolean, + content?: string | HTMLElement, + size?: Size, + offset?: Pixel, + position?: LngLat, + showShadow?: boolean + }); + + open(map: Map, pos: LngLat): void; + close(): void; + getIsOpen(): boolean; + setPosition(lnglat: LngLat): void; + getPosition(): LngLat; + setSize(size: Size): void; + getSize(): Size; + getContent(): string; + setContent(content: string|HTMLElement): void; + } + + class AdvancedInfoWindow extends EventBindable { + constructor(options?: { + autoMove?: boolean, + closeWhenClickMap?: boolean, + content?: string|HTMLElement, + offset?: Pixel, + position?: LngLat, + panel?: string|HTMLElement, + searchRadius?: number, + placeSearch?: boolean, + driving?: boolean, + walking?: boolean, + transit?: boolean, + asOrigin?: boolean, + asDestination?: boolean + }); + + open(map: Map, pos: LngLat): void; + close(): void; + getIsOpen(): boolean; + setPosition(lnglat: LngLat): void; + getPosition(): LngLat; + setContent(content: string|HTMLElement): void; + getContent(): string; + } + + class Geolocation extends EventBindable { + constructor(options: { + enableHighAccuracy?: boolean, + timeout?: number, + noIpLocate?: boolean, + maximumAge?: number, + convert?: boolean, + showButton?: boolean, + buttonDom?: string|HTMLElement, + buttonPosition?: string, + buttonOffset?: Pixel, + showMarker?: boolean, + markerOptions?: MarkerOptions, + showCircle?: boolean, + circleOptions?: CircleOptions, + panToLocation?: boolean, + zoomToAccuracy?: boolean, + useNative?: boolean + }); + + isSupported(): boolean; + getCurrentPosition(): void; + watchPosition(): number; + clearWatch(watchId: number): number; + } + + interface GeolocationResult { + position: LngLat; + accuracy: number; + isConverted: boolean; + info: string; + } + + interface GeolocationError { + info: string; + } + + interface BusinessArea { + id: string; + name: string; + location: string; + } + + interface Road { + id: string; + name: string; + distance: number; + location: LngLat; + direction: string; + } + + interface Cross { + distance: number; + direction: string; + location: LngLat; + first_id: string; + first_name: string; + second_id: string; + second_name: string; + } + + interface AddressComponent { + province: string; + city: string; + citycode: string; + district: string; + adcode: string; + township: string; + street: string; + streetNumber: string; + neighborhood: string; + neighborhoodType: string; + building: string; + buildingType: string; + businessAreas: BusinessArea[]; + } + + interface Geocode { + addressComponent: AddressComponent; + formattedAddress: string; + location: LngLat; + adcode: string; + level: string; + } + + interface ReGeocode { + addressComponent: AddressComponent; + formattedAddress: string; + roads: Road[]; + crosses: Cross[]; + pois: ReGeocodePoi[]; + } + + interface ReGeocodePoi { + id: string; + name: string; + type: string; + tel: string; + distance: number; + direction: string; + address: string; + location: LngLat; + businessArea: string; + } + + interface GeocodeResult { + info: string; + geocodes: LngLat[]; + resultNum: number; + } + + interface ReGeocodeResult { + info: string; + regeocode: ReGeocode; + } + + class Geocoder { + constructor(opts?: { + city?: string, + radius?: number, + batch?: boolean, + extensions?: string + }); + + getLocation(address: string, callback?: (status?: string, result?: string | GeocodeResult) => void): void; + + setCity(city: string): void; + + getAddress(location: LngLat|LngLat[], callback: (status?: string, result?: string | ReGeocodeResult) => void): void; + } + + /** + * 坐标转换结果 + */ + interface ConvertorResult { + info: string; + locations: LngLat[]; + } + + /** + * 坐标转换 + */ + function convertFrom(lnglat: LngLat | LngLat[] | [number, number], type: string, result: (status: string, result: ConvertorResult) => void): void; + + interface Poi { + id: string; + name: string; + type: string; + location: LngLat; + address: string; + distance: number; + tel: string; + + website: string; + pcode: string; + citycode: string; + adcode: string; + postcode: string; + pname: string; + cityname: string; + adname: string; + email: string; + entr_location: LngLat; + exit_location: LngLat; + groupbuy: boolean; + discount: boolean; + } + + interface CitySearchResult { + city: string; + bounds: Bounds; + } + + class CitySearch extends EventBindable { + getLocalCity(callback: (status: string, result: string | CitySearchResult) => void): void; + getCityByIp(ip: string, callback: (status: string, result: string | CitySearchResult) => void): void; + } + + enum DrivingPolicy { + LEAST_TIME, + LEAST_FEE, + LEAST_DISTANCE, + REAL_TRAFFIC + } + + interface ViaCity { + name: string; + citycode: string; + adcode: string; + districts: District[]; + } + + interface District { + name: string; + adcode: string; + } + + interface TMC { + lcode: string; + distance: number; + status: string; + } + + interface DriveStep { + start_location: LngLat; + end_location: LngLat; + instruction: string; + action: string; + assist_action: string; + orientation: string; + road: string; + distance: number; + tolls: number; + tolls_distance: number; + toll_road: string; + time: number; + path: LngLat[]; + cities?: ViaCity[]; + tmcs?: TMC[]; + } + + interface DriveRoute { + distance: number; + time: number; + policy: string; + tolls: number; + tolls_distance: number; + steps: DriveStep[]; + } + + interface DrivingResult { + info: string; + origin: LngLat; + destination: LngLat|Poi; + start: Poi; + waypoints: Poi; + taxi_cost: number; + routes: DriveRoute[]; + } + + class Driving extends EventBindable { + constructor(options?: { + policy?: DrivingPolicy, + extensions?: string, + map?: Map, + panel?: string|HTMLElement, + hideMarkers?: boolean, + showTraffic?: boolean + }); + + search(origin: LngLat, destination: LngLat, opts?: { + waypoints: LngLat[] + }, callback?: (status: string, result: string|DrivingResult) => void): void; + + search(point: Array<{ + keyword: string, + city: string + }>, callback: (status: string, result: string|DrivingResult) => void): void; + + setPolicy(policy: DrivingPolicy): void; + setAvoidPolygons(path: LngLat[][]): void; + setAvoidRoad(road: string): void; + clearAvoidRoad(): void; + clearAvoidPolygons(): void; + getAvlidPolygons(): LngLat[][]; + getAvoidRoad(): string; + clear(): void; + searchOnAMAP(obj: { + origin?: LngLat, + originName?: string, + destination?: LngLat, + destinationName?: string + }): void; + } + + // 天气插件 + + interface WeatherLiveResult { + info: string; + province: string; + city: string; + adcode: string; + weather: string; + temperature: number; + windDirection: string; + windPower: number; + humidity: string; + reportTime: string; + } + + interface Forecast { + date: string; + week: string; + dayWeather: string; + nightWeather: string; + dayTemp: number; + nightTemp: number; + dayWindDir: string; + nightWindDir: string; + dayWindPower: string; + nightWindPower: string; + } + + interface WeatherForecastResult { + info: string; + province: string; + city: string; + adcode: string; + reportTime: string; + forecasts: Forecast[]; + } + + class Weather { + /** + * 查询实时天气信息 + * @param district 支持城市名称/区域编码(如:“杭州市”/“330100”) + * @param callback 当请求成功时ErrorStatus为null,当请求不成功时ErrorStatus为Obj + */ + getLive(district: string, callback: (errorStatus: any, result: WeatherLiveResult) => void): void; + + /** + * 查询四天预报天气,包括查询当天天气信息 + * @param district 支持城市名称/区域编码(如:“杭州市”/“330100”) + * @param callback 当请求成功时ErrorStatus为null,当请求不成功时ErrorStatus为Obj + */ + getForecast(district: string, callback: (errorStatus: any, result: WeatherForecastResult) => void): void; + } + + interface Tip { + name: string; + district: string; + adcode: string; + } + + interface AutocompleteResult { + info: string; + count: number; + tips: Tip[]; + } + + class Autocomplete { + constructor(opts: { + type?: string, + city?: string, + datatype?: string, + citylimit?: boolean, + input?: string + }); + + search(keyword: string, callback: (status: string, result: string | AutocompleteResult) => void): void; + } + + interface SelectChangeEvent { + type: string; + id: string; + marker: Marker; + listElement: HTMLLIElement; + data: Poi; + } + + interface PoiList { + pois: Poi[]; + pageIndex: number; + pageSize: number; + count: number; + } + + interface CityInfo { + name: string; + citycode: string; + adcode: string; + count: number; + } + + interface SearchResult { + info: string; + poiList: PoiList; + keywordList: string[]; + cityList: CityInfo[]; + } + + interface Photo { + title: string; + url: string; + } + + interface Content { + id: string; + name: string; + } + + interface Discount { + title: string; + detail: string; + start_time: string; + end_time: string; + sold_num: string; + photos: Photo[]; + url: string; + provider: string; + } + + interface Groupbuy { + title: string; + type_code: string; + type: string; + detail: string; + stime: string; + etime: string; + count: number; + sold_num: number; + original_price: number; + groupbuy_price: number; + discount: number; + ticket_address: string; + ticket_tel: string; + photos: Photo[]; + url: string; + provider: string; + } + + class PlaceSearch { + constructor(opts: { + city?: string, + citylimit?: boolean, + children?: number, + type?: string, + lang?: string, + pageSize?: number, + pageIndex?: number, + extensions?: string, + map?: Map, + panel?: string|HTMLElement, + showCover?: boolean, + renderStyle?: string, + autoFitView?: boolean + }); + + search(keyword: string, callback: (status: string, result: string | SearchResult) => void): void; + searchNearBy(keyword: string, center: LngLat, radius: number, callback: (status: string, result: string|SearchResult) => void): void; + searchInBounds(keyword: string, bounds: Bounds|Polygon, callback: (status: string, result: string|SearchResult) => void): void; + getDetails(POIID: string, callback: (status: string, result: string|SearchResult) => void): void; + setType(type: string): void; + setCityLimit(p: boolean): void; + setPageIndex(pageIndex: number): void; + setPageSize(setPageSize: number): void; + setCity(city: string): void; + setLang(lang: string): string; + getLang(): string; + clear(): void; + poiOnAMAP(obj: any): void; + detailOnAMAP(obj: any): void; + } + + interface DistrictSearchOptions { + level: string; + showbiz?: boolean; + extensions?: string; + subdistrict?: number; + } + + interface DistrictSearchResult { + info: string; + districtList: District[]; + } + + interface District { + name: string; + center: LngLat; + citycode: string; + adcode: string; + level: string; + boundaries: LngLat[]; + districtList: District[]; + } + + class DistrictSearch { + constructor(opts: DistrictSearchOptions); + + search(keywords: string, callback?: (status: string, result: string| DistrictSearchResult) => void, opts?: DistrictSearchOptions): void; + setLevel(level: string): void; + setSubdistrict(district: number): void; + } + } diff --git a/types/amap-js-sdk/tsconfig.json b/types/amap-js-sdk/tsconfig.json new file mode 100644 index 0000000000..ba4581a859 --- /dev/null +++ b/types/amap-js-sdk/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", + "amap-js-sdk-tests.ts" + ] +} diff --git a/types/amap-js-sdk/tslint.json b/types/amap-js-sdk/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/amap-js-sdk/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/analytics-node/analytics-node-tests.ts b/types/analytics-node/analytics-node-tests.ts index 6740aaccff..a7dc5336ec 100644 --- a/types/analytics-node/analytics-node-tests.ts +++ b/types/analytics-node/analytics-node-tests.ts @@ -1,10 +1,10 @@ import Analytics = require("analytics-node"); -var analytics: Analytics; +let analytics: Analytics; function testConfig(): void { analytics = new Analytics('YOUR_WRITE_KEY', { flushAt: 20, - flushAfter: 10000, + flushInterval: 10000, host: "http://example.com", enable: true }); @@ -33,7 +33,7 @@ function testIdentify(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } @@ -59,7 +59,7 @@ function testTrack(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } @@ -91,20 +91,20 @@ function testPage(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } function testAlias(): void { // the anonymous user does actions ... - analytics.track({ userId: 'anonymous_user', event: 'Anonymous Event' }) + analytics.track({ userId: 'anonymous_user', event: 'Anonymous Event' }); // the anonymous user signs up and is aliased - analytics.alias({ previousId: 'anonymous_user', userId: 'identified@gmail.com' }) + analytics.alias({ previousId: 'anonymous_user', userId: 'identified@gmail.com' }); // the identified user is identified - analytics.identify({ userId: 'identified@gmail.com', traits: { plan: 'Free' } }) + analytics.identify({ userId: 'identified@gmail.com', traits: { plan: 'Free' } }); // the identified user does actions ... - analytics.track({ userId: 'identified@gmail.com', event: 'Identified Action' }) + analytics.track({ userId: 'identified@gmail.com', event: 'Identified Action' }); } function testGroup(): void { @@ -128,35 +128,41 @@ function testGroup(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } function testIntegrations(): void { analytics.track({ - event: 'Upgraded Membershipt', + event: 'Upgraded Membership', userId: '97234974', integrations: { - 'All': false, - 'Vero': true, - 'Google Analytics': false + All: false, + Vero: true, + 'Google Analytics': false, + AppsFlyer: { + appsflyer_id: 'example-id' + } } }); analytics.track({ - event: 'Upgraded Membershipt', + event: 'Upgraded Membership', userId: '97234974', integrations: { - 'All': false, - 'Vero': true, - 'Google Analytics': false + All: false, + Vero: true, + 'Google Analytics': false, + AppsFlyer: { + appsflyer_id: 'example-id' + } } }, (err, data) => { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } @@ -164,8 +170,10 @@ function testIntegrations(): void { function testFlush(): void { analytics.flush(); analytics.flush((err, batch) => { - if (err) { alert("Oh nos!"); } - else { console.log(batch.batch[0].type); } + if (err) { + alert("Oh nos!"); + } else { + console.log(batch.batch[0].type); + } }); } - diff --git a/types/analytics-node/index.d.ts b/types/analytics-node/index.d.ts index cc9e5386e2..168e0f17ea 100644 --- a/types/analytics-node/index.d.ts +++ b/types/analytics-node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Segment's analytics.js for Node.js +// Type definitions for analytics-node 3.1 // Project: https://segment.com/docs/libraries/node/ // Definitions by: Andrew Fong // Thomas Thiebaud @@ -19,7 +19,7 @@ declare namespace AnalyticsNode { _metadata: { nodeVersion: string; [key: string]: any; - }, + }; timestamp?: Date; messageId?: string; anonymousId?: string | number; @@ -27,19 +27,21 @@ declare namespace AnalyticsNode { } interface Data { - batch: Message[], + batch: Message[]; timestamp: Date; sentAt: Date; } interface Integrations { - [index: string]: boolean; + [integration_name: string]: IntegrationValue; } - export class Analytics { + type IntegrationValue = boolean | { [integration_key: string]: any }; + + class Analytics { constructor(writeKey: string, opts?: { flushAt?: number, - flushAfter?: number, + flushInterval?: number, host?: string, enable?: boolean }); @@ -49,9 +51,9 @@ declare namespace AnalyticsNode { identify(message: { userId?: string | number; anonymousId?: string | number; - traits?: Object; + traits?: any; timestamp?: Date; - context?: Object; + context?: any; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; @@ -60,9 +62,9 @@ declare namespace AnalyticsNode { userId?: string | number; anonymousId?: string | number; event: string; - properties?: Object; + properties?: any; timestamp?: Date; - context?: Object; + context?: any; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; @@ -73,9 +75,9 @@ declare namespace AnalyticsNode { anonymousId?: string | number; category?: string; name?: string; - properties?: Object; + properties?: any; timestamp?: Date; - context?: Object; + context?: any; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; @@ -93,8 +95,8 @@ declare namespace AnalyticsNode { userId?: string | number; anonymousId?: string | number; groupId: string | number; - traits?: Object; - context?: Object; + traits?: any; + context?: any; timestamp?: Date; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; diff --git a/types/analytics-node/tslint.json b/types/analytics-node/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/analytics-node/tslint.json +++ b/types/analytics-node/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/angular-material/index.d.ts b/types/angular-material/index.d.ts index 9202829175..19c6dcc9e5 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -344,6 +344,7 @@ declare module 'angular' { } interface IMenuService { + close(): void; hide(response?: any, options?: any): IPromise; open(event?: MouseEvent): void; } diff --git a/types/angular-resource/angular-resource-tests.ts b/types/angular-resource/angular-resource-tests.ts index c35f27a98d..f7b8db579c 100644 --- a/types/angular-resource/angular-resource-tests.ts +++ b/types/angular-resource/angular-resource-tests.ts @@ -90,6 +90,7 @@ angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactorySe responseError() {} }; actionDescriptor.cancellable = true; + actionDescriptor.hasBody = true; }); /////////////////////////////////////// diff --git a/types/angular-resource/index.d.ts b/types/angular-resource/index.d.ts index 1ebd198b82..c298001533 100644 --- a/types/angular-resource/index.d.ts +++ b/types/angular-resource/index.d.ts @@ -88,6 +88,7 @@ declare module 'angular' { withCredentials?: boolean; responseType?: string; interceptor?: IResourceInterceptor; + hasBody?: boolean; } // Allow specify more resource methods diff --git a/types/array-move/array-move-tests.ts b/types/array-move/array-move-tests.ts new file mode 100644 index 0000000000..0bf720b751 --- /dev/null +++ b/types/array-move/array-move-tests.ts @@ -0,0 +1,8 @@ +import arrayMove = require('array-move'); + +const input = ['a', 'b', 'c']; +const input2 = [1, 2, 3]; + +arrayMove(input, 1, 2); // $ExpectType string[] +arrayMove(input2, 1, 2); // $ExpectType number[] +arrayMove.mut(input, 1, 2); // $ExpectType void diff --git a/types/array-move/index.d.ts b/types/array-move/index.d.ts new file mode 100644 index 0000000000..9b9aae938a --- /dev/null +++ b/types/array-move/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for array-move 1.0 +// Project: https://github.com/sindresorhus/array-move +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = arrayMove; + +/** + * Move an array item to a different position. + * + * @param from Index of item to move. If negative, it will begin that many elements from the end. + * @param to Index of where to move the item. If negative, it will begin that many elements from the end. + * @returns A new array with the item moved to the new position. + */ +declare function arrayMove(input: T, from: number, to: number): T; + +declare namespace arrayMove { + /** + * Moves the item to the new position in the input array. + * + * Useful for huge arrays where absolute performance is needed. + * + * @param from Index of item to move. If negative, it will begin that many elements from the end. + * @param to Index of where to move the item. If negative, it will begin that many elements from the end. + */ + function mut(input: any[], from: number, to: number): void; +} diff --git a/types/array-move/tsconfig.json b/types/array-move/tsconfig.json new file mode 100644 index 0000000000..6b4a5d5bb0 --- /dev/null +++ b/types/array-move/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", + "array-move-tests.ts" + ] +} diff --git a/types/array-move/tslint.json b/types/array-move/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/array-move/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/async/index.d.ts b/types/async/index.d.ts index e6cfd3bcaa..05d99e5968 100644 --- a/types/async/index.d.ts +++ b/types/async/index.d.ts @@ -1,13 +1,18 @@ -// Type definitions for Async 2.0.1 +// Type definitions for Async 2.4 // Project: https://github.com/caolan/async -// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman , Angus Fenying , Pascal Martin +// Definitions by: Boris Yankov +// Arseniy Maximov +// Joe Herman +// Angus Fenying +// Pascal Martin +// Dmitri Trofimov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 export as namespace async; export interface Dictionary { [key: string]: T; } -export type IterableCollection = T[] | IterableIterator | Dictionary +export type IterableCollection = T[] | IterableIterator | Dictionary; export interface ErrorCallback { (err?: E | null): void; } export interface AsyncBooleanResultCallback { (err?: E | null, truthValue?: boolean): void; } @@ -26,30 +31,40 @@ export interface AsyncBooleanIterator { (item: T, callback: AsyncB export interface AsyncWorker { (task: T, callback: ErrorCallback): void; } export interface AsyncVoidFunction { (callback: ErrorCallback): void; } -export type AsyncAutoTasks, E> = { [K in keyof R]: AsyncAutoTask } -export type AsyncAutoTask, E> = AsyncAutoTaskFunctionWithoutDependencies | (keyof R | AsyncAutoTaskFunction)[]; +export type AsyncAutoTasks, E> = { [K in keyof R]: AsyncAutoTask }; +export type AsyncAutoTask, E> = AsyncAutoTaskFunctionWithoutDependencies | Array>; export interface AsyncAutoTaskFunctionWithoutDependencies { (cb: AsyncResultCallback | ErrorCallback): void; } export interface AsyncAutoTaskFunction, E = Error> { (results: R, cb: AsyncResultCallback | ErrorCallback): void; } +export interface DataContainer { + data: T; +} + +export interface CallbackContainer { + callback: Function; +} + +export interface PriorityContainer { + priority: number; +} + export interface AsyncQueue { length(): number; started: boolean; running(): number; idle(): boolean; concurrency: number; - push(task: T | T[], callback?: AsyncResultCallback): void; + push(task: T | T[], callback?: AsyncResultCallback): void; unshift(task: T | T[], callback?: ErrorCallback): void; + remove(filter: (node: DataContainer) => boolean): void; saturated: () => any; empty: () => any; drain: () => any; paused: boolean; - pause(): void + pause(): void; resume(): void; kill(): void; - workersList(): { - data: T, - callback: Function - }[]; + workersList, CallbackContainer>(): TWorker[]; error(error: Error, data: any): void; unsaturated(): void; buffer: number; @@ -60,7 +75,7 @@ export interface AsyncPriorityQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T | T[], priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T | T[], priority: number, callback?: AsyncResultArrayCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -69,11 +84,7 @@ export interface AsyncPriorityQueue { pause(): void; resume(): void; kill(): void; - workersList(): { - data: T, - priority: number, - callback: Function - }[]; + workersList, CallbackContainer, PriorityContainer>(): TWorker[]; error(error: Error, data: any): void; unsaturated(): void; buffer: number; @@ -82,7 +93,7 @@ export interface AsyncPriorityQueue { export interface AsyncCargo { length(): number; payload?: number; - push(task: any, callback? : Function): void; + push(task: any, callback?: Function): void; saturated(): void; empty(): void; drain(): void; @@ -105,11 +116,17 @@ export function forEachOfLimit(obj: IterableCollection, limit: export const eachOf: typeof forEachOf; export const eachOfSeries: typeof forEachOf; export const eachOfLimit: typeof forEachOfLimit; -export function map(arr: T[] | IterableIterator, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function map(arr: T[] | IterableIterator | Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; export const mapSeries: typeof map; export function mapLimit(arr: IterableCollection, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; + +export function mapValuesLimit( + obj: Dictionary, + limit: number, + iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, + callback: AsyncResultObjectCallback + ): void; + export function mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; export const mapValuesSeries: typeof mapValues; export function filter(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; @@ -151,7 +168,7 @@ export function concatLimit(arr: IterableCollection, limit: export const concatSeries: typeof concat; // Control Flow -export function series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; +export function series(tasks: Array>, callback?: AsyncResultArrayCallback): void; export function series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; export function parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; export function parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; @@ -161,9 +178,9 @@ export function whilst(test: () => boolean, fn: AsyncVoidFunction, export function doWhilst(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; export function until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; export function doUntil(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; -export function during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; +export function during(test: (testCallback: AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; export function doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; -export function forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; +export function forever(next: (next: ErrorCallback) => void, errBack: ErrorCallback): void; export function waterfall(tasks: Function[], callback?: AsyncResultCallback): void; export function compose(...fns: Function[]): Function; export function seq(...fns: Function[]): Function; @@ -172,34 +189,52 @@ export function applyEachSeries(fns: Function[], ...argsAndCallback: any[]): voi export function queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; export function queue(worker: AsyncResultIterator, concurrency?: number): AsyncQueue; export function priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; -export function cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; +export function cargo(worker: (tasks: any[], callback: ErrorCallback) => void, payload?: number): AsyncCargo; export function auto, E = Error>(tasks: AsyncAutoTasks, concurrency?: number, callback?: AsyncResultCallback): void; export function auto, E = Error>(tasks: AsyncAutoTasks, callback?: AsyncResultCallback): void; export function autoInject(tasks: any, callback?: AsyncResultCallback): void; -export function retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; -export function retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; + +export function retry( + opts: number | { + times: number, + interval: number | ((retryCount: number) => number) + }, + task: (callback: AsyncResultCallback, results: any) => void, + callback: AsyncResultCallback + ): void; + export function retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; -export function apply(fn: Function, ...args: any[]): AsyncFunction; +export function apply(fn: Function, ...args: any[]): AsyncFunction; export function nextTick(callback: Function, ...args: any[]): void; export const setImmediate: typeof nextTick; -export function reflect(fn: AsyncFunction) : (callback: (err: null, result: {error?: E, value?: T}) => void) => void; -export function reflectAll(tasks: AsyncFunction[]): ((callback: (err: null, result: {error?: E, value?: T}) => void) => void)[]; +export function reflect(fn: AsyncFunction): (callback: (err: null, result: {error?: E, value?: T}) => void) => void; +export function reflectAll(tasks: Array>): Array<(callback: (err: null, result: {error?: E, value?: T}) => void) => void>; export function timeout(fn: AsyncFunction, milliseconds: number, info?: any): AsyncFunction; export function timeout(fn: AsyncResultIterator, milliseconds: number, info?: any): AsyncResultIterator; -export function times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; +export function times(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; export function timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; export function timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; export function transform(arr: T[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; export function transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; -export function transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; -export function transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; +export function transform( + arr: {[key: string]: T}, + iteratee: (acc: {[key: string]: R}, item: T, key: string, callback: (error?: E) => void) => void, + callback?: AsyncResultObjectCallback + ): void; -export function race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; +export function transform( + arr: {[key: string]: T}, + acc: {[key: string]: R}, + iteratee: (acc: {[key: string]: R}, item: T, key: string, callback: (error?: E) => void) => void, + callback?: AsyncResultObjectCallback + ): void; + +export function race(tasks: Array>, callback: AsyncResultCallback): void; // Utils export function memoize(fn: Function, hasher?: Function): Function; diff --git a/types/async/test/es6-generators.ts b/types/async/test/es6-generators.ts index b67e7daad7..e0008d7d5e 100644 --- a/types/async/test/es6-generators.ts +++ b/types/async/test/es6-generators.ts @@ -10,45 +10,45 @@ function eachOfIterator(item: T, key: K, callback: (err: Error) => void function concatIterator(item: T, callback: (err: E, res: R[]) => void) { } -async.map(collectionGenerator(), funcMapIterator, funcMapComplete) -async.mapSeries(collectionGenerator(), funcMapIterator, funcMapComplete) -async.mapLimit(collectionGenerator(), 2, funcMapIterator, funcMapComplete) +async.map(collectionGenerator(), funcMapIterator, funcMapComplete); +async.mapSeries(collectionGenerator(), funcMapIterator, funcMapComplete); +async.mapLimit(collectionGenerator(), 2, funcMapIterator, funcMapComplete); -async.filter(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.filterSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.filterLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { }) -async.select(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.selectSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.selectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { }) +async.filter(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.filterSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.filterLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { }); +async.select(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.selectSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.selectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { }); -async.reject(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.rejectSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.rejectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { }) +async.reject(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.rejectSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.rejectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { }); -async.each(collectionGenerator(), eachIterator, function (err: Error) { }) -async.eachLimit(collectionGenerator(), 2, eachIterator, function (err: Error) { }) -async.eachSeries(collectionGenerator(), eachIterator, function (err: Error) { }) -async.eachOf(collectionGenerator(), eachOfIterator, function (err: Error) { }) -async.eachOfLimit(collectionGenerator(), 2, eachOfIterator, function (err: Error) { }) -async.eachOfSeries(collectionGenerator(), eachOfIterator, function (err: Error) { }) -async.forEach(collectionGenerator(), eachIterator, function (err: Error) { }) -async.forEachLimit(collectionGenerator(), 2, eachIterator, function (err: Error) { }) -async.forEachSeries(collectionGenerator(), eachIterator, function (err: Error) { }) -async.forEachOf(collectionGenerator(), eachOfIterator, function (err: Error) { }) -async.forEachOfLimit(collectionGenerator(), 2, eachOfIterator, function (err: Error) { }) -async.forEachOfSeries(collectionGenerator(), eachOfIterator, function (err: Error) { }) +async.each(collectionGenerator(), eachIterator, (err: Error) => { }); +async.eachLimit(collectionGenerator(), 2, eachIterator, (err: Error) => { }); +async.eachSeries(collectionGenerator(), eachIterator, (err: Error) => { }); +async.eachOf(collectionGenerator(), eachOfIterator, (err: Error) => { }); +async.eachOfLimit(collectionGenerator(), 2, eachOfIterator, (err: Error) => { }); +async.eachOfSeries(collectionGenerator(), eachOfIterator, (err: Error) => { }); +async.forEach(collectionGenerator(), eachIterator, (err: Error) => { }); +async.forEachLimit(collectionGenerator(), 2, eachIterator, (err: Error) => { }); +async.forEachSeries(collectionGenerator(), eachIterator, (err: Error) => { }); +async.forEachOf(collectionGenerator(), eachOfIterator, (err: Error) => { }); +async.forEachOfLimit(collectionGenerator(), 2, eachOfIterator, (err: Error) => { }); +async.forEachOfSeries(collectionGenerator(), eachOfIterator, (err: Error) => { }); -async.every(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) -async.everyLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { }) -async.everySeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) +async.every(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); +async.everyLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { }); +async.everySeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); -async.some(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) -async.someLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { }) -async.someSeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) +async.some(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); +async.someLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { }); +async.someSeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); -async.detect(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) -async.detectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { }) -async.detectSeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) +async.detect(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); +async.detectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { }); +async.detectSeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); -async.concat(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }) -async.concatSeries(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }) +async.concat(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }); +async.concatSeries(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }); diff --git a/types/async/test/explicit.ts b/types/async/test/explicit.ts index 0c0e1a44ee..ae97888531 100644 --- a/types/async/test/explicit.ts +++ b/types/async/test/explicit.ts @@ -1,74 +1,58 @@ - - interface StringCallback { (err?: Error, result?: string): void; } interface AsyncStringGetter { (callback: StringCallback): void; } -var taskArray: AsyncStringGetter[] = [ - function (callback) { - setTimeout(function () { - callback(undefined, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(undefined, 'two'); - }, 100); - }, +const taskArray: AsyncStringGetter[] = [ + callback => { setTimeout(() => { callback(undefined, 'one'); }, 200); }, + callback => { setTimeout(() => { callback(undefined, 'two'); }, 100); } ]; -async.series(taskArray, function (err, results) { +async.series(taskArray, (err, results) => { if (results) { - let first = results[0]; + const first = results[0]; if (first) { - console.log(first.match(/o/)) - } - } -}); -async.parallel(taskArray, function (err, results) { - if (results) { - let first = results[0]; - if (first) { - console.log(first.match(/o/)) - } - } -}); -async.parallelLimit(taskArray, 3, function (err, results) { - if (results) { - let first = results[0]; - if (first) { - console.log(first.match(/o/)) + console.log(first.match(/o/)); } } }); +async.parallel(taskArray, (err, results) => { + if (results) { + const first = results[0]; + if (first) { + console.log(first.match(/o/)); + } + } +}); + +async.parallelLimit(taskArray, 3, (err, results) => { + if (results) { + const first = results[0]; + if (first) { + console.log(first.match(/o/)); + } + } +}); interface Lookup { [key: string]: T; } interface NumberCallback { (err?: Error, result?: number): void; } interface AsyncNumberGetter { (callback: NumberCallback): void; } -var taskDict: Lookup = { - one: function(callback) { - setTimeout(function() { - callback(undefined, 1); - }, 200); - }, - two: function(callback) { - setTimeout(function() { - callback(undefined, 2); - }, 100); - } -} +const taskDict: Lookup = { + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } +}; -async.series(taskDict, function(err, results) { - let one = results['one']; - console.log(one && one.toFixed(1)) -}); -async.parallel(taskDict, function(err, results) { - let one = results['one']; - console.log(one && one.toFixed(1)) -}); -async.parallelLimit(taskDict, 3, function(err, results) { - let one = results['one']; - console.log(one && one.toFixed(1)) +async.series(taskDict, (err, results) => { + const one = results['one']; + console.log(one && one.toFixed(1)); }); +async.parallel(taskDict, (err, results) => { + const one = results['one']; + console.log(one && one.toFixed(1)); +}); + +async.parallelLimit(taskDict, 3, (err, results) => { + const one = results['one']; + console.log(one && one.toFixed(1)); +}); diff --git a/types/async/test/index.ts b/types/async/test/index.ts index 574a5ed8b9..97e888870b 100644 --- a/types/async/test/index.ts +++ b/types/async/test/index.ts @@ -9,406 +9,272 @@ declare var path: { exists: (path: string, callback?: (err: Error, exists: boolean) => any) => void; }; -function funcStringCbErrBoolean(v:string, cb:(err:Error,res:boolean) => void) {} +function funcStringCbErrBoolean(v: string, cb: (err: Error, res: boolean) => void) {} function callback() { } -async.map(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); -async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); -async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err:Error, results:Array) { }); +async.map(['file1', 'file2', 'file3'], fs.stat, (err: Error, results: fs.Stats[]) => { }); +async.mapSeries(['file1', 'file2', 'file3'], fs.stat, (err: Error, results: fs.Stats[]) => { }); +async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, (err: Error, results: fs.Stats[]) => { }); -async.filter(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.filterSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.filterLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.select(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.selectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.selectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.filter(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.filterSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.filterLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.select(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.selectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.selectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, results: string[]) => { }); -async.reject(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.rejectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.rejectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.reject(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.rejectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.rejectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, results: string[]) => { }); async.parallel([ - function () { }, - function () { } + () => { }, + () => { } ], callback); async.series([ - function () { }, - function () { } + () => { }, + () => { } ]); -var data: any[] = []; +const data: any[] = []; function asyncProcess(item: any, callback: (err: Error, result: any) => void) { } -async.map(data, asyncProcess, function (err, results) { - console.log(results); -}); +async.map(data, asyncProcess, (err, results) => { console.log(results); }); -var openFiles = ['file1', 'file2']; -var openFilesObj = { +const openFiles = ['file1', 'file2']; +const openFilesObj = { file1: "fileOne", file2: "fileTwo" -} +}; -var saveFile = function (file:string,cb:(err:Error)=>void) { } -async.each(openFiles, saveFile, function (err:Error) { }); -async.eachSeries(openFiles, saveFile, function (err:Error) { }); +const saveFile = (file: string, cb: (err: Error) => void) => { }; +async.each(openFiles, saveFile, (err: Error) => { }); +async.eachSeries(openFiles, saveFile, (err: Error) => { }); -var documents: any, requestApi: any; -async.eachLimit(documents, 20, requestApi, function (err) { }); +const documents: any[] = []; +const requestApi: async.AsyncIterator = () => { }; +async.eachLimit(documents, 20, requestApi, err => { }); // forEachOf* functions. May accept array or object. function forEachOfIterator(item: string, key: string, forEachOfIteratorCallback: any) { - console.log("ForEach: item=" + item + ", key=" + key); + console.log(`ForEach: item=${item}, key=${key}`); forEachOfIteratorCallback(); } -async.forEachOf(openFiles, forEachOfIterator, function (err) { }); -async.forEachOf(openFilesObj, forEachOfIterator, function (err) { }); -async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { }); -async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); -async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); -async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); +async.forEachOf(openFiles, forEachOfIterator, err => { }); +async.forEachOf(openFilesObj, forEachOfIterator, err => { }); +async.forEachOfSeries(openFiles, forEachOfIterator, err => { }); +async.forEachOfSeries(openFilesObj, forEachOfIterator, err => { }); +async.forEachOfLimit(openFiles, 2, forEachOfIterator, err => { }); +async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, err => { }); -var numArray = [1, 2, 3]; +const numArray = [1, 2, 3]; function reducer(memo: any, item: any, callback: any) { - process.nextTick(function () { - callback(null, memo + item) - }); + process.nextTick(() => { callback(null, memo + item); }); } -async.reduce(numArray, 0, reducer, function (err, result) { }); -async.inject(numArray, 0, reducer, function (err, result) { }); -async.foldl(numArray, 0, reducer, function (err, result) { }); -async.reduceRight(numArray, 0, reducer, function (err, result) { }); -async.foldr(numArray, 0, reducer, function (err, result) { }); -async.detect(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err: Error,result:string) { }); -async.detectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err,result) { }); -async.detectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err,result) { }); +async.reduce(numArray, 0, reducer, (err, result) => { }); +async.inject(numArray, 0, reducer, (err, result) => { }); +async.foldl(numArray, 0, reducer, (err, result) => { }); +async.reduceRight(numArray, 0, reducer, (err, result) => { }); +async.foldr(numArray, 0, reducer, (err, result) => { }); -async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { - fs.stat(file, function (err, stats) { - callback(err, stats.mtime); - }); -}, function (err, results) { }); +async.detect(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: string) => { }); +async.detectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err, result) => { }); +async.detectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err, result) => { }); -async.some(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.someLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.any(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.sortBy(['file1', 'file2', 'file3'], (file, callback) => { + fs.stat(file, (err, stats) => { callback(err, stats.mtime); }); +}, (err, results) => { }); -async.every(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.everyLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.all(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.some(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.someLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.any(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); -async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); -async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); +async.every(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.everyLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.all(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, (err, files) => { }); +async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, (err, files) => { }); // Control Flow // -async.series([ - function (callback) { - callback(undefined, 'one'); - }, - function (callback) { - callback(undefined, 'two'); - }, -], -function (err, results) { }); - -async.series([ - function (callback) { - callback(undefined, 'one'); - }, - function (callback) { - callback(undefined, 'two'); - }, -], -function (err, results) { }); +async.series([callback => { callback(undefined, 'one'); }, callback => { callback(undefined, 'two'); }], (err, results) => { }); +async.series([callback => { callback(undefined, 'one'); }, callback => { callback(undefined, 'two'); }], (err, results) => { }); async.series({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, -function (err, results) { }); + (err, results) => { }); async.series({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, -function (err, results) { }); + (err, results) => { }); -async.times(5, function(n, next) { - next(undefined as any, n) -}, function(err, results) { - console.log(results) -}) +async.times(5, (n, next) => { next(undefined as any, n); }, (err, results) => { console.log(results); }); -async.timesSeries(5, function(n, next) { - next(undefined as any, n) -}, function(err, results) { - console.log(results) -}) +async.timesSeries(5, (n, next) => { next(undefined as any, n); }, (err, results) => { console.log(results); }); async.parallel([ - function (callback) { - setTimeout(function () { - callback(undefined, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(undefined, 'two'); - }, 100); - }, -], -function (err, results) { }); + callback => { setTimeout(() => { callback(undefined, 'one'); }, 200); }, + callback => { setTimeout(() => { callback(undefined, 'two'); }, 100); } + ], + (err, results) => { }); async.parallel([ - function (callback) { - setTimeout(function () { - callback(undefined, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(undefined, 'two'); - }, 100); - }, -], -function (err, results) { }); - + callback => { setTimeout(() => { callback(undefined, 'one'); }, 200); }, + callback => { setTimeout(() => { callback(undefined, 'two'); }, 100); } + ], + (err, results) => { }); async.parallel({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, -function (err, results) { }); + (err, results) => { }); async.parallel({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, - function (err, results) { }); + (err, results) => { }); async.parallelLimit({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, 2, - function (err, results) { } + (err, results) => { } ); - function whileFn(callback: any) { setTimeout(() => callback(null, ++count), 1000); } function whileTest() { return count < 5; } function doWhileTest(count: number) { return count < 5; } -var count = 0; -async.whilst(whileTest, whileFn, function (err) { }); -async.until(whileTest, whileFn, function (err) { }); -async.doWhilst(whileFn, doWhileTest, function (err) { }); -async.doUntil(whileFn, doWhileTest, function (err) { }); -async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) }); -async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) }); -async.forever(function (errBack) { - errBack(new Error("Not going on forever.")); -}, - function (error) { - console.log(error); - } -); +let count = 0; +async.whilst(whileTest, whileFn, err => { }); +async.until(whileTest, whileFn, err => { }); +async.doWhilst(whileFn, doWhileTest, err => { }); +async.doUntil(whileFn, doWhileTest, err => { }); + +async.during(testCallback => { testCallback(new Error(), false); }, callback => { callback(); }, error => { console.log(error); }); +async.doDuring(callback => { callback(); }, testCallback => { testCallback(new Error(), false); }, error => { console.log(error); }); +async.forever(errBack => { errBack(new Error("Not going on forever.")); }, error => { console.log(error); }); async.waterfall([ - function (callback: any) { - callback(null, 'one', 'two'); - }, - function (arg1: any, arg2: any, callback: any) { - callback(null, 'three'); - }, - function (arg1: any, callback: any) { - callback(null, 'done'); - } -], function (err, result) { }); + (callback: any) => { callback(null, 'one', 'two'); }, + (arg1: any, arg2: any, callback: any) => { callback(null, 'three'); }, + (arg1: any, callback: any) => { callback(null, 'done'); } + ], + (err, result) => { }); - -var q = async.queue(function (task: any, callback: (err?:Error,msg?:string) => void) { +const q = async.queue((task: any, callback: (err?: Error, msg?: string) => void) => { console.log('hello ' + task.name); - callback(undefined,'a message.'); + callback(undefined, 'a message.'); }, 2); - -q.drain = function () { - console.log('all items have been processed'); -} +q.drain = () => { console.log('all items have been processed'); }; q.push({ name: 'foo' }); - -q.push({ name: 'bar' }, function (err) { - console.log('finished processing bar'); -}); - -q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { - console.log('finished processing bar'); -}); - -q.push({name: 'foo'}, function (err, msg) { - console.log('foo finished with a message "'+ msg! + '"'); -}); +q.push({ name: 'bar' }, err => { console.log('finished processing bar'); }); +q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], err => { console.log('finished processing bar'); }); +q.push({name: 'foo'}, (err, msg) => { console.log(`foo finished with a message "${msg!}"`); }); q.unshift({ name: 'foo' }); +q.unshift({ name: 'bar' }, err => { console.log('finished processing bar'); }); +q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], err => { console.log('finished processing bar'); }); -q.unshift({ name: 'bar' }, function (err) { - console.log('finished processing bar'); -}); +const qLength: number = q.length(); +const qStarted: boolean = q.started; +const qPaused: boolean = q.paused; +const qProcessingCount: number = q.running(); +const qIsIdle: boolean = q.idle(); -q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { - console.log('finished processing bar'); -}); +q.saturated = () => { console.log('queue is saturated.'); }; -var qLength : number = q.length(); -var qStarted : boolean = q.started; -var qPaused : boolean = q.paused; -var qProcessingCount : number = q.running(); -var qIsIdle : boolean = q.idle(); +q.empty = () => { console.log('queue is empty.'); }; -q.saturated = function() { - console.log('queue is saturated.'); -} - -q.empty = function() { - console.log('queue is empty.'); -} - -q.drain = function() { - console.log('queue was drained.'); -} +q.drain = () => { console.log('queue was drained.'); }; q.pause(); q.resume(); q.kill(); // tests for strongly typed tasks -var q2 = async.queue(function (task: string, callback: () => void) { +const q2 = async.queue((task: string, callback: () => void) => { console.log('Task: ' + task); callback(); }, 1); q2.push('task1'); - -q2.push('task2', function (error) { - console.log('Finished tasks'); -}); - -q2.push(['task3', 'task4', 'task5'], function (error) { - console.log('Finished tasks'); -}); +q2.push('task2', error => { console.log('Finished tasks'); }); +q2.push(['task3', 'task4', 'task5'], error => { console.log('Finished tasks'); }); q2.unshift('task1'); +q2.unshift('task2', error => { console.log('Finished tasks'); }); +q2.unshift(['task3', 'task4', 'task5'], error => { console.log('Finished tasks'); }); -q2.unshift('task2', function (error) { - console.log('Finished tasks'); -}); +const q2Length = q2.length(); +q2.push('testRemovalTask'); +q2.remove(x => x.data === 'testTaskRemoval'); +if (q2Length !== q2.length()) { + throw new Error('Failed to remove a task from queue.'); +} -q2.unshift(['task3', 'task4', 'task5'], function (error) { - console.log('Finished tasks'); -}); - - -var aq = async.queue(function (level: number, callback: (error?: Error, newLevel?: number) => void) { +const aq = async.queue((level: number, callback: (error?: Error, newLevel?: number) => void) => { console.log('hello ' + level); - callback(undefined, level+1); + callback(undefined, level + 1); }); -aq.push(1, function (err : Error, newLevel : number) { +aq.push(1, (err: Error, newLevel: number) => { console.log('finished processing bar' + newLevel); }); // create a cargo object with payload 2 -var cargo = async.cargo(function (tasks, callback) { - for (var i = 0; i < tasks.length; i++) { - console.log('hello ' + tasks[i].name); +const cargo = async.cargo((tasks, callback) => { + for (const task of tasks) { + console.log('hello ' + task.name); } callback(); }, 2); - // add some items -cargo.push({ name: 'foo' }, function (err: Error) { - console.log('finished processing foo'); -}); -cargo.push({ name: 'bar' }, function (err: Error) { - console.log('finished processing bar'); -}); -cargo.push({ name: 'baz' }, function (err: Error) { - console.log('finished processing baz'); -}); +cargo.push({ name: 'foo' }, (err: Error) => { console.log('finished processing foo'); }); +cargo.push({ name: 'bar' }, (err: Error) => { console.log('finished processing bar'); }); +cargo.push({ name: 'baz' }, (err: Error) => { console.log('finished processing baz'); }); -var filename = ''; +const filename = ''; async.auto({ - get_data: function (callback: AsyncResultCallback) { }, - make_folder: function (callback: AsyncResultCallback) { }, - //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { + get_data: (callback: AsyncResultCallback) => { }, + make_folder: (callback: AsyncResultCallback) => { }, + + // arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', ((callback: AsyncResultCallback) => { callback(null, filename); - } as any], - //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] + }) as any], + + // arrays with different types are not accepted by TypeScript. + email_link: ['write_file', ((callback: AsyncResultCallback, results: any) => { }) as any] }); async.auto({ - get_data: function (callback: AsyncResultCallback) { }, - make_folder: function (callback: AsyncResultCallback) { }, - //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { - callback(null, filename); - } as any], - //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] -}, function (err, results) { - console.log('finished auto'); -}); + get_data: (callback: AsyncResultCallback) => { }, + make_folder: (callback: AsyncResultCallback) => { }, + + // arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', ((callback: AsyncResultCallback) => { callback(null, filename); }) as any], + + // arrays with different types are not accepted by TypeScript. + email_link: ['write_file', ((callback: AsyncResultCallback, results: any) => { }) as any] + }, + (err, results) => { console.log('finished auto'); } +); interface A { get_data: any; @@ -418,32 +284,28 @@ interface A { } async.auto({ - get_data: function (callback: AsyncResultCallback) { }, - make_folder: function (callback: AsyncResultCallback) { }, - //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { - callback(null, filename); - } as any], - //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] -}, 1, function (err, results) { - console.log('finished auto'); -}); + get_data: (callback: AsyncResultCallback) => { }, + make_folder: (callback: AsyncResultCallback) => { }, -async.retry(3, function (callback, results) { }, function (err, result) { }); -async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { }); -async.retry({ times: 3, interval: (retryCount) => { return 200 * retryCount; } }, function (callback, results) { }, function (err, result) { }); + // arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', ((callback: AsyncResultCallback) => { callback(null, filename); }) as any], + // arrays with different types are not accepted by TypeScript. + email_link: ['write_file', ((callback: AsyncResultCallback, results: any) => { }) as any] + }, + 1, + (err, results) => { console.log('finished auto'); } +); + +async.retry(3, (callback, results) => { }, (err, result) => { }); +async.retry({ times: 3, interval: 200 }, (callback, results) => { }, (err, result) => { }); +async.retry({ times: 3, interval: (retryCount) => 200 * retryCount }, (callback, results) => { }, (err, result) => { }); async.parallel([ - function (callback: ( err:Error, val:string ) => void ) { }, - function (callback) { } -], -function (err:Error,results:Array) { - async.series([ - function (callback) { }, - function email_link(callback) { } - ]); + (callback: (err: Error, val: string) => void) => { }, + callback => { } + ], + (err: Error, results: string[]) => { async.series([callback => { }, function email_link(callback) { }]); }); async.parallel([ @@ -451,428 +313,281 @@ async.parallel([ async.apply(fs.writeFile, 'testfile2', 'test2'), ]); - async.parallel([ - function (callback) { - fs.writeFile('testfile1', 'test1', callback); - }, - function (callback) { - fs.writeFile('testfile2', 'test2', callback); - }, + callback => { fs.writeFile('testfile1', 'test1', callback); }, + callback => { fs.writeFile('testfile2', 'test2', callback); } ]); -var call_order: string[] = []; -async.nextTick(function () { - call_order.push('two'); -}); +const call_order: string[] = []; +async.nextTick(() => { call_order.push('two'); }); call_order.push('one'); -var slow_fn = function (name: string, callback: any) { - callback(null, 123); -}; -var fn = async.memoize(slow_fn); -fn('some name', function () {}); +const slow_fn = (name: string, callback: any) => { callback(null, 123); }; +const fn = async.memoize(slow_fn); + +fn('some name', () => { }); async.unmemoize(fn); -async.ensureAsync(function () { }); +async.ensureAsync(() => { }); async.constant(42); -async.asyncify(function () { }); +async.asyncify(() => { }); -async.log(function (name: any, callback: any) { - setTimeout(function () { - callback(null, 'hello ' + name); - }, 0); -}, "world" - ); +async.log( + (name: any, callback: any) => { setTimeout(() => { callback(null, 'hello ' + name); }, 0); }, + "world"); -async.dir(function (name: string, callback: any) { - setTimeout(function () { - callback(null, { hello: name }); - }, 1000); -}, "world"); +async.dir((name: string, callback: any) => { setTimeout(() => { callback(null, { hello: name }); }, 1000); }, "world"); // each -async.each({ - "a": 1, - "b": 2 -}, function(val: number, next: ErrorCallback): void { +async.each( + { a: 1, b: 2 }, + (val: number, next: ErrorCallback) => { + setTimeout(() => { + console.log(`async.each: ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.each: done."); } +); - setTimeout(function(): void { +async.eachSeries( + { a: 1, b: 2 }, + (val: number, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.eachSeries: ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.eachSeries: done."); } +); - console.log(`async.each: ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.each: done."); - -}); - -async.eachSeries({ - "a": 1, - "b": 2 -}, function(val: number, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.eachSeries: ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.eachSeries: done."); - -}); - -async.eachLimit({ - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6 -}, 2, function(val: number, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.eachLimit: ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.eachLimit: done."); - -}); +async.eachLimit( + { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }, + 2, + (val: number, next: ErrorCallback) => { + setTimeout(() => { + console.log(`async.eachLimit: ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.eachLimit: done."); } +); // forEachOf/eachOf -async.eachOf({ - "a": 1, - "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { +async.eachOf( + { a: 1, b: 2 }, + (val: number, key: string, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.forEachOf/eachOf: ${key} = ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.forEachOf/eachOf: done."); } +); - setTimeout(function(): void { +async.forEachOfSeries( + { a: 1, b: 2 }, + (val: number, key: string, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.forEachOfSeries: ${key} = ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.forEachOfSeries: done."); } +); - console.log(`async.forEachOf/eachOf: ${key} = ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.forEachOf/eachOf: done."); - -}); - -async.forEachOfSeries({ - "a": 1, - "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.forEachOfSeries: ${key} = ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.forEachOfSeries: done."); - -}); - -async.forEachOfLimit({ - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6 -}, 2, function(val: number, key: string, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.forEachOfLimit: ${key} = ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.forEachOfLimit: done."); - -}); +async.forEachOfLimit( + { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }, + 2, + (val: number, key: string, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.forEachOfLimit: ${key} = ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.forEachOfLimit: done."); } +); // map -async.map({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncResultCallback): void { +async.map( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.map: ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: string[]) => { console.log("async.map: done with results", results); } +); - setTimeout(function(): void { +async.mapSeries( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapSeries: ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: string[]) => { console.log("async.mapSeries: done with results", results); } +); - console.log(`async.map: ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: string[]): void { - - console.log("async.map: done with results", results); - -}); - -async.mapSeries({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.mapSeries: ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: string[]): void { - - console.log("async.mapSeries: done with results", results); - -}); - -async.mapLimit({ - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6 -}, 2, function(val: number, next: AsyncResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.mapLimit: ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: string[]): void { - - console.log("async.mapLimit: done with results", results); - -}); +async.mapLimit( + { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }, + 2, + (val: number, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapLimit: ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: string[]) => { console.log("async.mapLimit: done with results", results); } +); // mapValues -async.mapValues({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { +async.mapValues( + { a: 1, b: 2, c: 3 }, + (val: number, key: string, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapValues: ${key} = ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: Dictionary) => { console.log("async.mapValues: done with results", results); } +); - setTimeout(function(): void { - - console.log(`async.mapValues: ${key} = ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: Dictionary): void { - - console.log("async.mapValues: done with results", results); - -}); - -async.mapValuesSeries({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.mapValuesSeries: ${key} = ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: Dictionary): void { - - console.log("async.mapValuesSeries: done with results", results); - -}); +async.mapValuesSeries( + { a: 1, b: 2, c: 3 }, + (val: number, key: string, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapValuesSeries: ${key} = ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: Dictionary) => { console.log("async.mapValuesSeries: done with results", results); } +); // filter/select/reject -async.filter({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { +async.filter( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncBooleanResultCallback) => { + setTimeout( + () => { + console.log(`async.filter/select: ${val}`); + next(undefined as any, val % 2 === 0); + }, + 500); + }, + (err: Error, results: number[]) => { console.log("async.filter/select: done with results", results); } +); - setTimeout(function(): void { - - console.log(`async.filter/select: ${val}`); - - next(undefined as any, val % 2 === 0); - - }, 500); - -}, function(err: Error, results: number[]): void { - - console.log("async.filter/select: done with results", results); - -}); - -async.reject({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.reject: ${val}`); - - next(undefined as any, val % 2 === 0); - - }, 500); - -}, function(err: Error, results: number[]): void { - - console.log("async.reject: done with results", results); - -}); +async.reject( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncBooleanResultCallback) => { + setTimeout( + () => { + console.log(`async.reject: ${val}`); + next(undefined as any, val % 2 === 0); + }, + 500); + }, + (err: Error, results: number[]) => { console.log("async.reject: done with results", results); } +); // concat -async.concat({ - "a": "1", - "b": "2", - "c": "3" -}, function(item: string, next: AsyncResultCallback): void { - - console.log(`async.concat: ${item}`); - - next(undefined as any, [item, item, item]); - -}, function(err: Error, results: string[]) { - - console.log("async.concat: done with results", results); - -}); +async.concat( + { a: "1", b: "2", c: "3" }, + (item: string, next: AsyncResultCallback) => { + console.log(`async.concat: ${item}`); + next(undefined as any, [item, item, item]); + }, + (err: Error, results: string[]) => { console.log("async.concat: done with results", results); } +); // detect/find -async.detect({ - "a": 1, - "b": 2, - "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { - - console.log(`async.detect/find: ${item}`); - - next(undefined as any, item > 1); - -}, function(err: Error, result: number) { - - if (err) { - - console.log(err); - - } else { - - console.log("async.detect/find: done with result", result); +async.detect( + { a: 1, b: 2, c: 3 }, + (item: number, next: AsyncBooleanResultCallback) => { + console.log(`async.detect/find: ${item}`); + next(undefined as any, item > 1); + }, + (err: Error, result: number) => { + if (err) { + console.log(err); + } else { + console.log("async.detect/find: done with result", result); + } } - -}); +); // every/all -async.every({ - "a": 1, - "b": 2, - "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { - - console.log(`async.every/all: ${item}`); - - next(undefined as any, item > 0); - -}, function(err: Error, result: boolean) { - - console.log("async.every/all: done with result", result); - -}); +async.every( + { a: 1, b: 2, c: 3 }, + (item: number, next: AsyncBooleanResultCallback) => { + console.log(`async.every/all: ${item}`); + next(undefined as any, item > 0); + }, + (err: Error, result: boolean) => { console.log("async.every/all: done with result", result); } +); // some/any -async.some({ - "a": 1, - "b": 2, - "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { - - console.log(`async.some/any: ${item}`); - - next(undefined as any, item > 2); - -}, function(err: Error, result: boolean) { - - console.log("async.some/any: done with result", result); - -}); +async.some( + { a: 1, b: 2, c: 3 }, + (item: number, next: AsyncBooleanResultCallback) => { + console.log(`async.some/any: ${item}`); + next(undefined as any, item > 2); + }, + (err: Error, result: boolean) => { console.log("async.some/any: done with result", result); } +); // timeout -function myFunction1(foo : any, callback: (err?: Error, result?: any) => void ) : void { +function myFunction1(foo: any, callback: (err?: Error, result?: any) => void): void { console.log(`async.timeout 1 ${foo}`); - return callback(undefined, foo); + callback(undefined, foo); } -var wrapped1 = async.timeout(myFunction1, 1000); -wrapped1({ bar: 'bar' }, function(err : Error, data : any) { - console.log(`async.timeout 1 end ${data}`); -}); +const wrapped1 = async.timeout(myFunction1, 1000); +wrapped1({ bar: 'bar' }, (err: Error, data: any) => { console.log(`async.timeout 1 end ${data}`); }); - -function myFunction2(callback: (err?: Error, result?: any) => void ) : void { +function myFunction2(callback: (err?: Error, result?: any) => void): void { console.log(`async.timeout 2`); - return callback(undefined, { bar: 'bar' }); + callback(undefined, { bar: 'bar' }); } -var wrapped2 = async.timeout(myFunction2, 1000); -wrapped2( function(err : Error, data : any) { - console.log(`async.timeout 2 end ${data}`); -}); +const wrapped2 = async.timeout(myFunction2, 1000); +wrapped2((err: Error, data: any) => { console.log(`async.timeout 2 end ${data}`); }); -function myFunction3(callback: (err?: Error, result?: any) => void ) : void { +function myFunction3(callback: (err?: Error, result?: any) => void): void { console.log(`async.timeout 3`); - return callback(undefined, { bar: 'bar' }); + callback(undefined, { bar: 'bar' }); } -var wrapped3 = async.timeout(myFunction3, 1000, { bar: 'bar' }); -wrapped3( function(err : Error, data : any) { - console.log(`async.timeout 3 end ${data}`); -}); - +const wrapped3 = async.timeout(myFunction3, 1000, { bar: 'bar' }); +wrapped3((err: Error, data: any) => { console.log(`async.timeout 3 end ${data}`); }); diff --git a/types/async/tslint.json b/types/async/tslint.json index 9380375afa..5612ed6657 100644 --- a/types/async/tslint.json +++ b/types/async/tslint.json @@ -1,34 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - // TODOs - "arrow-return-shorthand": false, - "array-type": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "max-line-length": false, - "no-consecutive-blank-lines": false, - "no-padding": false, - "no-unnecessary-generics": false, - "no-var-keyword": false, - "no-void-expression": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-const": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "trim-file": false, - "typedef-whitespace": false, - "unified-signatures": false, - "whitespace": false + "ban-types": true, // PRODUCES ERRORS WHEN REMOVED + "callable-types": false, // HAS ISSUES + "no-unnecessary-generics": false // HAS ISSUES } } diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 6e23e81d5e..53c50dd98f 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -130,7 +130,8 @@ const otherOptions : Auth0LockConstructorOptions = { hashCleanup: false, leeway: 30, _enableImpersonation: true, - _enableIdPInitiatedLogin: false + _enableIdPInitiatedLogin: false, + defaultADUsernameFromEmailPrefix: false }; new Auth0Lock(CLIENT_ID, DOMAIN, otherOptions); diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 2916ec58c8..32a3228e56 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -130,7 +130,7 @@ interface Auth0LockConstructorOptions { closable?: boolean; configurationBaseUrl?: string; container?: string; - defaultADUsernameFromEmailPrefix?: string; + defaultADUsernameFromEmailPrefix?: boolean; defaultDatabaseConnection?: string; defaultEnterpriseConnection?: string; flashMessage?: Auth0LockFlashMessageOptions; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index 60bbf86823..cca6bf8373 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -147,11 +147,21 @@ management management .updateUser({id: "user_id"}, {"email": "hi@me.co"}, (err: Error, users: auth0.User) => {}); - // Update user metadata management .updateUserMetadata({id: "user_id"}, {"key": "value"}); +// Update user metadata with JSON object +management + .updateUserMetadata({id: "user_id"}, { + key: "value", + numKey: 123, + objKey: { + foo: "bar", + another: "value" + } + }); + // Update user metadata using callback management .updateUserMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 39d9d36fd7..f91d2eb876 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for auth0 2.9.2 +// Type definitions for auth0 2.9.3 // Project: https://github.com/auth0/node-auth0 // Definitions by: Seth Westphal +// Ian Howe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -32,7 +33,7 @@ export interface RetryOptions { } export interface UserMetadata { - [propName: string]: string + [propName: string]: any } export interface AppMetadata { @@ -46,7 +47,9 @@ export interface UserData { verify_email?: boolean; password?: string; phone_number?: string; - phone_verified?: boolean, + phone_verified?: boolean; + given_name?: string; + family_name?: string; user_metadata?: UserMetadata; app_metadata?: AppMetadata; } diff --git a/types/backbone-relational/backbone-relational-tests.ts b/types/backbone-relational/backbone-relational-tests.ts index 90433cd153..6e0135fcd9 100644 --- a/types/backbone-relational/backbone-relational-tests.ts +++ b/types/backbone-relational/backbone-relational-tests.ts @@ -74,6 +74,7 @@ paul.get('livesIn'); // === ourHouse // You can control which relations get serialized to JSON, using the 'includeInJSON' // property on a Relation. Also, each object will only get serialized once to prevent loops. alert(JSON.stringify(paul.get('user').toJSON(), null, '\t')); +alert(JSON.stringify(paul.get('user').toJSON({ option1: 'value1' }), null, '\t')); // Load occupants 'person-2' and 'person-5', which don't exist yet, from the server ourHouse.fetchRelated('occupants'); diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index 403759ac97..84406fb60a 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -34,7 +34,7 @@ declare module 'backbone' { fetchRelated(key:string, options?:any, update?:boolean):any; - toJSON():any; + toJSON(options?: any):any; static setup(); diff --git a/types/badgen/badgen-tests.ts b/types/badgen/badgen-tests.ts new file mode 100644 index 0000000000..1b795b3d72 --- /dev/null +++ b/types/badgen/badgen-tests.ts @@ -0,0 +1,24 @@ +import badgen from 'badgen'; + +// $ExpectType string +badgen({ + subject: 'SUBJECT', + status: 'STATUS' +}); + +// $ExpectType string +badgen({ + subject: 'SUBJECT', + status: 'STATUS', + color: 'green' +}); + +// $ExpectType string +badgen({ + subject: 'SUBJECT', + status: 'STATUS', + color: '#FF0000', + style: 'flat', + icon: 'data:image/svg+xml;base64,...', + iconWidth: 20 +}); diff --git a/types/badgen/index.d.ts b/types/badgen/index.d.ts new file mode 100644 index 0000000000..cc6aa1fe54 --- /dev/null +++ b/types/badgen/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for badgen 2.6 +// Project: https://github.com/amio/badgen +// Definitions by: m5d215 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +type ColorPresets = + | 'green' + | 'blue' + | 'red' + | 'yellow' + | 'orange' + | 'purple' + | 'pink' + | 'grey' + | 'gray' + | 'cyan' + | 'black'; + +interface BadgeCreationParams { + /** + * Text representing the subject. + */ + subject: string; + + /** + * Text representing the status. + */ + status: string; + + /** + * Color RGB or Color Name, optional. + */ + color?: ColorPresets | string; + + /** + * 'flat' or undefined, optional. + */ + style?: 'flat'; + + /** + * Use icon, optional. + */ + icon?: string; + + /** + * Use this if icon is not square. + * @default 13 + */ + iconWidth?: number; +} + +declare function badgen(params: BadgeCreationParams): string; + +export = badgen; diff --git a/types/badgen/tsconfig.json b/types/badgen/tsconfig.json new file mode 100644 index 0000000000..8e915b8aac --- /dev/null +++ b/types/badgen/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, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "badgen-tests.ts" + ] +} diff --git a/types/badgen/tslint.json b/types/badgen/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/badgen/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/bandagedbd__bdapi/bandagedbd__bdapi-tests.ts b/types/bandagedbd__bdapi/bandagedbd__bdapi-tests.ts new file mode 100644 index 0000000000..3966aa3d1e --- /dev/null +++ b/types/bandagedbd__bdapi/bandagedbd__bdapi-tests.ts @@ -0,0 +1,6 @@ +import { BdApi } from 'bandagedbd__bdapi'; + +BdApi.React; // $ExpectType typeof React +BdApi.ReactDOM.render; // $ExpectType Renderer +BdApi.alert('foo', 'bar'); // $ExpectType void +BdApi.showToast('hello', { timeout: 2000 }); // $ExpectType void diff --git a/types/bandagedbd__bdapi/index.d.ts b/types/bandagedbd__bdapi/index.d.ts new file mode 100644 index 0000000000..4792992374 --- /dev/null +++ b/types/bandagedbd__bdapi/index.d.ts @@ -0,0 +1,176 @@ +// Type definitions for bdapi 0.2 +// Project: https://github.com/rauenzi/BetterDiscordApp +// Definitions by: Ari Seyhun +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 +// Documentation: https://github.com/rauenzi/BetterDiscordApp/wiki/Creating-Plugins#bdapi + +import * as ReactInstance from 'react'; +import * as ReactDOMInstance from 'react-dom'; + +export const BdApi: typeof BdApiModule; + +/** + * Function with no arguments and no return value that may be called to revert changes made by monkeyPatch method, + * restoring (unpatching) original method. + */ +export type CancelPatch = () => void; + +/** + * A callback that modifies method logic. + * This callback is called on each call of the original method and is provided all data about original call. + * Any of the data can be modified if necessary, but do so wisely. + */ +export type PatchFunction = (data: PatchData) => any; + +/** + * A callback that modifies method logic. + * This callback is called on each call of the original method and is provided all data about original call. + * Any of the data can be modified if necessary, but do so wisely. + */ +export interface PatchData { + thisObject: object; + methodArguments: any[]; + CancelPatch: CancelPatch; + originalMethod: () => void; + callOriginalMethod: () => void; + returnValue: any; +} + +export interface MonkeyPatchOptions { + once?: boolean; + silent?: boolean; + displayName?: string; + before?: PatchFunction; + after?: PatchFunction; + instead?: PatchFunction; +} + +export interface ToastOptions { + type?: string; + icon?: boolean; + timeout?: number; +} + +export namespace BdApiModule { + /** + * The React module being used inside Discord. + */ + const React: typeof ReactInstance; + + /** + * The ReactDOM module being used inside Discord. + */ + const ReactDOM: typeof ReactDOMInstance; + + /** + * Creates an shows an alert modal to the user. A preview of how it may look can be found [here](https://i.zackrauen.com/7qnnNC.png). + */ + function alert(title: string, content: string): void; + + /** + * Removes a style added with [`injectCSS`](#injectcssid-css) below. + */ + function clearCSS(id: string): void; + + /** + * Deletes some saved data for plugin `pluginName` with key `key`. + */ + function deleteData(pluginName: string, key: string): void; + + /** + * Searches for an internal Discord webpack module based on `filter`. + */ + function findModule(filter: () => void): any; + + /** + * Searches for multiple internal Discord webpack module based on `filter`. It's the same as [`findModule`](#findmodulefilter) but will return all matches + */ + function findAllModules(filter: () => void): any[]; + + /** + * Searches for an internal Discord webpack module that has every property passed. + */ + function findModuleByProps(...props: string[]): any; + + /** + * Returns BandagedBD's instance of the core module. Only use this if you know what you are doing. + */ + function getCore(): any; // TODO: This should not return 'any' but instead 'Core' + + /** + * Alias for [loadData(pluginName, key)](#loaddatapluginname-key) + */ + function getData(pluginName: string, key: string): any; + + /** + * Gets the internal react instance for a particular node. + */ + function getInternalInstance(node: HTMLElement): object|undefined; + + /** + * Gets the instance of another plugin with the name `name`. + */ + function getPlugin(name: string): object|null; + + /** + * Adds a block of css to the current document's `head`. + */ + function injectCSS(id: string, css: string): object|null; + + /** + * Links some remote JavaScript to be added to the page. Useful for libraries like `Sortable.js`. + */ + function linkJS(id: string, url: string): void; + + /** + * Gets some saved data for plugin `pluginName` with key `key`. Data can be saved with [`saveData`](#savedatapluginname-key-data). + */ + function loadData(pluginName: string, key: string): any; + + /** + * This function monkey-patches a method on an object. The patching callback may be run before, after or instead of target method. + * - Be careful when monkey-patching. Think not only about original functionality of target method and your changes, + * but also about developers of other plugins, who may also patch this method before or after you. + * Try to change target method behaviour as little as possible, and avoid changing method signatures. + * - Display name of patched method is changed, so you can see if a function has been patched (and how many times) while debugging or in the stack trace. + * Also, patched methods have property `__monkeyPatched` set to `true`, in case you want to check something programmatically. + */ + function monkeyPatch(module: object, methodName: string, options: MonkeyPatchOptions): CancelPatch; + + /** + * Adds a listener for when the node is removed from the document body. + */ + function onRemoved(node: HTMLElement, callback: () => void): void; + + /** + * Saved some `data` for plugin `pluginName` under `key` key. Gets saved in the plugins folder under `pluginName.config.json`. Data can be saved with [`loadData`](#loaddatapluginname-key). + */ + function saveData(pluginName: string, key: string, data: any): void; + + /** + * Alias for [saveData(pluginName, key, data)](#savedatapluginname-key-data) + * + */ + function setData(pluginName: string, key: string, data: any): void; + + /** + * Shows a simple toast message similar to on Android. An example of the `success` toast can be seen [here](https://i.zackrauen.com/zIagVa.png). + */ + function showToast(content: string, options?: ToastOptions): void; + + /** + * Wraps a function in a try catch block. + */ + function suppressErrors(method: () => void, message?: string): () => void; + + /** + * Determines if the input is valid and parseable JSON. + */ + function testJSON(data: string): boolean; + + /** + * Removes some previously linked JS by [`linkJS`](#linkjsid-url). + */ + function unlinkJS(id: string): void; +} diff --git a/types/nuka-carousel/tsconfig.json b/types/bandagedbd__bdapi/tsconfig.json similarity index 93% rename from types/nuka-carousel/tsconfig.json rename to types/bandagedbd__bdapi/tsconfig.json index 240c9965c5..7e35378a67 100644 --- a/types/nuka-carousel/tsconfig.json +++ b/types/bandagedbd__bdapi/tsconfig.json @@ -20,6 +20,6 @@ }, "files": [ "index.d.ts", - "nuka-carousel-tests.tsx" + "bandagedbd__bdapi-tests.ts" ] } diff --git a/types/bandagedbd__bdapi/tslint.json b/types/bandagedbd__bdapi/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bandagedbd__bdapi/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/beeper/beeper-tests.ts b/types/beeper/beeper-tests.ts new file mode 100644 index 0000000000..b3f6f8d60b --- /dev/null +++ b/types/beeper/beeper-tests.ts @@ -0,0 +1,7 @@ +import beeper = require('beeper'); + +beeper(); +beeper(3); +beeper(3, () => {}); +beeper('****-*-*'); +beeper('****-*-*', () => {}); diff --git a/types/beeper/index.d.ts b/types/beeper/index.d.ts new file mode 100644 index 0000000000..3e17e4be1c --- /dev/null +++ b/types/beeper/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for beeper 1.1 +// Project: https://github.com/sindresorhus/beeper#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = beeper; + +declare function beeper(count?: number, cb?: () => void): void; +declare function beeper(melody: string, cb?: () => void): void; diff --git a/types/beeper/tsconfig.json b/types/beeper/tsconfig.json new file mode 100644 index 0000000000..54614ad773 --- /dev/null +++ b/types/beeper/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", + "beeper-tests.ts" + ] +} diff --git a/types/beeper/tslint.json b/types/beeper/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/beeper/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bell/bell-tests.ts b/types/bell/bell-tests.ts index 26a29670a0..8a091f005c 100644 --- a/types/bell/bell-tests.ts +++ b/types/bell/bell-tests.ts @@ -16,7 +16,7 @@ async function run() { clientSecret: '', scope(request) { const scopes = ['public_profile', 'email']; - if ((request.query as RequestQuery).wantsSharePermission) { + if (request.query.wantsSharePermission) { scopes.push('publish_actions'); } return scopes; diff --git a/types/bip32/index.d.ts b/types/bip32/index.d.ts index 99a1b8dffd..c536f741af 100644 --- a/types/bip32/index.d.ts +++ b/types/bip32/index.d.ts @@ -17,6 +17,7 @@ export class BIP32 { identifier: Buffer; fingerprint: Buffer; + chainCode: Buffer; privateKey: Buffer; publicKey: Buffer; diff --git a/types/bn.js/bn.js-tests.ts b/types/bn.js/bn.js-tests.ts index a5d37dfdeb..738d5220d4 100644 --- a/types/bn.js/bn.js-tests.ts +++ b/types/bn.js/bn.js-tests.ts @@ -8,3 +8,11 @@ bn.byteLength; bn.toArrayLike(Buffer, 'le', 2); const test = new BN(1, 'le'); + +const ctx = BN.red('p224'); +ctx.prime.name; + +const red = bn.toRed(ctx); +const newRed = red.redAdd(new BN(1)); +newRed.cmp(bn); +newRed.fromRed(); diff --git a/types/bn.js/index.d.ts b/types/bn.js/index.d.ts index db4c9f8b9e..be04dbcc5f 100644 --- a/types/bn.js/index.d.ts +++ b/types/bn.js/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/indutny/bn.js // Definitions by: Leonid Logvinov // Henry Nguyen +// Gaylor Bosson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,36 +10,16 @@ type Endianness = 'le' | 'be'; type IPrimeName = 'k256' | 'p224' | 'p192' | 'p25519'; -declare class RedBN { - redAdd(b: RedBN): RedBN; - redIAdd(b: RedBN): RedBN; - redSub(b: RedBN): RedBN; - redISub(b: RedBN): RedBN; - redShl(num: number): RedBN; - redMul(b: RedBN): RedBN; - redIMul(b: RedBN): RedBN; - redSqr(): RedBN; - redISqr(): RedBN; - /** - * @description square root modulo reduction context's prime - */ - redSqrt(): RedBN; - /** - * @description modular inverse of the number - */ - redInvm(): RedBN; - redNeg(): RedBN; - /** - * @description modular exponentiation - */ - redPow(b: RedBN): RedBN; - fromRed(): BN; +interface MPrime { + name: string; + p: BN; + n: number; + k: BN; } -// FIXME: not sure how to specify the reduction context here interface ReductionContext { m: number; - prime: any; + prime: MPrime; [key: string]: any; } @@ -78,11 +59,6 @@ declare class BN { */ static min(left: BN, right: BN): BN; - /** - * @description Convert number to red - */ - toRed(reductionContext: ReductionContext): RedBN; - /** * @description clone number */ @@ -522,6 +498,87 @@ declare class BN { * @description inverse `a` modulo `b` */ invm(b: BN): BN; + + /** + * @description Convert number to red + */ + toRed(reductionContext: ReductionContext): RedBN; +} + +/** + * Big-Number class with additionnal methods that are using modular + * operation. + */ +declare class RedBN extends BN { + /** + * @description Convert back a number using a reduction context + */ + fromRed(): BN; + + /** + * @description modular addition + */ + redAdd(b: BN): RedBN; + + /** + * @description in-place modular addition + */ + redIAdd(b: BN): RedBN; + + /** + * @description modular subtraction + */ + redSub(b: BN): RedBN; + + /** + * @description in-place modular subtraction + */ + redISub(b: BN): RedBN; + + /** + * @description modular shift left + */ + redShl(num: number): RedBN; + + /** + * @description modular multiplication + */ + redMul(b: BN): RedBN; + + /** + * @description in-place modular multiplication + */ + redIMul(b: BN): RedBN; + + /** + * @description modular square + */ + redSqr(): RedBN; + + /** + * @description in-place modular square + */ + redISqr(): RedBN; + + /** + * @description modular square root + */ + redSqrt(): RedBN; + + /** + * @description modular inverse of the number + */ + redInvm(): RedBN; + + /** + * @description modular negation + */ + redNeg(): RedBN; + + /** + * @description modular exponentiation + */ + redPow(b: BN): RedBN; } export = BN; diff --git a/types/browserslist-useragent/browserslist-useragent-tests.ts b/types/browserslist-useragent/browserslist-useragent-tests.ts new file mode 100644 index 0000000000..83103178e5 --- /dev/null +++ b/types/browserslist-useragent/browserslist-useragent-tests.ts @@ -0,0 +1,30 @@ +import { + matchesUA, + resolveUserAgent, + normalizeQuery +} from 'browserslist-useragent'; + +// $ExpectType boolean +matchesUA( + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' +); + +// $ExpectType boolean +matchesUA( + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', + { + browsers: ['defaults'], + env: 'production', + ignorePath: true, + ignoreMinor: false, + allowHigherVersions: false + } +); + +// $ExpectType ResolvedUserAgent +resolveUserAgent( + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' +); + +// $ExpectType string +normalizeQuery('defaults'); diff --git a/types/browserslist-useragent/index.d.ts b/types/browserslist-useragent/index.d.ts new file mode 100644 index 0000000000..4c7e548a4a --- /dev/null +++ b/types/browserslist-useragent/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for browserslist-useragent 3.0 +// Project: https://github.com/browserslist/browserslist-useragent (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: nju33 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ResolvedUserAgent { + family: string; + version: string; +} + +export interface BrowserslistUseragentOptions { + browsers?: string[]; + env?: string; + ignorePath?: boolean; + ignoreMinor?: boolean; + allowHigherVersions?: boolean; +} + +export function matchesUA( + uaString: string, + opts?: BrowserslistUseragentOptions +): boolean; +export function resolveUserAgent(uaString: string): ResolvedUserAgent; +export function normalizeQuery(query: string): string; diff --git a/types/browserslist-useragent/tsconfig.json b/types/browserslist-useragent/tsconfig.json new file mode 100644 index 0000000000..849531b901 --- /dev/null +++ b/types/browserslist-useragent/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": ["index.d.ts", "browserslist-useragent-tests.ts"] +} diff --git a/types/browserslist-useragent/tslint.json b/types/browserslist-useragent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/browserslist-useragent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 2419afee8f..b2fb68d4d7 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -36,6 +36,8 @@ declare namespace Bull { max: number; /** Per duration in milliseconds */ duration: number; + /** When jobs get rate limited, they stay in the waiting queue and are not moved to the delayed queue */ + bounceBack?: boolean; } interface QueueOptions { @@ -68,6 +70,11 @@ declare namespace Bull { */ lockDuration?: number; + /** + * Interval in milliseconds on which to acquire the job lock. + */ + lockRenewTime?: number; + /** * How often check for stalled jobs (use 0 for never checking) */ @@ -129,6 +136,25 @@ declare namespace Bull { */ finishedOn?: number; + /** + * Which queue this job was part of + */ + queue: Queue; + + timestamp: number; + + /** + * The named processor name + */ + name: string; + + /** + * The stacktrace for any errors + */ + stacktrace: string[]; + + returnvalue: any; + /** * Report progress on a job */ @@ -340,6 +366,11 @@ declare namespace Bull { } interface Queue { + /** + * The name of the queue + */ + name: string; + /** * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. * This replaces the `ready` event emitted on Queue in previous verisons. diff --git a/types/cadesplugin/index.d.ts b/types/cadesplugin/index.d.ts new file mode 100644 index 0000000000..6b93a9514d --- /dev/null +++ b/types/cadesplugin/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for cadesplugin 2.1 +// Project: https://www.npmjs.com/package/cadesplugin +// Definitions by: Delagen , +// kvmi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +declare const cadesplugin: any; diff --git a/types/cadesplugin/package.json b/types/cadesplugin/package.json new file mode 100644 index 0000000000..bb80441dc0 --- /dev/null +++ b/types/cadesplugin/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} diff --git a/types/cadesplugin/ts3.1/cadescom.d.ts b/types/cadesplugin/ts3.1/cadescom.d.ts new file mode 100644 index 0000000000..a721b54d97 --- /dev/null +++ b/types/cadesplugin/ts3.1/cadescom.d.ts @@ -0,0 +1,97 @@ +declare namespace CAdESCOM { + interface CPSigner { + Certificate: CAPICOM.Certificate; + CheckCertificate: boolean; + + KeyPin: string; + Options: CADES_Common.ValuesOf; + readonly SignatureTimeStampTime: CADES_Common.VarDate; + readonly SigningTime: CADES_Common.VarDate; + TSAAddress: string; + + Display(hwndParent?: number, title?: string): void; + + Load(fileName: string, password?: string): void; + } + + interface CadesSignedData { + readonly Certificates: CAPICOM.Certificates; + Content: string; + ContentEncoding: CADES_Common.ValuesOf; + + DisplayData: CADES_Common.ValuesOf; + + Display(hwndParent?: number, title?: string): void; + + EnhanceCades(cadesType?: CADES_Common.ValuesOf, TSAAddress?: string, encodingType?: CADES_Common.ValuesOf): string; + + SignCades(signer?: CPSigner, CadesType?: CADES_Common.ValuesOf, bDetached?: boolean, EncodingType?: CADES_Common.ValuesOf): string; + + VerifyCades(SignedMessage: string, CadesType?: CADES_Common.ValuesOf, bDetached?: boolean): void; + } + + interface Version { + readonly BuildVersion: number; + readonly MajorVersion: number; + readonly MinorVersion: number; + readonly toStringDefault: string; + + toString(): string; + } + + interface About { + readonly BuildVersion: number; + readonly MajorVersion: number; + readonly MinorVersion: number; + readonly PluginVersion: Version; + readonly Version: string; + + CSPName(ProviderType?: number): string; + + CSPVersion(ProviderName?: string, ProviderType?: number): Version; + + ProviderVersion(ProviderName?: string, ProviderType?: number): string; + + toString(): string; + } + + interface CPSigners { + readonly Count: number; + + Item(index: number): CPSigner; + } + + interface SignedXML { + Content: string; + DigestMethod: string; + SignatureMethod: string; + SignatureType: CADES_Common.ValuesOf; + readonly Signers: CAPICOM.Signers; + + Sign(signer?: CPSigner, XPath?: string): string; + + Verify(SignedMessage: string, XPath?: string): void; + } + + interface CPHashedData { + Algorithm: CADES_Common.ValuesOf; + DataEncoding: CADES_Common.ValuesOf; + Value: string; + + Hash(newVal: string): void; + + SetHashValue(newVal: string): void; + } + + interface CPAttribute { + Name: CADES_Common.ValuesOf; + Value: any; + ValueEncoding: CADES_Common.ValuesOf; + } + + interface RawSignature { + SignHash(hash: CPHashedData, certificate?: string): string; + + VerifyHash(hash: CPHashedData, certificate: CAPICOM.Certificate, signature: string): void; + } +} diff --git a/types/cadesplugin/ts3.1/cadescom_async.d.ts b/types/cadesplugin/ts3.1/cadescom_async.d.ts new file mode 100644 index 0000000000..94e95b2acc --- /dev/null +++ b/types/cadesplugin/ts3.1/cadescom_async.d.ts @@ -0,0 +1,57 @@ +declare namespace CAdESCOM { + interface CPSignerAsync extends CADES_Common.Async { + propset_Certificate(certificate: CAPICOM.CertificateAsync): Promise; + + propset_CheckCertificate(checkCertificate: boolean): Promise; + + propset_KeyPin(keyPin: string): Promise; + + propset_Options(options: CADES_Common.ValuesOf): Promise; + + propset_TSAAddress(TSAAddress: string): Promise; + } + + interface CadesSignedDataAsync extends CADES_Common.Async { + propset_DisplayData(displayData: CADES_Common.ValuesOf): Promise; + + propset_Content(content: string): Promise; + + propset_ContentEncoding(contentEncoding: CADES_Common.ValuesOf): Promise; + } + + interface VersionAsync extends CADES_Common.Async { + } + + interface AboutAsync extends CADES_Common.Async { + } + + interface CPSignersAsync extends CADES_Common.Async { + } + + interface SignedXMLAsync extends CADES_Common.Async { + propset_Content(content: string): Promise; + + propset_DigestMethod(digestMethod: string): Promise; + + propset_SignatureMethod(signatureMethod: string): Promise; + + propset_SignatureType(signatureType: CADES_Common.ValuesOf): Promise; + } + + interface CPHashedDataAsync extends CADES_Common.Async { + propset_Algorithm(algorithm: CADES_Common.ValuesOf): Promise; + + propset_DataEncoding(dataEncoding: CADES_Common.ValuesOf): Promise; + } + + interface CPAttributeAsync extends CADES_Common.Async { + propset_Name(name: CADES_Common.ValuesOf): Promise; + + propset_Value(value: any): Promise; + + propset_ValueEncoding(valueEncoding: CADES_Common.ValuesOf): Promise; + } + + interface RawSignatureAsync extends CADES_Common.Async { + } +} diff --git a/types/cadesplugin/ts3.1/cadescom_enums.d.ts b/types/cadesplugin/ts3.1/cadescom_enums.d.ts new file mode 100644 index 0000000000..918803a47d --- /dev/null +++ b/types/cadesplugin/ts3.1/cadescom_enums.d.ts @@ -0,0 +1,74 @@ +declare namespace CAdESCOM { + interface StoreLocationPlugin { + readonly CADESCOM_LOCAL_MACHINE_STORE: 1; + readonly CADESCOM_CURRENT_USER_STORE: 2; + readonly CADESCOM_CONTAINER_STORE: 100; + } + + interface CADESCOM_STORE_LOCATION extends StoreLocationPlugin { + readonly CADESCOM_MEMORY_STORE: 0; + readonly CADESCOM_ACTIVE_DIRECTORY_USER_STORE: 3; + readonly CADESCOM_SMART_CARD_USER_STORE: 4; + } + + interface CADESCOM_CADES_TYPE { + readonly CADESCOM_CADES_BES: 1; + readonly CADESCOM_CADES_DEFAULT: 0; + readonly CADESCOM_CADES_T: 5; + readonly CADESCOM_CADES_X_LONG_TYPE_1: 93; + } + + interface CADESCOM_CONTENT_ENCODING_TYPE { + readonly CADESCOM_BASE64_TO_BINARY: 1; + readonly CADESCOM_STRING_TO_UCS2LE: 0; + } + + interface CADESCOM_XML_SIGNATURE_TYPE { + readonly CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED: 0; + readonly CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING: 1; + readonly CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE: 2; + } + + interface CADESCOM_ENCRYPTION_ALGORITHM { + readonly CADESCOM_ENCRYPTION_ALGORITHM_RC2: 0; + readonly CADESCOM_ENCRYPTION_ALGORITHM_RC4: 1; + readonly CADESCOM_ENCRYPTION_ALGORITHM_DES: 2; + readonly CADESCOM_ENCRYPTION_ALGORITHM_3DES: 3; + readonly CADESCOM_ENCRYPTION_ALGORITHM_AES: 4; + readonly CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89: 25; + } + + interface CADESCOM_HASH_ALGORITHM { + readonly CADESCOM_HASH_ALGORITHM_SHA1: 0; + readonly CADESCOM_HASH_ALGORITHM_MD2: 1; + readonly CADESCOM_HASH_ALGORITHM_MD4: 2; + readonly CADESCOM_HASH_ALGORITHM_MD5: 3; + readonly CADESCOM_HASH_ALGORITHM_SHA_256: 4; + readonly CADESCOM_HASH_ALGORITHM_SHA_384: 5; + readonly CADESCOM_HASH_ALGORITHM_SHA_512: 6; + readonly CADESCOM_HASH_ALGORITHM_CP_GOST_3411: 100; + readonly CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256: 101; + readonly CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512: 102; + } + + interface CADESCOM_ATTRIBUTE { + readonly CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME: 0; + readonly CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME: 1; + readonly CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION: 2; + readonly CADESCOM_ATTRIBUTE_OTHER: -1; + } + + interface CADESCOM_DISPLAY_DATA { + readonly CADESCOM_DISPLAY_DATA_NONE: 0; + readonly CADESCOM_DISPLAY_DATA_CONTENT: 1; + readonly CADESCOM_DISPLAY_DATA_ATTRIBUTE: 2; + } + + interface CADESCOM_InstallResponseRestrictionFlags { + readonly CADESCOM_AllowNone: 0; + readonly CADESCOM_AllowNoOutstandingRequest: 1; + readonly CADESCOM_AllowUntrustedCertificate: 2; + readonly CADESCOM_AllowUntrustedRoot: 4; + readonly CADESCOM_SkipInstallToStore: 0x10000000; + } +} diff --git a/types/cadesplugin/ts3.1/cadesplugin-tests.ts b/types/cadesplugin/ts3.1/cadesplugin-tests.ts new file mode 100644 index 0000000000..c9784f1671 --- /dev/null +++ b/types/cadesplugin/ts3.1/cadesplugin-tests.ts @@ -0,0 +1,12 @@ +cadesplugin.then(async () => { + if ("CreateObjectAsync" in cadesplugin) { + const pluginAsync: CADESPluginAsync = cadesplugin; + const oAbout = await pluginAsync.CreateObjectAsync("CAdESCOM.About"); + const oVersion = await oAbout.CSPVersion(); + await oVersion.toString(); + } + if ("CreateObject" in cadesplugin) { + const pluginSync: CADESPluginSync = cadesplugin; + pluginSync.CreateObject("CAdESCOM.About").CSPVersion().toString(); + } +}); diff --git a/types/cadesplugin/ts3.1/cadesplugin.d.ts b/types/cadesplugin/ts3.1/cadesplugin.d.ts new file mode 100644 index 0000000000..53bba7e1bd --- /dev/null +++ b/types/cadesplugin/ts3.1/cadesplugin.d.ts @@ -0,0 +1,80 @@ +declare namespace CADES_Plugin { + interface ObjectNames { + "CAPICOM.Store": CAPICOM.Store; + "CAdESCOM.CPSigner": CAdESCOM.CPSigner; + "CAdESCOM.About": CAdESCOM.About; + "CAdESCOM.SignedXML": CAdESCOM.SignedXML; + "CAdESCOM.HashedData": CAdESCOM.CPHashedData; + "CAdESCOM.CadesSignedData": CAdESCOM.CadesSignedData; + "CAdESCOM.CPAttribute": CAdESCOM.CPAttribute; + "CAdESCOM.RawSignature": CAdESCOM.RawSignature; + } + + interface ObjectNamesAsync { + "CAdESCOM.Store": CAPICOM.StoreAsync; + "CAdESCOM.CPSigner": CAdESCOM.CPSignerAsync; + "CAdESCOM.About": CAdESCOM.AboutAsync; + "CAdESCOM.SignedXML": CAdESCOM.SignedXMLAsync; + "CAdESCOM.HashedData": CAdESCOM.CPHashedDataAsync; + "CAdESCOM.CadesSignedData": CAdESCOM.CadesSignedDataAsync; + "CAdESCOM.CPAttribute": CAdESCOM.CPAttributeAsync; + "CAdESCOM.RawSignature": CAdESCOM.RawSignatureAsync; + } + + interface LogLevel { + readonly LOG_LEVEL_DEBUG: 4; + readonly LOG_LEVEL_INFO: 2; + readonly LOG_LEVEL_ERROR: 1; + } + + interface SignedXmlUrls { + readonly XmlDsigGost3410Url: "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"; + readonly XmlDsigGost3410UrlObsolete: "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411"; + readonly XmlDsigGost3411Url: "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"; + readonly XmlDsigGost3411UrlObsolete: "http://www.w3.org/2001/04/xmldsig-more#gostr3411"; + } + + interface EncodingType { + readonly CADESCOM_ENCODE_ANY: -1; + readonly CADESCOM_ENCODE_BASE64: 0; + readonly CADESCOM_ENCODE_BINARY: 1; + } +} + +interface CADESPluginBase extends Promise, + CAPICOM.StoreLocationPlugin, CAdESCOM.StoreLocationPlugin, CAPICOM.StoreNamePlugin, + CAPICOM.StoreOpenModePlugin, CAPICOM.CAPICOM_CERTIFICATE_FIND_TYPE, + CADES_Plugin.LogLevel, CAdESCOM.CADESCOM_XML_SIGNATURE_TYPE, + CADES_Plugin.SignedXmlUrls, CAdESCOM.CADESCOM_CADES_TYPE, + CADES_Plugin.EncodingType, CAPICOM.CAPICOM_CERTIFICATE_INCLUDE_OPTION, + CAPICOM.CertIntoTypePlugin, CAPICOM.KeyUsagePlugin, + CAPICOM.PropIDPlugin, CAPICOM.OIDPlugin, CAPICOM.EKUPlugin, + CAPICOM.CAPICOM_ATTRIBUTE, CAdESCOM.CADESCOM_ATTRIBUTE, + CAdESCOM.CADESCOM_CONTENT_ENCODING_TYPE, CAdESCOM.CADESCOM_DISPLAY_DATA, + CAdESCOM.CADESCOM_ENCRYPTION_ALGORITHM, CAdESCOM.CADESCOM_HASH_ALGORITHM, + CAdESCOM.CADESCOM_InstallResponseRestrictionFlags { + readonly JSModuleVersion: string; + readonly current_log_level: number; + + async_spawn(generatorFun: (...args: any[]) => Iterator): T; + + set(obj: CADESPluginBase): void; + + set_log_level(level: CADES_Common.ValuesOf): void; + + getLastError(exception: Error): string; + + is_capilite_enabled(): boolean; +} + +interface CADESPluginAsync extends CADESPluginBase { + CreateObjectAsync(objName: T): Promise; + + ReleasePluginObjects(): Promise; +} + +interface CADESPluginSync extends CADESPluginBase { + CreateObject(objName: T): CADES_Plugin.ObjectNames[T]; +} + +type CADESPlugin = CADESPluginAsync | CADESPluginSync; diff --git a/types/cadesplugin/ts3.1/capicom.d.ts b/types/cadesplugin/ts3.1/capicom.d.ts new file mode 100644 index 0000000000..02bb6f05b5 --- /dev/null +++ b/types/cadesplugin/ts3.1/capicom.d.ts @@ -0,0 +1,83 @@ +declare namespace CAPICOM { + interface EncodedData { + readonly Format: string; + + Value(EncodingType?: CAPICOM_ENCODING_TYPE): string; + } + + interface OID { + FriendlyName: string; + Name: CAPICOM_OID; + Value: string; + } + + interface PublicKey { + readonly Algorithm: OID; + readonly EncodedKey: EncodedData; + readonly EncodedParameters: EncodedData; + readonly Length: number; + } + + interface Certificate { + readonly Version: number; + readonly Thumbprint: string; + readonly SubjectName: string; + readonly SerialNumber: string; + readonly IssuerName: string; + readonly ValidFromDate: CADES_Common.VarDate; + readonly ValidToDate: CADES_Common.VarDate; + + HasPrivateKey(): boolean; + + GetInfo(infoType: CAPICOM_CERT_INFO_TYPE): string; + + IsValid(): CertificateStatus; + + Display(): void; + + PublicKey(): PublicKey; + + Export(EncodingType: CADES_Common.ValuesOf): string; + } + + interface CertificateStatus { + Result: boolean; + } + + interface Certificates { + readonly Count: number; + + Item(index: number): Certificate; + + Find(findType: CADES_Common.ValuesOf, varCriteria?: any, bFindValidOnly?: boolean): Certificates; + + Select(title?: string, displayString?: string, bMultiSelect?: boolean): Certificates; + } + + interface Store { + readonly Certificates: Certificates; + readonly Location: CADES_Common.ValuesOf; + readonly Name: string; + + Open(location?: CADES_Common.ValuesOf, name?: CADES_Common.ValuesOf, openMode?: CADES_Common.ValuesOf): void; + + Close(): void; + + Delete(): boolean; + + Import(encodedStore: string): void; + } + + interface Signers { + readonly Count: number; + + Item(index: number): Signer; + } + + interface Signer { + Certificate: Certificate; + Options: CAPICOM_CERTIFICATE_INCLUDE_OPTION; + + Load(fileName: string, password?: string): void; + } +} diff --git a/types/cadesplugin/ts3.1/capicom_async.d.ts b/types/cadesplugin/ts3.1/capicom_async.d.ts new file mode 100644 index 0000000000..5ab775aba2 --- /dev/null +++ b/types/cadesplugin/ts3.1/capicom_async.d.ts @@ -0,0 +1,19 @@ +declare namespace CAPICOM { + interface CertificateAsync extends CADES_Common.Async { + } + + interface CertificatesAsync extends CADES_Common.Async { + } + + interface StoreAsync extends CADES_Common.Async { + } + + interface EncodedDataAsync extends CADES_Common.Async { + } + + interface OIDAsync extends CADES_Common.Async { + } + + interface PublicKeyAsync extends CADES_Common.Async { + } +} diff --git a/types/cadesplugin/ts3.1/capicom_enums.d.ts b/types/cadesplugin/ts3.1/capicom_enums.d.ts new file mode 100644 index 0000000000..aada08bfe2 --- /dev/null +++ b/types/cadesplugin/ts3.1/capicom_enums.d.ts @@ -0,0 +1,226 @@ +declare namespace CAPICOM { + interface StoreLocationPlugin { + readonly CAPICOM_LOCAL_MACHINE_STORE: 1; + readonly CAPICOM_CURRENT_USER_STORE: 2; + } + + interface CAPICOM_STORE_LOCATION { + readonly CAPICOM_MEMORY_STORE: 0; + readonly CAPICOM_LOCAL_MACHINE_STORE: 1; + readonly CAPICOM_CURRENT_USER_STORE: 2; + readonly CAPICOM_ACTIVE_DIRECTORY_USER_STORE: 3; + readonly CAPICOM_SMART_CARD_USER_STORE: 4; + } + + interface StoreNamePlugin { + readonly CAPICOM_MY_STORE: "My"; + } + + interface CAPICOM_STORE_NAME extends StoreNamePlugin { + readonly CAPICOM_CA_STORE: "Ca"; + readonly CAPICOM_OTHER_STORE: "AddressBook"; + readonly CAPICOM_ROOT_STORE: "Root"; + } + + interface StoreOpenModePlugin { + readonly CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED: 2; + } + + interface CAPICOM_STORE_OPEN_MODE extends StoreOpenModePlugin { + readonly CAPICOM_STORE_OPEN_READ_ONLY: 0; + readonly CAPICOM_STORE_OPEN_READ_WRITE: 1; + readonly CAPICOM_STORE_OPEN_EXISTING_ONLY: 128; + readonly CAPICOM_STORE_OPEN_INCLUDE_ARCHIVED: 256; + } + + interface CAPICOM_CERTIFICATE_FIND_TYPE { + readonly CAPICOM_CERTIFICATE_FIND_SHA1_HASH: 0; + readonly CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME: 1; + readonly CAPICOM_CERTIFICATE_FIND_ISSUER_NAME: 2; + readonly CAPICOM_CERTIFICATE_FIND_ROOT_NAME: 3; + readonly CAPICOM_CERTIFICATE_FIND_TEMPLATE_NAME: 4; + readonly CAPICOM_CERTIFICATE_FIND_EXTENSION: 5; + readonly CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY: 6; + readonly CAPICOM_CERTIFICATE_FIND_APPLICATION_POLICY: 7; + readonly CAPICOM_CERTIFICATE_FIND_CERTIFICATE_POLICY: 8; + readonly CAPICOM_CERTIFICATE_FIND_TIME_VALID: 9; + readonly CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID: 10; + readonly CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED: 11; + readonly CAPICOM_CERTIFICATE_FIND_KEY_USAGE: 12; + } + + interface CAPICOM_CERTIFICATE_INCLUDE_OPTION { + readonly CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT: 0; + readonly CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY: 2; + readonly CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN: 1; + } + + interface CertIntoTypePlugin { + readonly CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME: 0; + readonly CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME: 1; + } + + interface CAPICOM_CERT_INFO_TYPE extends CertIntoTypePlugin { + readonly CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME: 2; + readonly CAPICOM_CERT_INFO_ISSUER_EMAIL_NAME: 3; + readonly CAPICOM_CERT_INFO_SUBJECT_UPN: 4; + readonly CAPICOM_CERT_INFO_ISSUER_UPN: 5; + readonly CAPICOM_CERT_INFO_SUBJECT_DNS_NAME: 6; + readonly CAPICOM_CERT_INFO_ISSUER_DNS_NAME: 7; + } + + interface KeyUsagePlugin { + readonly CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE: 128; + } + + interface CAPICOM_KEY_USAGE extends KeyUsagePlugin { + readonly CAPICOM_NON_REPUDIATION_KEY_USAGE: 64; + readonly CAPICOM_KEY_ENCIPHERMENT_KEY_USAGE: 32; + readonly CAPICOM_DATA_ENCIPHERMENT_KEY_USAGE: 16; + readonly CAPICOM_KEY_AGREEMENT_KEY_USAGE: 8; + readonly CAPICOM_KEY_CERT_SIGN_KEY_USAGE: 4; + readonly CAPICOM_OFFLINE_CRL_SIGN_KEY_USAGE: 2; + readonly CAPICOM_CRL_SIGN_KEY_USAGE: 2; + readonly CAPICOM_ENCIPHER_ONLY_KEY_USAGE: 1; + readonly CAPICOM_DECIPHER_ONLY_KEY_USAGE: 32768; + } + + interface PropIDPlugin { + readonly CAPICOM_PROPID_ENHKEY_USAGE: 9; + } + + interface CAPICOM_PROPID extends PropIDPlugin { + readonly CAPICOM_PROPID_UNKNOWN: 0; + readonly CAPICOM_PROPID_KEY_PROV_HANDLE: 1; + readonly CAPICOM_PROPID_KEY_PROV_INFO: 2; + readonly CAPICOM_PROPID_SHA1_HASH: 3; + readonly CAPICOM_PROPID_HASH_PROP: 3; + readonly CAPICOM_PROPID_MD5_HASH: 4; + readonly CAPICOM_PROPID_KEY_CONTEXT: 5; + readonly CAPICOM_PROPID_KEY_SPEC: 6; + readonly CAPICOM_PROPID_IE30_RESERVED: 7; + readonly CAPICOM_PROPID_PUBKEY_HASH_RESERVED: 8; + readonly CAPICOM_PROPID_CTL_USAGE: 9; + readonly CAPICOM_PROPID_NEXT_UPDATE_LOCATION: 10; + readonly CAPICOM_PROPID_FRIENDLY_NAME: 11; + readonly CAPICOM_PROPID_PVK_FILE: 12; + readonly CAPICOM_PROPID_DESCRIPTION: 13; + readonly CAPICOM_PROPID_ACCESS_STATE: 14; + readonly CAPICOM_PROPID_SIGNATURE_HASH: 15; + readonly CAPICOM_PROPID_SMART_CARD_DATA: 16; + readonly CAPICOM_PROPID_EFS: 17; + readonly CAPICOM_PROPID_FORTEZZA_DATA: 18; + readonly CAPICOM_PROPID_ARCHIVED: 19; + readonly CAPICOM_PROPID_KEY_IDENTIFIER: 20; + readonly CAPICOM_PROPID_AUTO_ENROLL: 21; + readonly CAPICOM_PROPID_PUBKEY_ALG_PARA: 22; + readonly CAPICOM_PROPID_CROSS_CERT_DIST_POINTS: 23; + readonly CAPICOM_PROPID_ISSUER_PUBLIC_KEY_MD5_HASH: 24; + readonly CAPICOM_PROPID_SUBJECT_PUBLIC_KEY_MD5_HASH: 25; + readonly CAPICOM_PROPID_ENROLLMENT: 26; + readonly CAPICOM_PROPID_DATE_STAMP: 27; + readonly CAPICOM_PROPID_ISSUER_SERIAL_NUMBER_MD5_HASH: 28; + readonly CAPICOM_PROPID_SUBJECT_NAME_MD5_HASH: 29; + readonly CAPICOM_PROPID_EXTENDED_ERROR_INFO: 30; + readonly CAPICOM_PROPID_RENEWAL: 64; + readonly CAPICOM_PROPID_ARCHIVED_KEY_HASH: 65; + readonly CAPICOM_PROPID_FIRST_RESERVED: 66; + readonly CAPICOM_PROPID_LAST_RESERVED: 32767; + readonly CAPICOM_PROPID_FIRST_USER: 32768; + readonly CAPICOM_PROPID_LAST_USER: 65535; + } + + interface OIDPlugin { + readonly CAPICOM_OID_OTHER: 0; + readonly CAPICOM_OID_KEY_USAGE_EXTENSION: 10; + } + + interface CAPICOM_OID extends OIDPlugin { + readonly CAPICOM_OID_AUTHORITY_KEY_IDENTIFIER_EXTENSION: 1; + readonly CAPICOM_OID_KEY_ATTRIBUTES_EXTENSION: 2; + readonly CAPICOM_OID_CERT_POLICIES_95_EXTENSION: 3; + readonly CAPICOM_OID_KEY_USAGE_RESTRICTION_EXTENSION: 4; + readonly CAPICOM_OID_LEGACY_POLICY_MAPPINGS_EXTENSION: 5; + readonly CAPICOM_OID_SUBJECT_ALT_NAME_EXTENSION: 6; + readonly CAPICOM_OID_ISSUER_ALT_NAME_EXTENSION: 7; + readonly CAPICOM_OID_BASIC_CONSTRAINTS_EXTENSION: 8; + readonly CAPICOM_OID_SUBJECT_KEY_IDENTIFIER_EXTENSION: 9; + readonly CAPICOM_OID_PRIVATEKEY_USAGE_PERIOD_EXTENSION: 11; + readonly CAPICOM_OID_SUBJECT_ALT_NAME2_EXTENSION: 12; + readonly CAPICOM_OID_ISSUER_ALT_NAME2_EXTENSION: 13; + readonly CAPICOM_OID_BASIC_CONSTRAINTS2_EXTENSION: 14; + readonly CAPICOM_OID_NAME_CONSTRAINTS_EXTENSION: 15; + readonly CAPICOM_OID_CRL_DIST_POINTS_EXTENSION: 16; + readonly CAPICOM_OID_CERT_POLICIES_EXTENSION: 17; + readonly CAPICOM_OID_POLICY_MAPPINGS_EXTENSION: 18; + readonly CAPICOM_OID_AUTHORITY_KEY_IDENTIFIER2_EXTENSION: 19; + readonly CAPICOM_OID_POLICY_CONSTRAINTS_EXTENSION: 20; + readonly CAPICOM_OID_ENHANCED_KEY_USAGE_EXTENSION: 21; + readonly CAPICOM_OID_CERTIFICATE_TEMPLATE_EXTENSION: 22; + readonly CAPICOM_OID_APPLICATION_CERT_POLICIES_EXTENSION: 23; + readonly CAPICOM_OID_APPLICATION_POLICY_MAPPINGS_EXTENSION: 24; + readonly CAPICOM_OID_APPLICATION_POLICY_CONSTRAINTS_EXTENSION: 25; + readonly CAPICOM_OID_AUTHORITY_INFO_ACCESS_EXTENSION: 26; + readonly CAPICOM_OID_SERVER_AUTH_EKU: 100; + readonly CAPICOM_OID_CLIENT_AUTH_EKU: 101; + readonly CAPICOM_OID_CODE_SIGNING_EKU: 102; + readonly CAPICOM_OID_EMAIL_PROTECTION_EKU: 103; + readonly CAPICOM_OID_IPSEC_END_SYSTEM_EKU: 104; + readonly CAPICOM_OID_IPSEC_TUNNEL_EKU: 105; + readonly CAPICOM_OID_IPSEC_USER_EKU: 106; + readonly CAPICOM_OID_TIME_STAMPING_EKU: 107; + readonly CAPICOM_OID_CTL_USAGE_SIGNING_EKU: 108; + readonly CAPICOM_OID_TIME_STAMP_SIGNING_EKU: 109; + readonly CAPICOM_OID_SERVER_GATED_CRYPTO_EKU: 110; + readonly CAPICOM_OID_ENCRYPTING_FILE_SYSTEM_EKU: 111; + readonly CAPICOM_OID_EFS_RECOVERY_EKU: 112; + readonly CAPICOM_OID_WHQL_CRYPTO_EKU: 113; + readonly CAPICOM_OID_NT5_CRYPTO_EKU: 114; + readonly CAPICOM_OID_OEM_WHQL_CRYPTO_EKU: 115; + readonly CAPICOM_OID_EMBEDED_NT_CRYPTO_EKU: 116; + readonly CAPICOM_OID_ROOT_LIST_SIGNER_EKU: 117; + readonly CAPICOM_OID_QUALIFIED_SUBORDINATION_EKU: 118; + readonly CAPICOM_OID_KEY_RECOVERY_EKU: 119; + readonly CAPICOM_OID_DIGITAL_RIGHTS_EKU: 120; + readonly CAPICOM_OID_LICENSES_EKU: 121; + readonly CAPICOM_OID_LICENSE_SERVER_EKU: 122; + readonly CAPICOM_OID_SMART_CARD_LOGON_EKU: 123; + readonly CAPICOM_OID_PKIX_POLICY_QUALIFIER_CPS: 124; + readonly CAPICOM_OID_PKIX_POLICY_QUALIFIER_USERNOTICE: 125; + } + + interface EKUPlugin { + readonly CAPICOM_EKU_OTHER: 0; + readonly CAPICOM_EKU_CLIENT_AUTH: 2; + readonly CAPICOM_EKU_SMARTCARD_LOGON: 5; + } + + interface CAPICOM_EKU { + readonly CAPICOM_EKU_SERVER_AUTH: 1; + readonly CAPICOM_EKU_CODE_SIGNING: 3; + readonly CAPICOM_EKU_EMAIL_PROTECTION: 4; + readonly CAPICOM_EKU_ENCRYPTING_FILE_SYSTEM: 6; + } + + interface CAPICOM_ATTRIBUTE { + readonly CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME: 0; + readonly CAPICOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME: 1; + readonly CAPICOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION: 2; + } + + interface CAPICOM_HASH_ALGORITHM { + readonly CAPICOM_HASH_ALGORITHM_SHA1: 0; + readonly CAPICOM_HASH_ALGORITHM_MD2: 1; + readonly CAPICOM_HASH_ALGORITHM_MD4: 2; + readonly CAPICOM_HASH_ALGORITHM_MD5: 3; + readonly CAPICOM_HASH_ALGORITHM_SHA_256: 4; + readonly CAPICOM_HASH_ALGORITHM_SHA_384: 5; + readonly CAPICOM_HASH_ALGORITHM_SHA_512: 6; + } + + interface CAPICOM_ENCODING_TYPE { + readonly CAPICOM_ENCODE_ANY: -1; + readonly CAPICOM_ENCODE_BASE64: 0; + readonly CAPICOM_ENCODE_BINARY: 1; + } +} diff --git a/types/cadesplugin/ts3.1/common.d.ts b/types/cadesplugin/ts3.1/common.d.ts new file mode 100644 index 0000000000..315b0490a3 --- /dev/null +++ b/types/cadesplugin/ts3.1/common.d.ts @@ -0,0 +1,25 @@ +declare namespace CADES_Common { + type ValuesOf = T[keyof T]; + type VarDate = object; + + // Extracts the type if wrapped by a Promise + type Unpacked = T extends Promise ? U : + T extends CAPICOM.Certificate ? CAPICOM.CertificateAsync : + T extends CAPICOM.Certificates ? CAPICOM.CertificatesAsync : + T extends CAdESCOM.CPSigner ? CAdESCOM.CPSignerAsync : + T extends CAdESCOM.CPHashedData ? CAdESCOM.CPHashedDataAsync : + T extends CAdESCOM.Version ? CAdESCOM.VersionAsync : + T extends CAPICOM.OID ? CAPICOM.OIDAsync : + T extends CAPICOM.EncodedData ? CAPICOM.EncodedDataAsync : + T extends CAPICOM.PublicKey ? CAPICOM.PublicKeyAsync : + T; + + type PromisifiedFunction = // tslint:disable-line ban-types + T extends (...args: infer A) => infer U ? (...args: { [K in keyof A]: Unpacked }) => Promise> : + T; + + type Async = { + readonly [K in keyof T]: T[K] extends Function ? PromisifiedFunction : // tslint:disable-line ban-types + Promise>; + }; +} diff --git a/types/cadesplugin/ts3.1/index.d.ts b/types/cadesplugin/ts3.1/index.d.ts new file mode 100644 index 0000000000..13fdba4187 --- /dev/null +++ b/types/cadesplugin/ts3.1/index.d.ts @@ -0,0 +1,13 @@ +/// + +/// +/// +/// + +/// +/// +/// + +/// + +declare const cadesplugin: CADESPlugin; diff --git a/types/cadesplugin/ts3.1/tsconfig.json b/types/cadesplugin/ts3.1/tsconfig.json new file mode 100644 index 0000000000..dbc37d117b --- /dev/null +++ b/types/cadesplugin/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "extends": "../tsconfig", + "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", + "cadesplugin-tests.ts" + ] +} diff --git a/types/cadesplugin/ts3.1/tslint.json b/types/cadesplugin/ts3.1/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cadesplugin/ts3.1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/cadesplugin/tsconfig.json b/types/cadesplugin/tsconfig.json new file mode 100644 index 0000000000..71e6b79545 --- /dev/null +++ b/types/cadesplugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "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" + ] +} diff --git a/types/cadesplugin/tslint.json b/types/cadesplugin/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cadesplugin/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 62b99ac5b3..32fbdf6f3f 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -249,7 +249,7 @@ export interface GenerateFuncFlags { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export type GenerateFunc = (id: string, flags: GenerateFuncFlags) => Promise; +export type GenerateFunc = (id: Id, flags: GenerateFuncFlags) => Promise; /** * An object with logging information about the generation operation containing the following keys (as relevant): diff --git a/types/chromecast-caf-receiver/cast.framework.messages.d.ts b/types/chromecast-caf-receiver/cast.framework.messages.d.ts index c3dc4a405f..1846fd4840 100644 --- a/types/chromecast-caf-receiver/cast.framework.messages.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.messages.d.ts @@ -1372,12 +1372,12 @@ export interface MediaInformation { * is playing or ones that receiver will play shortly after; instead of sending * whole list of clips. This is to avoid overflow of MediaStatus message. */ - breakClips: BreakClip[]; + breakClips?: BreakClip[]; /** * List of breaks. */ - breaks: Break[]; + breaks?: Break[]; /** * Typically the url of the media. @@ -1414,12 +1414,18 @@ export interface MediaInformation { /** * The format of the HLS media segment. */ - hlsSegmentFormat: HlsSegmentFormat; + hlsSegmentFormat?: HlsSegmentFormat; /** * The media metadata. */ - metadata: MediaMetadata; + metadata?: + | MediaMetadata + | GenericMediaMetadata + | MovieMediaMetadata + | MusicTrackMediaMetadata + | PhotoMediaMetadata + | TvShowMediaMetadata; /** * The stream type. @@ -1429,12 +1435,12 @@ export interface MediaInformation { /** * The style of text track. */ - textTrackStyle: TextTrackStyle; + textTrackStyle?: TextTrackStyle; /** * The media tracks. */ - tracks: Track[]; + tracks?: Track[]; } /** diff --git a/types/cli-spinners/cli-spinners-tests.ts b/types/cli-spinners/cli-spinners-tests.ts new file mode 100644 index 0000000000..45acb25db7 --- /dev/null +++ b/types/cli-spinners/cli-spinners-tests.ts @@ -0,0 +1,3 @@ +import cliSpinners = require('cli-spinners'); + +cliSpinners.dots; // $ExpectType Spinner diff --git a/types/cli-spinners/index.d.ts b/types/cli-spinners/index.d.ts new file mode 100644 index 0000000000..db04ab5cc1 --- /dev/null +++ b/types/cli-spinners/index.d.ts @@ -0,0 +1,87 @@ +// Type definitions for cli-spinners 1.3 +// Project: https://github.com/sindresorhus/cli-spinners#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = cliSpinners; + +declare const cliSpinners: Record; + +declare namespace cliSpinners { + type SpinnerName = + | 'dots' + | 'dots2' + | 'dots3' + | 'dots4' + | 'dots5' + | 'dots6' + | 'dots7' + | 'dots8' + | 'dots9' + | 'dots10' + | 'dots11' + | 'dots12' + | 'line' + | 'line2' + | 'pipe' + | 'simpleDots' + | 'simpleDotsScrolling' + | 'star' + | 'star2' + | 'flip' + | 'hamburger' + | 'growVertical' + | 'growHorizontal' + | 'balloon' + | 'balloon2' + | 'noise' + | 'bounce' + | 'boxBounce' + | 'boxBounce2' + | 'triangle' + | 'arc' + | 'circle' + | 'squareCorners' + | 'circleQuarters' + | 'circleHalves' + | 'squish' + | 'toggle' + | 'toggle2' + | 'toggle3' + | 'toggle4' + | 'toggle5' + | 'toggle6' + | 'toggle7' + | 'toggle8' + | 'toggle9' + | 'toggle10' + | 'toggle11' + | 'toggle12' + | 'toggle13' + | 'arrow' + | 'arrow2' + | 'arrow3' + | 'bouncingBar' + | 'bouncingBall' + | 'smiley' + | 'monkey' + | 'hearts' + | 'clock' + | 'earth' + | 'moon' + | 'runner' + | 'pong' + | 'shark' + | 'dqpb' + | 'weather' + | 'christmas' + | 'grenade' + | 'point' + | 'layer'; + + interface Spinner { + interval: number; + frames: string[]; + } +} diff --git a/types/cli-spinners/tsconfig.json b/types/cli-spinners/tsconfig.json new file mode 100644 index 0000000000..8b4a54bd83 --- /dev/null +++ b/types/cli-spinners/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", + "cli-spinners-tests.ts" + ] +} diff --git a/types/cli-spinners/tslint.json b/types/cli-spinners/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cli-spinners/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cookiejar/index.d.ts b/types/cookiejar/index.d.ts index ba50b63ea2..b976a0e1dc 100644 --- a/types/cookiejar/index.d.ts +++ b/types/cookiejar/index.d.ts @@ -112,5 +112,5 @@ export class CookieJar { * grab all cookies matching this access_info * @param accessInfo CookieAccessInfo */ - getCookies(accessInfo: CookieAccessInfo): ReadonlyArray; + getCookies(accessInfo: CookieAccessInfo): ReadonlyArray & { toValueString(): string }; } diff --git a/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts b/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts index 6e4317ac9d..f7830c18b2 100644 --- a/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts +++ b/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts @@ -61,59 +61,89 @@ var demoExtendedData : BLECentralPlugin.PeripheralDataExtended = { //get updates about the bluethooth states ble.startStateNotifications((state) => log(`BLE state ${state}`)); +ble.startStateNotifications((state) => log(`BLE state ${state}`), (err: string) => log(`things when wrong ${err}`)); -ble.isEnabled(()=> log(`bluetooth is enabled`), ()=>log(`bluetooth is not enabled`)); +ble.isEnabled(()=> log(`bluetooth is enabled`), err =>log(`bluetooth is not enabled: ${err}`)); //here we try to enable bluetooth -ble.enable(() => log(`yes it worked, or it was already enabled `), () => log(`nope it didn't work, the user pressed cancel, or we are in iOS`)); +ble.enable(() => log(`yes it worked, or it was already enabled `), err => log(`nope it didn't work, the user pressed cancel, or we are in iOS: ${err}`)); ble.showBluetoothSettings(() => log(`yes it worked`), () => log(`nope it didn't work`)) //stop getting updates about the bluethooth states ble.stopStateNotifications() +ble.stopStateNotifications(() => log(`yes it worked`)) +ble.stopStateNotifications(() => log(`yes it worked`), () => log(`nope it didn't work`)) //scan 5 seconds -ble.scan([], 5000, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ); +ble.scan([], 5000, (data) => { devices.push(data); }); +ble.scan([], 5000, (data) => { devices.push(data); }, () => log(`couldn't connect`) ); +ble.scan([], 5000, (data) => { devices.push(data); }, err => log(`couldn't connect: ${err}`) ); //scan continously -ble.startScan([], (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) +ble.startScan([], (data) => { devices.push(data); }) +ble.startScan([], (data) => { devices.push(data); }, () => log('couldn\'t connect') ) +ble.startScan([], (data) => { devices.push(data); }, err => log(`couldn't connect: ${err}`) ); ////scan continously -ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) +ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }); +ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }, err => log(`couldn't connect: ${err}`)); //stop scanning ble.stopScan(()=> log('all good'), ()=> log('couldn\'t stop scanning')); //are we conenected to that device? +ble.isConnected(demoDevice.id, () => log(`already connected to this device`)); ble.isConnected(demoDevice.id, () => log(`already connected to this device`), ()=> log(`not yet connected to that device`)); //connect to a specific device var extendedData : BLECentralPlugin.PeripheralDataExtended; -ble.connect(demoDevice.id, (data)=> extendedData = data, () => log(`couldn't connect to the device`) ); +ble.connect(demoDevice.id, (data)=> extendedData = data, err => log(`couldn't connect to the device: ${err}`) ); //read some data from a characteristic var charsOfOneOfItsServices = demoExtendedData.characteristics.filter((value) => value.service == demoExtendedData.services[0]); +ble.read(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic); ble.read(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data) => log(`we've received some data`), ()=> log(`couldn't read any data`)); //read the rssi ble.readRSSI(demoDevice.id, (rssi)=>log(`Device ${demoDevice.name} has an RSSI of ${rssi}`)); +ble.readRSSI(demoDevice.id, (rssi)=>log(`Device ${demoDevice.name} has an RSSI of ${rssi}`), err => log(`Unable to read RSSI: ${err}`)); + + +// request mtu +ble.requestMtu(demoDevice.id, 10); +ble.requestMtu(demoDevice.id, 10, () => log('it worked')); +ble.requestMtu(demoDevice.id, 10, () => log('it worked'), () => log('it failed')); + +// refreshDeviceCache +ble.refreshDeviceCache(demoDevice.id, 10); +ble.refreshDeviceCache(demoDevice.id, 10, () => log('it worked')); +ble.refreshDeviceCache(demoDevice.id, 10, () => log('it worked'), () => log('it failed')); var notificationsReceived : number = 0; //get notified of changes for that characteristic -ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data)=> notificationsReceived++, ()=> log(`darn`)); +ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, + (data)=> notificationsReceived++); +ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, + (data)=> notificationsReceived++, err => log(`darn: ${err}`)); //write some data +ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40)); +ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`)); ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); //write some data without getting notified +ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40)); +ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`)); ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); //stop getting notified of changes. ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic); +ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, () => log('it worked')); +ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, () => log('it worked'), () => log('it failed')); //notificationsReceived == 1 //just disconnect ble.disconnect(demoDevice.id); - - - +ble.disconnect(demoDevice.id, () => log('it worked')); +ble.disconnect(demoDevice.id, () => log('it worked'), () => log('it failed')); diff --git a/types/cordova-plugin-ble-central/index.d.ts b/types/cordova-plugin-ble-central/index.d.ts index ccf2396833..070b62ff9e 100644 --- a/types/cordova-plugin-ble-central/index.d.ts +++ b/types/cordova-plugin-ble-central/index.d.ts @@ -1,12 +1,13 @@ -// Type definitions for cordova-plugin-ble-central 1.1.2 +// Type definitions for cordova-plugin-ble-central 1.2.2 // Project: https://github.com/don/cordova-plugin-ble-central // Definitions by: Gidon Junge +// Philip Peitsch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace BLECentralPlugin { - interface PeripheralCharacteristic { + interface PeripheralCharacteristic { service: string; characteristic: string; properties: string[]; @@ -26,7 +27,12 @@ declare namespace BLECentralPlugin { characteristics: PeripheralCharacteristic[] } - + + interface BLEError { + name: string; + id: string; + errorMessage: string; + } interface StartScanOptions { @@ -34,75 +40,80 @@ declare namespace BLECentralPlugin { } export interface BLECentralPluginStatic { - scan(services: string[], seconds: number, success : (data: PeripheralData) => any): void; - scan(services: string[], seconds: number, success : (data: PeripheralData) => any, failure : () => any): void; - - startScan(services: string[], success: (data: PeripheralData) => any): void; - startScan(services: string[], success: (data: PeripheralData) => any, failure: () => any): void; + scan(services: string[], seconds: number, success : (data: PeripheralData) => any, failure? : (error: string) => any): void; - startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any): void; - startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any, failure: () => any): void; + startScan(services: string[], success: (data: PeripheralData) => any, failure?: (error: string|BLEError) => any): void; + + startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any, failure?: (error: string) => any): void; stopScan(): void; - stopScan(success: () => any): void; - stopScan(success: () => any, failure: () => any): void; - - connect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: () => any): void; + stopScan(success: () => any, failure?: () => any): void; - disconnect(device_id:string): void; - disconnect(device_id:string, success: () => any): void; - disconnect(device_id:string, success: () => any, failure: () => any): void; + connect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: (error: string|BLEError) => any): void; - read(device_id: string, service_uuid:string, characteristic_uuid:string): void; - read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; - read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; + /* Automatically connect to a device when it is in range of the phone + [iOS] background notifications on ios must be enabled if you want to run in the background + [Android] this relies on the autoConnect argument of BluetoothDevice.connectGatt(). Not all Android devices implement this feature correctly. */ + autoConnect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: (error: string|BLEError) => any): void; - write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; - write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; - write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + disconnect(device_id:string, success?: () => any, failure?: (error: string|BLEError) => any): void; - /* Writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack. + read(device_id: string, service_uuid:string, characteristic_uuid:string, success?: (rawData: ArrayBuffer) => any, failure?: (error: string|BLEError) => any): void; + + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success?: () => any, failure?: (error: string|BLEError) => any): void; + + /* Writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack. The success callback is be called when the characteristic is written.*/ - writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; - writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; - writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success?: () => any, failure?: (error: string) => any): void; /* Register to be notified when the value of a characteristic changes. */ - startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; - startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; - - stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string): void; - stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any): void; - stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any, failure: () => any): void; + startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure?: (error: string|BLEError) => any): void; + + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success?: () => any, failure?: (error: string|BLEError) => any): void; /* Reports if bluetooth is enabled. */ - isEnabled(success: () => any , failure: () => any): void; + isEnabled(success: () => any , failure: (error: string) => any): void; /* Calls the success callback when the peripheral is connected and the failure callback when not connected. */ - isConnected(device_id: string, success: () => any): void; - isConnected(device_id: string, success: () => any, failure: () => any): void; + isConnected(device_id: string, success: () => any, failure?: (error: string) => any): void; - startStateNotifications(success: (state: string) => any): void; - startStateNotifications(success: (state: string) => any, failure: () => any): void; + /* May be used to request (on Android) a larger MTU size to be able to send more data at once + [iOS] requestMtu is not supported on iOS. */ + requestMtu(device_id: string, mtu: number, success?: () => any, failure?: () => any): void; + + /* Clears cached services and characteristics info for some poorly behaved devices. Uses an undocumented API, + so it is not guaranteed to work. + [iOS] refreshDeviceCache is not supported on iOS. */ + refreshDeviceCache(device_id: string, timeout_millis: number, success?: (data: PeripheralDataExtended) => any, failure?: (error: string|BLEError) => any): void; + + startStateNotifications(success: (state: string) => any, failure?: (error: string) => any): void; + + stopStateNotifications(success?: () => any, failure?: () => any): void; - stopStateNotifications(): void; - stopStateNotifications(success: () => any): void; - stopStateNotifications(success: () => any, failure: () => any): void; - /* Opens the Bluetooth settings for the operating systems. [iOS] showBluetoothSettings is not supported on iOS. */ - showBluetoothSettings(): void; - showBluetoothSettings(success: () => any): void; showBluetoothSettings(success: () => any, failure: () => any): void; - + /* Enable Bluetooth on the device. [iOS] enable is not supported on iOS. */ - enable(success: () => any, failure: () => any): void; - + enable(success: () => any, failure: (error: string) => any): void; - readRSSI(device_id:string, success: (rssi: number) => any): void; - readRSSI(device_id:string, success: (rssi: number) => any, failure: () => any): void; + readRSSI(device_id:string, success: (rssi: number) => any, failure?: (error: string) => any): void; + + /* Find connected peripherals offering the listed service UUIDs. + This function wraps CBCentralManager.retrieveConnectedPeripheralsWithServices. + [Android] peripheralsWithIdentifiers is not supported on Android. */ + connectedPeripheralsWithServices(services: string[], success: (data: PeripheralData[]) => any, failure: () => any): void; + + /* Find known (but not necessarily connected) peripherals offering the listed service UUIDs. + This function wraps CBCentralManager.retrievePeripheralsWithIdentifiers + [Android] peripheralsWithIdentifiers is not supported on Android. */ + peripheralsWithIdentifiers(services: string[], success: (data: PeripheralData[]) => any, failure: () => any): void; + + /* Find the bonded devices. + [iOS] bondedDevices is not supported on iOS. */ + bondedDevices(success: (data: PeripheralData[]) => any, failure: () => any): void; } } -declare var ble: BLECentralPlugin.BLECentralPluginStatic; \ No newline at end of file +declare var ble: BLECentralPlugin.BLECentralPluginStatic; diff --git a/types/country-data/country-data-tests.ts b/types/country-data/country-data-tests.ts new file mode 100644 index 0000000000..850116dc63 --- /dev/null +++ b/types/country-data/country-data-tests.ts @@ -0,0 +1,14 @@ +import * as lib from 'country-data'; + +lib.callingCodes.all; // $ExpectType ReadonlyArray +lib.callingCountries.all; // $ExpectType ReadonlyArray +lib.continents.africa; // $ExpectType Continent +lib.continents.africa.countries; // $ExpectType ReadonlyArray +lib.countries.all; // $ExpectType ReadonlyArray +lib.currencies.all; // $ExpectType ReadonlyArray +lib.languages.all; // $ExpectType ReadonlyArray +lib.regions.antarctica; // $ExpectType Region +lib.regions.antarctica.countries; // $ExpectType ReadonlyArray +lib.lookup.countries(""); // $ExpectType ReadonlyArray +lib.lookup.currencies(""); // $ExpectType ReadonlyArray +lib.lookup.languages(""); // $ExpectType ReadonlyArray diff --git a/types/country-data/index.d.ts b/types/country-data/index.d.ts new file mode 100644 index 0000000000..80acbbcbba --- /dev/null +++ b/types/country-data/index.d.ts @@ -0,0 +1,103 @@ +// Type definitions for country-data 0.0 +// Project: https://github.com/OpenBookPrices/country-data +// Definitions by: Logan Dam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Country { + readonly alpha2: string; + readonly alpha3: string; + readonly countryCallingCodes: ReadonlyArray; + readonly currencies: ReadonlyArray; + readonly emoji: string; + readonly ioc: string; + readonly languages: ReadonlyArray; + readonly name: string; + readonly status: string; +} + +export interface Currency { + readonly code: string; + readonly decimals: number; + readonly name: string; + readonly number: number; +} + +export interface Language { + readonly alpha2: string; + readonly alpha3: string; + readonly bibliographic: string; + readonly name: string; +} + +export interface Continent { + readonly name: string; + readonly regions: ReadonlyArray; + readonly countries: ReadonlyArray; +} + +export interface Region { + readonly name: string; + readonly countries: ReadonlyArray; +} + +export const countries: { + readonly all: ReadonlyArray; +}; + +export const continents: { + readonly africa: Continent; + readonly antarctica: Continent; + readonly asia: Continent; + readonly europe: Continent; + readonly northAmerica: Continent; + readonly oceania: Continent; + readonly southAmerica: Continent; +}; + +export const callingCodes: { + readonly all: ReadonlyArray; +}; + +export const callingCountries: { + readonly all: ReadonlyArray; +}; + +export const currencies: { + readonly all: ReadonlyArray; +}; + +export const languages: { + readonly all: ReadonlyArray; +}; + +export const regions: { + readonly centralAsia: Region; + readonly southernAsia: Region; + readonly southeastAsia: Region; + readonly eastAsia: Region; + readonly westernAsia: Region; + readonly centralAfrica: Region; + readonly northAfrica: Region; + readonly southernAfrica: Region; + readonly eastAfrica: Region; + readonly westAfrica: Region; + readonly centralAmerica: Region; + readonly northernAmerica: Region; + readonly caribbean: Region; + readonly southAmerica: Region; + readonly antarctica: Region; + readonly northernEurope: Region; + readonly southernEurope: Region; + readonly easternEurope: Region; + readonly westernEurope: Region; + readonly australia: Region; + readonly melanesia: Region; + readonly micronesia: Region; + readonly polynesia: Region; +}; + +export const lookup: { + readonly countries: (query: any) => ReadonlyArray; + readonly currencies: (query: any) => ReadonlyArray; + readonly languages: (query: any) => ReadonlyArray; +}; diff --git a/types/country-data/tsconfig.json b/types/country-data/tsconfig.json new file mode 100644 index 0000000000..ccbbf6ecd6 --- /dev/null +++ b/types/country-data/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", + "country-data-tests.ts" + ] +} diff --git a/types/country-data/tslint.json b/types/country-data/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/country-data/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/custom-functions-runtime/custom-functions-runtime-tests.ts b/types/custom-functions-runtime/custom-functions-runtime-tests.ts index 0a3c482505..8f54ee4f5c 100644 --- a/types/custom-functions-runtime/custom-functions-runtime-tests.ts +++ b/types/custom-functions-runtime/custom-functions-runtime-tests.ts @@ -5,6 +5,11 @@ function add10(n: number) { CustomFunctions.associate('ADD10', add10); +CustomFunctions.associate({ + ADD10: add10, + RANDOM: (n: number) => n * Math.random() +}); + async function getStockValues(ticker: string): Promise { const response = await fetch(`myService.com/prices/${ticker}`); return (await response.json())["price"]; diff --git a/types/custom-functions-runtime/index.d.ts b/types/custom-functions-runtime/index.d.ts index f78f6a45c4..174308c131 100644 --- a/types/custom-functions-runtime/index.d.ts +++ b/types/custom-functions-runtime/index.d.ts @@ -16,9 +16,14 @@ Copyright (c) Microsoft Corporation declare namespace CustomFunctions { /** * @beta - * Ties together the function's JavaScript name with the JSON id property + * Associates the JavaScript function to the name given by the "id" property in the metadata JSON file. */ function associate(id: string, functionObject: Function): void; + /** + * @beta + * Associates the JavaScript functions to the names given by the "id" properties in the metadata JSON file. + */ + function associate(mappings: { [key: string]: Function }): void; /** * A handler passed automatically as the last parameter @@ -28,7 +33,6 @@ declare namespace CustomFunctions { * to handle what happens when the function stops streaming. * @beta */ - interface StreamingHandler extends CancelableHandler { /** * Sets the returned result for a streaming custom function. @@ -36,6 +40,7 @@ declare namespace CustomFunctions { */ setResult: (value: T | Error) => void; } + /** * @beta * CancelableHandler interface diff --git a/types/d3-geo/d3-geo-tests.ts b/types/d3-geo/d3-geo-tests.ts index 6e824e8e69..36c4debbe3 100644 --- a/types/d3-geo/d3-geo-tests.ts +++ b/types/d3-geo/d3-geo-tests.ts @@ -371,6 +371,7 @@ const gnomonicRaw: d3Geo.GeoRawProjection = d3Geo.geoGnomonicRaw(); const mercatorRaw: d3Geo.GeoRawProjection = d3Geo.geoMercatorRaw(); const orthographicRaw: d3Geo.GeoRawProjection = d3Geo.geoOrthographicRaw(); const stereographicRaw: d3Geo.GeoRawProjection = d3Geo.geoStereographicRaw(); +const equalEarthRaw: d3Geo.GeoRawProjection = d3Geo.geoEqualEarthRaw(); const transverseMercatorRaw: d3Geo.GeoRawProjection = d3Geo.geoTransverseMercatorRaw(); const naturalEarth1Raw: d3Geo.GeoRawProjection = d3Geo.geoNaturalEarth1Raw(); @@ -398,6 +399,7 @@ const gnomonic: d3Geo.GeoProjection = d3Geo.geoGnomonic(); const mercator: d3Geo.GeoProjection = d3Geo.geoMercator(); const orthographic: d3Geo.GeoProjection = d3Geo.geoOrthographic(); const stereographic: d3Geo.GeoProjection = d3Geo.geoStereographic(); +const equalEarth: d3Geo.GeoProjection = d3Geo.geoEqualEarth(); const transverseMercator: d3Geo.GeoProjection = d3Geo.geoTransverseMercator(); const naturalEarth1: d3Geo.GeoProjection = d3Geo.geoNaturalEarth1(); diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index 8f22503d71..16c51dfae6 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for D3JS d3-geo module 1.10 +// Type definitions for D3JS d3-geo module 1.11 // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 1.10.0 +// Last module patch version validated against: 1.11.3 import * as GeoJSON from 'geojson'; @@ -1345,11 +1345,22 @@ export function geoOrthographicRaw(): GeoRawProjection; * The stereographic projection. */ export function geoStereographic(): GeoProjection; + /** * The raw stereographic projection. */ export function geoStereographicRaw(): GeoRawProjection; +/** + * The Equal Eartch projection, by Bojan Šavrič et al., 2018. + */ +export function geoEqualEarth(): GeoProjection; + +/** + * The raw Equal Earth projection, by Bojan Šavrič et al., 2018. + */ +export function geoEqualEarthRaw(): GeoRawProjection; + // Composite Projections --------------------------------------------------- /** diff --git a/types/d3-shape/d3-shape-tests.ts b/types/d3-shape/d3-shape-tests.ts index 8ad3e4809a..fb79b15e4a 100644 --- a/types/d3-shape/d3-shape-tests.ts +++ b/types/d3-shape/d3-shape-tests.ts @@ -161,8 +161,9 @@ accessorArcDatumNumberOrNull = svgArc.padRadius(); // centroid(...) --------------------------------------------------------------------- -const centroid: [number, number] = svgArc.centroid(arcDatum); -// centroid = svgArc.centroid(arcDefaultDatum); // fails, wrong datum type +let centroid: [number, number] = svgArc.centroid(arcDatum); +// $ExpectError +centroid = svgArc.centroid(arcDefaultDatum); // fails, wrong datum type // generate arc ---------------------------------------------------------------------- @@ -176,10 +177,13 @@ const wrongArc1: Selection = select = select('.arc-paths'); // mock pArc.attr('d', svgArc); -// wrongArc1.attr('d', svgArc); // fails, incompatible this contexts -// wrongArc2.attr('d', svgArc); // fails, incompatible datum types +// $ExpectError +wrongArc1.attr('d', svgArc); // fails, incompatible this contexts +// $ExpectError +wrongArc2.attr('d', svgArc); // fails, incompatible datum types -// pathStringMaybe = svgArc(arcDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgArc(arcDatum); // fails, wrong this type for invocation // Use with custom object @@ -270,13 +274,13 @@ let pie: d3Shape.Pie = d3Shape.pie(); // value(...) ------------------------------------------------------------------------- -let defaultPieValueAccessor: (d: number | { valueOf(): number }, i?: number, data?: Array) => number; +let defaultPieValueAccessor: (d: number | { valueOf(): number }, i: number, data: Array) => number; defaultPie = defaultPie.value(10); defaultPieValueAccessor = defaultPie.value(); -let pieValueAccessor: (d: PieDatum, i?: number, data?: PieDatum[]) => number; +let pieValueAccessor: (d: PieDatum, i: number, data: PieDatum[]) => number; pie = pie.value((d, i, data) => { console.log(data.length > 0 ? data[0].val : 'no data'); // data type is Array @@ -364,8 +368,8 @@ interface LineDatum { missing: boolean; } -let lineXYAccessorFn: (d: LineDatum, index?: number, data?: LineDatum[]) => number; -let lineDefAccessorFn: (d: LineDatum, index?: number, data?: LineDatum[]) => boolean; +let lineXYAccessorFn: (d: LineDatum, index: number, data: LineDatum[]) => number; +let lineDefAccessorFn: (d: LineDatum, index: number, data: LineDatum[]) => boolean; interface LineRadialDatum { angle: number; @@ -373,8 +377,8 @@ interface LineRadialDatum { missing: boolean; } -let lineRadialAngRAccessorFn: (d: LineRadialDatum, index?: number, data?: LineRadialDatum[]) => number; -let lineRadialDefAccessorFn: (d: LineRadialDatum, index?: number, data?: LineRadialDatum[]) => boolean; +let lineRadialAngRAccessorFn: (d: LineRadialDatum, index: number, data: LineRadialDatum[]) => number; +let lineRadialDefAccessorFn: (d: LineRadialDatum, index: number, data: LineRadialDatum[]) => boolean; // line(...) create Line generator ===================================================== @@ -541,9 +545,9 @@ interface AreaDatum { missing: boolean; } -let areaXYAccessorFn: (d: AreaDatum, index?: number, data?: AreaDatum[]) => number; -let areaXYAccessorFnMaybe: null | ((d: AreaDatum, index?: number, data?: AreaDatum[]) => number); -let areaDefAccessorFn: (d: AreaDatum, index?: number, data?: AreaDatum[]) => boolean; +let areaXYAccessorFn: (d: AreaDatum, index: number, data: AreaDatum[]) => number; +let areaXYAccessorFnMaybe: null | ((d: AreaDatum, index: number, data: AreaDatum[]) => number); +let areaDefAccessorFn: (d: AreaDatum, index: number, data: AreaDatum[]) => boolean; interface AreaRadialDatum { startAngle: number; @@ -553,9 +557,9 @@ interface AreaRadialDatum { missing: boolean; } -let areaRadialAngRAccessorFn: (d: AreaRadialDatum, index?: number, data?: AreaRadialDatum[]) => number; -let areaRadialAngRAccessorFnMaybe: null | ((d: AreaRadialDatum, index?: number, data?: AreaRadialDatum[]) => number); -let areaRadialDefAccessorFn: (d: AreaRadialDatum, index?: number, data?: AreaRadialDatum[]) => boolean; +let areaRadialAngRAccessorFn: (d: AreaRadialDatum, index: number, data: AreaRadialDatum[]) => number; +let areaRadialAngRAccessorFnMaybe: null | ((d: AreaRadialDatum, index: number, data: AreaRadialDatum[]) => number); +let areaRadialDefAccessorFn: (d: AreaRadialDatum, index: number, data: AreaRadialDatum[]) => boolean; // area(...) create Area generator ===================================================== @@ -662,7 +666,8 @@ areaDefAccessorFn = area.defined(); defaultArea = defaultArea.curve(d3Shape.curveLinear); area = area.curve(d3Shape.curveCardinal.tension(0.5)); -// area = area.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods +// $ExpectError +area = area.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods currentCurveFactory = area.curve(); @@ -800,7 +805,8 @@ areaRadialDefAccessorFn = areaRadial.defined(); defaultAreaRadial = defaultAreaRadial.curve(d3Shape.curveLinear); areaRadial = areaRadial.curve(d3Shape.curveCardinal.tension(0.5)); -// areaRadial = areaRadial.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods +// $ExpectError +areaRadial = areaRadial.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods currentCurveFactory = areaRadial.curve(); @@ -868,7 +874,8 @@ curveBundleFactory = d3Shape.curveBundle.beta(0.5); lineOnlyGenerator = d3Shape.curveBundle.beta(0.5)(context!); // force context to be non-null with post-fix for mock lineOnlyGenerator = d3Shape.curveBundle.beta(0.5)(path()); -// curveGenerator = d3Shape.curveBundle.beta(0.5)(context); // fails, no area related methods +// $ExpectError +curveGenerator = d3Shape.curveBundle.beta(0.5)(context); // fails, no area related methods let curveCardinalFactory: d3Shape.CurveCardinalFactory; @@ -1153,22 +1160,28 @@ defaultLinkRadial(defaultLinkDatum); // vertical/horizontal pLink.attr('d', svgLink); -// wrongLink1.attr('d', svgLink); // fails, incompatible this contexts -// wrongLink2.attr('d', svgLink); // fails, incompatible datum types +// $ExpectError +wrongLink1.attr('d', svgLink); // fails, incompatible this contexts +// $ExpectError +wrongLink2.attr('d', svgLink); // fails, incompatible datum types pathStringMaybe = link(linkDatum); -// pathStringMaybe = svgLink(linkDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgLink(linkDatum); // fails, wrong this type for invocation // radial pLink.attr('d', svgLinkRadial); -// wrongLink1.attr('d', svgLinkRadial); // fails, incompatible this contexts -// wrongLink2.attr('d', svgLinkRadial); // fails, incompatible datum types +// $ExpectError +wrongLink1.attr('d', svgLinkRadial); // fails, incompatible this contexts +// $ExpectError +wrongLink2.attr('d', svgLinkRadial); // fails, incompatible datum types pathStringMaybe = radialLink(linkDatum); -// pathStringMaybe = svgLinkRadial(linkDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgLinkRadial(linkDatum); // fails, wrong this type for invocation // ----------------------------------------------------------------------------------- // Test Symbols @@ -1259,10 +1272,13 @@ const wrongSymbol1: Selection = select< const wrongSymbol2: Selection = select('.symbol-path'); // mock pSymbol.attr('d', svgSymbol); -// wrongSymbol1.attr('d', svgSymbol); // fails, incompatible this contexts -// wrongSymbol2.attr('d', svgSymbol); // fails, incompatible datum types +// $ExpectError +wrongSymbol1.attr('d', svgSymbol); // fails, incompatible this contexts +// $ExpectError +wrongSymbol2.attr('d', svgSymbol); // fails, incompatible datum types -// pathStringMaybe = svgSymbol(symbolDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgSymbol(symbolDatum); // fails, wrong this type for invocation // Use with custom object @@ -1390,11 +1406,11 @@ keysAccessor = overlyComplicatedStack.keys(); defaultStack = defaultStack.value(30); -overlyComplicatedStack = overlyComplicatedStack.value((d, key, j, data) => { +overlyComplicatedStack = overlyComplicatedStack.value((d, key, i, data) => { return d.values[key.name]; }); -let valueAccessorFn: (this: any, d: StackDatum, key: StackKey, j?: number, data?: StackDatum[]) => number; +let valueAccessorFn: (d: StackDatum, key: StackKey, i: number, data: StackDatum[]) => number; valueAccessorFn = overlyComplicatedStack.value(); // order(...) ---------------------------------------------------------------------- diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index 0c0e27cbd7..ed64d6f827 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for D3JS d3-shape module 1.2 // Project: https://github.com/d3/d3-shape/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -38,7 +41,7 @@ export interface CanvasPath_D3Shape { // ----------------------------------------------------------------------------------- /** - * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator + * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator. */ export interface DefaultArcObject { /** @@ -385,7 +388,7 @@ export function arc(): Arc; */ export interface PieArcDatum { /** - * The input datum; the corresponding element in the input data array of the Pie generator + * The input datum; the corresponding element in the input data array of the Pie generator. */ data: T; /** @@ -439,7 +442,6 @@ export interface Pie { /** * Returns the current value accessor, which defaults to a function returning the first argument passed into it. * The default value accessor assumes that the input data are numbers, or that they are coercible to numbers using valueOf. - * */ value(): (d: Datum, i: number, data: Datum[]) => number; /** @@ -455,7 +457,6 @@ export interface Pie { * The default value accessor assumes that the input data are numbers, or that they are coercible to numbers using valueOf. * If your data are not simply numbers, then you should specify an accessor that returns the corresponding numeric value for a given datum. * - * * @param value A value accessor function, which is invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. * It returns a numeric value. */ @@ -506,7 +507,6 @@ export interface Pie { * @param comparator The value comparator takes two arguments a and b which are values derived from the input data array using the value accessor, not the data elements. * If the arc for a should be before the arc for b, then the comparator must return a number less than zero; * if the arc for a should be after the arc for b, then the comparator must return a number greater than zero; returning zero means that the relative order of a and b is unspecified. - * */ sortValues(comparator: (a: number, b: number) => number): this; /** @@ -737,7 +737,7 @@ export interface Line { * Note that if a line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -912,7 +912,7 @@ export interface LineRadial { * Note that if a radial line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -1166,7 +1166,6 @@ export interface Area { * two-element array of numbers. * * If the y1 accessor is null, the previously-computed y0 value is reused for the y1 value. - * */ y1(): ((d: Datum, index: number, data: Datum[]) => number) | null; /** @@ -1209,9 +1208,9 @@ export interface Area { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -1228,7 +1227,7 @@ export interface Area { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, * being passed the element d, the index i, and the array data as three arguments. @@ -1248,7 +1247,6 @@ export interface Area { /** * Sets the curve factory and returns this area generator. * - * * @param curve A valid curve factory. */ curve(curve: CurveFactory): this; @@ -1470,7 +1468,6 @@ export interface AreaRadial { * two-element array of numbers. * * If the outerRadius accessor is null, the previously-computed innerRadius value is reused for the outerRadius value. - * */ outerRadius(): ((d: Datum, index: number, data: Datum[]) => number) | null; /** @@ -1515,9 +1512,9 @@ export interface AreaRadial { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -1533,7 +1530,7 @@ export interface AreaRadial { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, * being passed the element d, the index i, and the array data as three arguments. @@ -1668,16 +1665,13 @@ export interface CurveGeneratorLineOnly { /** * A factory for curve generators addressing only lines, but not areas. */ -// This is a base interface to be extended, hence the suppression of the warning -// tslint:disable-next-line:callable-types -export interface CurveFactoryLineOnly { +export type CurveFactoryLineOnly = /** * Returns a "lines only" curve generator which renders to the specified context. * - * @param context A rendering context + * @param context A rendering context. */ - (context: CanvasRenderingContext2D | Path): CurveGeneratorLineOnly; -} + (context: CanvasRenderingContext2D | Path) => CurveGeneratorLineOnly; /** * A minimal interface for a curve generator which supports the rendering of lines and areas. @@ -1704,16 +1698,13 @@ export interface CurveGenerator extends CurveGeneratorLineOnly { /** * A factory for curve generators addressing both lines and areas. */ -// This is a base interface to be extended, hence the suppression of the warning -// tslint:disable-next-line:callable-types -export interface CurveFactory { +export type CurveFactory = /** * Returns a curve generator which renders to the specified context. * - * @param context A rendering context + * @param context A rendering context. */ - (context: CanvasRenderingContext2D | Path): CurveGenerator; -} + (context: CanvasRenderingContext2D | Path) => CurveGenerator; /** * A curve factory for cubic basis spline generators. @@ -1924,7 +1915,7 @@ export const curveStepBefore: CurveFactory; /** * An interface describing the default Link Data structure expected - * by the Link and LinkRadial generators + * by the Link and LinkRadial generators. */ export interface DefaultLinkObject { /** @@ -2077,7 +2068,7 @@ export function linkHorizontal(): Link * * The first generic corresponds to the datum type of the link object for which the link is to be generated. * - * The second generic corresponds to the datum type of the source/target node contained in the link object + * The second generic corresponds to the datum type of the source/target node contained in the link object. */ export function linkHorizontal(): Link; /** @@ -2091,7 +2082,7 @@ export function linkHorizontal(): Link(): Link; @@ -2111,7 +2102,7 @@ export function linkVertical(): Link; * * The first generic corresponds to the datum type of the link object for which the link is to be generated. * - * The second generic corresponds to the datum type of the source/target node contained in the link object + * The second generic corresponds to the datum type of the source/target node contained in the link object. */ export function linkVertical(): Link; /** @@ -2125,7 +2116,7 @@ export function linkVertical(): Link(): Link; @@ -2262,7 +2253,7 @@ export function linkRadial(): LinkRadial(): LinkRadial; /** @@ -2276,7 +2267,7 @@ export function linkRadial(): LinkRadial(): LinkRadial; @@ -2289,7 +2280,7 @@ export function linkRadial(): LinkRadial { /** * Sets the symbol type to the specified symbol type and returns this symbol generator. * - * * @param type A constant symbol type. */ type(type: SymbolType): this; @@ -2485,7 +2475,7 @@ export function pointRadial(angle: number, radius: number): [number, number]; * the difference between y0 and y1 corresponds to the computed value for this point. * * SeriesPoint is a [number, number] two-element Array with added data and index properties - * related to the data element which formed the basis for theSeriesPoint + * related to the data element which formed the basis for theSeriesPoint. */ export interface SeriesPoint extends Array { /** @@ -2510,11 +2500,11 @@ export interface SeriesPoint extends Array { */ export interface Series extends Array> { /** - * Key of the series + * Key of the series. */ key: Key; /** - * Index of the series in the series array returned by stack generator + * Index of the series in the series array returned by stack generator. */ index: number; } @@ -2578,7 +2568,7 @@ export interface Stack { * * Thus, by default the stack generator assumes that the input data is an array of objects, with each object exposing named properties with numeric values; see stack for an example. */ - value(): (d: Datum, key: Key, j: number, data: Datum[]) => number; + value(): (d: Datum, key: Key, i: number, data: Datum[]) => number; /** * Sets the value accessor to the specified number and returns this stack generator. * @@ -2591,7 +2581,7 @@ export interface Stack { * @param value A value accessor function which returns the numeric value for a given data element and key combination. The accessor function is invoked for each data element and key being passed * the datum, the key, index of the data element in the input data array, and the complete data array. */ - value(value: (d: Datum, key: Key, j: number, data: Datum[]) => number): this; + value(value: (d: Datum, key: Key, i: number, data: Datum[]) => number): this; /** * Returns the current order accessor, which defaults to stackOrderNone; this uses the order given by the key accessor. @@ -2683,14 +2673,14 @@ export function stack(): Stack; /** * Returns a series order such that the smallest series (according to the sum of values) is at the bottom. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderAscending(series: Series): number[]; /** * Returns a series order such that the largest series (according to the sum of values) is at the bottom. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderDescending(series: Series): number[]; @@ -2698,28 +2688,28 @@ export function stackOrderDescending(series: Series): number[]; * Returns a series order such that the larger series (according to the sum of values) are on the inside and the smaller series are on the outside. * This order is recommended for streamgraphs in conjunction with the wiggle offset. See Stacked Graphs—Geometry & Aesthetics by Byron & Wattenberg for more information. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderInsideOut(series: Series): number[]; /** * Returns the given series order [0, 1, … n - 1] where n is the number of elements in series. Thus, the stack order is given by the key accessor. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderNone(series: Series): number[]; /** * Returns the reverse of the given series order [n - 1, n - 2, … 0] where n is the number of elements in series. Thus, the stack order is given by the reverse of the key accessor. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderReverse(series: Series): number[]; /** * Applies a zero baseline and normalizes the values for each point such that the topline is always one. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetExpand(series: Series, order: number[]): void; @@ -2727,7 +2717,7 @@ export function stackOffsetExpand(series: Series, order: number[]): vo /** * Positive values are stacked above zero, while negative values are stacked below zero. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetDiverging(series: Series, order: number[]): void; @@ -2735,7 +2725,7 @@ export function stackOffsetDiverging(series: Series, order: number[]): /** * Applies a zero baseline. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetNone(series: Series, order: number[]): void; @@ -2743,7 +2733,7 @@ export function stackOffsetNone(series: Series, order: number[]): void /** * Shifts the baseline down such that the center of the streamgraph is always at zero. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetSilhouette(series: Series, order: number[]): void; @@ -2752,7 +2742,7 @@ export function stackOffsetSilhouette(series: Series, order: number[]) * Shifts the baseline so as to minimize the weighted wiggle of layers. This offset is recommended for streamgraphs in conjunction with the inside-out order. * See Stacked Graphs—Geometry & Aesthetics by Bryon & Wattenberg for more information. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetWiggle(series: Series, order: number[]): void; diff --git a/types/d3-shape/tsconfig.json b/types/d3-shape/tsconfig.json index 0436aafd66..093e9b98c3 100644 --- a/types/d3-shape/tsconfig.json +++ b/types/d3-shape/tsconfig.json @@ -8,7 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/d3-shape/tslint.json b/types/d3-shape/tslint.json index b1ba182ba6..54efb0b84e 100644 --- a/types/d3-shape/tslint.json +++ b/types/d3-shape/tslint.json @@ -1,10 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO - "no-this-assignment": false, "unified-signatures": false, - "callable-types": false, "no-unnecessary-generics": false } } diff --git a/types/d3/index.d.ts b/types/d3/index.d.ts index 43c264f280..9b62c1e025 100644 --- a/types/d3/index.d.ts +++ b/types/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 5.5 +// Type definitions for D3JS d3 standard bundle 5.7 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek // Alex Ford @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 5.5.0 +// Last module patch version validated against: 5.7.0 // NOTE TO MAINTAINERS: Review D3 v4.x module dependencies (see v4 sub-folder) and update its path-mappings in tsconfig (v4 folder), // if new MAJOR version of D3 v4 modules are released!!! diff --git a/types/debounce-fn/debounce-fn-tests.ts b/types/debounce-fn/debounce-fn-tests.ts new file mode 100644 index 0000000000..9f9d3881e9 --- /dev/null +++ b/types/debounce-fn/debounce-fn-tests.ts @@ -0,0 +1,10 @@ +import debounceFn = require('debounce-fn'); + +const debounced = debounceFn((s: string) => true); +debounced; // $ExpectType ((s: string) => boolean | undefined) & { cancel(): void; } + +debounceFn((s: string) => true); +debounceFn((s: string) => true, { wait: 100 }); +debounceFn((s: string) => true, { immediate: true }); + +debounced.cancel(); diff --git a/types/debounce-fn/index.d.ts b/types/debounce-fn/index.d.ts new file mode 100644 index 0000000000..01e147a14a --- /dev/null +++ b/types/debounce-fn/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for debounce-fn 1.0 +// Project: https://github.com/sindresorhus/debounce-fn#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +export = debounce; + +/** + * Returns a debounced function that delays calling the `input` function until after `wait` milliseconds + * have elapsed since the last time the debounced function was called. + * + * It comes with a `.cancel()` method to cancel any scheduled `input` function calls. + */ +declare function debounce( + input: (...args: TArgs) => TResult, + options?: debounce.Options +): ((...args: TArgs) => TResult | undefined) & { cancel(): void }; + +declare namespace debounce { + interface Options { + /** + * Time to wait until the `input` function is called. + * @default 0 + */ + wait?: number; + /** + * Trigger the function on the leading edge instead of the trailing edge of the `wait` interval. + * For example, can be useful for preventing accidental double-clicks on a "submit" button + * from firing a second time. + */ + immediate?: boolean; + } +} diff --git a/types/debounce-fn/tsconfig.json b/types/debounce-fn/tsconfig.json new file mode 100644 index 0000000000..f2d90018fb --- /dev/null +++ b/types/debounce-fn/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", + "debounce-fn-tests.ts" + ] +} diff --git a/types/debounce-fn/tslint.json b/types/debounce-fn/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/debounce-fn/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index cd06bc7ebb..bdbda1ed95 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -151,8 +151,8 @@ declare namespace Dockerode { modem: any; name: string; - inspect(callback: Callback): void; - inspect(): Promise; + inspect(callback: Callback): void; + inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; @@ -367,6 +367,22 @@ declare namespace Dockerode { Ingress: boolean; } + interface VolumeInspectInfo { + Name: string; + Driver: string; + Mountpoint: string; + Status?: { [key: string]: string }; + Labels: { [key: string]: string }; + Scope: 'local' | 'global'; + // Field is always present, but sometimes is null + Options: { [key: string]: string } | null; + // Field is sometimes present, and sometimes null + UsageData?: { + Size: number; + RefCount: number; + } | null; + } + interface ContainerInspectInfo { Id: string; Created: string; @@ -1140,9 +1156,18 @@ declare class Dockerode { listPlugins(callback: Callback): void; listPlugins(options?: {}): Promise; - listVolumes(options: {}, callback: Callback): void; - listVolumes(callback: Callback): void; - listVolumes(options?: {}): Promise; + listVolumes(options: {}, callback: Callback<{ + Volumes: Dockerode.VolumeInspectInfo[]; + Warnings: string[]; + }>): void; + listVolumes(callback: Callback<{ + Volumes: Dockerode.VolumeInspectInfo[]; + Warnings: string[]; + }>): void; + listVolumes(options?: {}): Promise<{ + Volumes: Dockerode.VolumeInspectInfo[]; + Warnings: string[]; + }>; listNetworks(options: {}, callback: Callback): void; listNetworks(callback: Callback): void; diff --git a/types/doge-seed/doge-seed-tests.ts b/types/doge-seed/doge-seed-tests.ts new file mode 100644 index 0000000000..fa47414d65 --- /dev/null +++ b/types/doge-seed/doge-seed-tests.ts @@ -0,0 +1,4 @@ +import dogeSeed = require('doge-seed'); + +dogeSeed(); // $ExpectType string +dogeSeed(128); // $ExpectType string diff --git a/types/doge-seed/index.d.ts b/types/doge-seed/index.d.ts new file mode 100644 index 0000000000..8670f36332 --- /dev/null +++ b/types/doge-seed/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for doge-seed 1.0 +// Project: https://github.com/lukechilds/doge-seed#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = dogeSeed; + +/** + * Generates a cryptographically secure mnemonic seed phrase with added dankness. + * The first four words will be a randomly generated Doge-like sentence. + * + * The seed phrases are fully valid checksummed BIP39 seeds. They can be used with any cryptocurrency + * and can be imported into any BIP39 compliant wallet. + * + * @param bits The number of bits to derive a BIP39 mnemonic from. Default: `128`. + * @returns A BIP39 mnemonic seed phrase. + */ +declare function dogeSeed(bits?: 128 | 160 | 192 | 224 | 256): string; diff --git a/types/doge-seed/tsconfig.json b/types/doge-seed/tsconfig.json new file mode 100644 index 0000000000..cd46d1ee9c --- /dev/null +++ b/types/doge-seed/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", + "doge-seed-tests.ts" + ] +} diff --git a/types/doge-seed/tslint.json b/types/doge-seed/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/doge-seed/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dotenv-webpack/dotenv-webpack-tests.ts b/types/dotenv-webpack/dotenv-webpack-tests.ts index 6605550529..b4d7e849d8 100644 --- a/types/dotenv-webpack/dotenv-webpack-tests.ts +++ b/types/dotenv-webpack/dotenv-webpack-tests.ts @@ -3,19 +3,27 @@ import DotenvWebpackPlugin = require('dotenv-webpack'); new DotenvWebpackPlugin(); // $ExpectType DotenvWebpackPlugin -const options: DotenvWebpackPlugin.Options = { +const optionsEmpty: DotenvWebpackPlugin.Options = {}; + +const optionsFull: DotenvWebpackPlugin.Options = { path: './some.other.env', safe: true, systemvars: true, - silent: true + silent: true, + expand: true, + defaults: true +}; + +const optionsStrings: DotenvWebpackPlugin.Options = { + safe: './some.other.env.example', + defaults: './some.other.env.defaults' }; const config: webpack.Configuration = { plugins: [ new DotenvWebpackPlugin(), - new DotenvWebpackPlugin({ - path: './some.other.env', - }), - new DotenvWebpackPlugin(options), + new DotenvWebpackPlugin(optionsEmpty), + new DotenvWebpackPlugin(optionsFull), + new DotenvWebpackPlugin(optionsStrings) ] }; diff --git a/types/dotenv-webpack/index.d.ts b/types/dotenv-webpack/index.d.ts index 2d330ace45..25c64b7905 100644 --- a/types/dotenv-webpack/index.d.ts +++ b/types/dotenv-webpack/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for dotenv-webpack 1.5 +// Type definitions for dotenv-webpack 1.7 // Project: https://github.com/mrsteele/dotenv-webpack // Definitions by: Karol Majewski +// Dave Cardwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 @@ -20,7 +21,7 @@ declare namespace DotenvWebpackPlugin { /** * If `false` ignore safe-mode, if `true` load `'./.env.example'`, if a `string` load that file as the sample. Default: `false`. */ - safe?: boolean; + safe?: boolean | string; /** * Set to `true` if you would rather load all system variables as well (useful for CI purposes). Default: `false`. @@ -31,6 +32,17 @@ declare namespace DotenvWebpackPlugin { * If `true`, all warnings will be surpressed. Default: `false`. */ silent?: boolean; + + /** + * Allows your variables to be "expanded" for reusability within your .env file. Default: `false`. + */ + expand?: boolean; + + /** + * Adds support for dotenv-defaults. If set to `true`, uses `./.env.defaults`. If a `string`, uses that location for a defaults file. + * Read more at https://www.npmjs.com/package/dotenv-defaults. Default: `false`. + */ + defaults?: boolean | string; } } diff --git a/types/elliptic/elliptic-tests.ts b/types/elliptic/elliptic-tests.ts index d587be5e8d..8af88b46a4 100644 --- a/types/elliptic/elliptic-tests.ts +++ b/types/elliptic/elliptic-tests.ts @@ -1,4 +1,5 @@ import elliptic = require('elliptic'); +import BN = require('bn.js'); const ec = new elliptic.ec('secp256k1'); @@ -45,3 +46,49 @@ const newKey = ec.keyFromPublic(pub, 'hex'); // Verify signature console.log(key.verify(msgHash, signature)); + +// EDDSA tests +const eddsa = new elliptic.eddsa('ed25519'); +const msg = Buffer.from('dead', 'hex'); +const priv = 'deadbeef'; + +const sig = eddsa.sign(msg, priv); +sig.toHex(); +sig.toBytes(); +eddsa.sign(msg.toString('hex'), priv).toHex(); + +const edkey = eddsa.keyFromSecret(priv); +edkey.verify(msg, sig); +edkey.verify(msg.toString('hex'), sig.toBytes()); + +const edkey2 = eddsa.keyFromPublic(key.getPublic()); +edkey2.verify(msg, sig); + +eddsa.verify(msg, sig, edkey2.getPublic('hex')); +eddsa.verify(msg.toString('hex'), sig.toBytes(), edkey2.getPublic()); +eddsa.verify(msg, sig.toHex(), edkey2.getPublic()); + +// Curves Tests +elliptic.curve.base.BasePoint; + +const c = new elliptic.curve.edwards({ + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: -1, + c: 1, + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', +}); + +const p = c.pointFromX(5555); +p.eq(p); +eddsa.isPoint(p); +c.validate(p.add(p).mul(new BN(3)).dbl()); + +const sc = new elliptic.curve.short({ + a: 1, + b: 0, + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', +}); + +const p2 = sc.pointFromX(123456789); +sc.validate(p2.add(p2).mul(new BN(5)).dbl()); +sc.pointFromJSON(p2.toJSON(), false).toJSON(); diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts index 7ae7972150..2f1ceb9aab 100644 --- a/types/elliptic/index.d.ts +++ b/types/elliptic/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for elliptic 6.4 // Project: https://github.com/indutny/elliptic // Definitions by: Daniel Byrne +// Gaylor Bosson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import BN = require('bn.js'); @@ -8,151 +9,286 @@ import BN = require('bn.js'); // incomplete typings export const utils: any; export const rand: any; -export const eddsa: any; export type BNInput = string | BN | number | Buffer | number[]; export const version: number; export namespace curve { - class BaseCurve { - constructor(type: string, conf: BaseCurve.BaseCurveOptions) - p: BN; - type: string; - red: any; // ? - zero: any; // ? - one: any; // ? - two: any; // ? - n: BN | undefined | null; - g: any; // ? - redN: any; // ? - decodePoint(bytes: any, enc: string): any; // ? - } + /** + * @description Base class for the curves + */ + class base { + p: BN; + type: string; + red: any; // ? + zero: BN; + one: BN; + two: BN; + n: BN; + g: base.BasePoint; + redN: BN; - namespace BaseCurve { - class BasePoint { - constructor(curve: any, type: string); - curve: any; - type: string; - precomputed: PrecomputedValues | null; - encode(enc: string, compact: boolean): BN; - encodeCompressed(enc: string): BN; - validate(): boolean; - precompute(power: number): BasePoint; - dblp(k: any): any; // ? - } + constructor(type: string, conf: base.BaseCurveOptions) - interface BaseCurveOptions { - p: number | string | number[] | Buffer | BN; - prime?: BN | string; - n?: number | BN | Buffer; - g?: any; // ? - gRed?: any; // ? - } + validate(point: base.BasePoint): boolean; + decodePoint(bytes: Buffer | string, enc?: 'hex'): base.BasePoint; + } - interface PrecomputedValues { - doubles: any; // ? - naf: any; // ? - beta: any; // ? - } - } + namespace base { + class BasePoint { + curve: base; + type: string; + precomputed: PrecomputedValues | null; + + constructor(curve: base, type: string); + + encode(enc: string, compact: boolean): string | Buffer; + encodeCompressed(enc: string): BN; + validate(): boolean; + precompute(power: number): BasePoint; + dblp(k: number): BasePoint; + inspect(): string; + isInfinity(): boolean; + add(p: BasePoint): BasePoint; + mul(k: BN): BasePoint; + dbl(): BasePoint; + getX(): BN; + getY(): BN; + eq(p: BasePoint): boolean; + neg(): BasePoint; + } + + interface BaseCurveOptions { + p: number | string | number[] | Buffer | BN; + prime?: BN | string; + n?: number | BN | Buffer; + g?: BasePoint; + gRed?: any; // ? + } + + interface PrecomputedValues { + doubles: any; // ? + naf: any; // ? + beta: any; // ? + } + } + + class edwards extends base { + a: BN; + c: BN; + c2: BN; + d: BN; + dd: BN; + + constructor(conf: edwards.EdwardsConf); + + point(x: BNInput, y: BNInput, z?: BNInput, t?: BNInput): edwards.EdwardsPoint; + pointFromX(x: BNInput, odd?: boolean): edwards.EdwardsPoint; + pointFromY(y: BNInput, odd?: boolean): edwards.EdwardsPoint; + pointFromJSON(obj: BNInput[]): edwards.EdwardsPoint; + } + + namespace edwards { + interface EdwardsConf extends base.BaseCurveOptions { + a: BNInput; + c: BNInput; + d: BNInput; + } + + class EdwardsPoint extends base.BasePoint { + x: BN; + y: BN; + z: BN; + t: BN; + + normalize(): EdwardsPoint; + eqXToP(x: BN): boolean; + } + } + + class short extends base { + a: BNInput; + b: BNInput; + g: short.ShortPoint; + + constructor(conf: short.ShortConf); + + point(x: BNInput, y: BNInput, isRed?: boolean): short.ShortPoint; + pointFromX(x: BNInput, odd?: boolean): short.ShortPoint; + pointFromJSON(obj: BNInput[], red: boolean): short.ShortPoint; + } + + namespace short { + interface ShortConf extends base.BaseCurveOptions { + a: BNInput; + b: BNInput; + beta?: BNInput; + lambda?: BNInput; + } + + class ShortPoint extends base.BasePoint { + x: BN; + y: BN; + inf: boolean; + + toJSON(): BNInput[]; + } + } } export namespace curves { - class PresetCurve { - constructor(options: PresetCurve.Options) - type: string; - g: any; // ? - n: BN | undefined | null; - hash: any; // ? - } + class PresetCurve { + type: string; + g: any; // ? + n: BN | undefined | null; + hash: any; // ? - namespace PresetCurve { - interface Options { - type: string; - prime: string | null; - p: string; - a: string; - b: string; - n: string; - hash: any; - gRed: boolean; - g: any; // ? - beta?: string; - lambda?: string; - basis?: any; // ? - } - } + constructor(options: PresetCurve.Options) + } + + namespace PresetCurve { + interface Options { + type: string; + prime: string | null; + p: string; + a: string; + b: string; + n: string; + hash: any; + gRed: boolean; + g: any; // ? + beta?: string; + lambda?: string; + basis?: any; // ? + } + } } export class ec { - constructor(options: string | curves.PresetCurve) - curve: any; - n: BN | undefined | null; - nh: any; - g: any; - hash: any; + curve: any; + n: BN | undefined | null; + nh: any; + g: any; + hash: any; - keyPair(options: ec.KeyPairOptions): ec.KeyPair; - keyFromPrivate(priv: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; - keyFromPublic(pub: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; - genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; - sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; - sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; - verify(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, key: Buffer | ec.KeyPair, enc?: string): boolean; - recoverPubKey(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, j: number, enc?: string): any; - getKeyRecoveryParam(e: Error | undefined, signature: ec.Signature | ec.SignatureOptions, Q: BN, enc?: string): number; + constructor(options: string | curves.PresetCurve) + + keyPair(options: ec.KeyPairOptions): ec.KeyPair; + keyFromPrivate(priv: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPublic(pub: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; + genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; + sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; + sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; + verify(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, key: Buffer | ec.KeyPair, enc?: string): boolean; + recoverPubKey(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, j: number, enc?: string): any; + getKeyRecoveryParam(e: Error | undefined, signature: ec.Signature | ec.SignatureOptions, Q: BN, enc?: string): number; } export namespace ec { - interface GenKeyPairOptions { - pers: any; - entropy: any; - persEnc?: string; - entropyEnc?: string; - } + interface GenKeyPairOptions { + pers: any; + entropy: any; + persEnc?: string; + entropyEnc?: string; + } - interface SignOptions { - pers: any; - persEnc?: string; - canonical?: boolean; - k?: BN; - } + interface SignOptions { + pers: any; + persEnc?: string; + canonical?: boolean; + k?: BN; + } - class KeyPair { - static fromPublic(ec: ec, pub: Buffer | KeyPair, enc?: string): KeyPair; - static fromPrivate(ec: ec, priv: Buffer | KeyPair, enc?: string): KeyPair; - constructor(ec: ec, options: KeyPairOptions) - ec: ec; - validate(): { readonly result: boolean, readonly reason: string }; - getPublic(compact: boolean, enc?: string): any; // ? - getPublic(enc?: string): any; // ? - getPrivate(enc?: 'hex'): Buffer | BN | string; - derive(pub: any): any; // ? - sign(msg: BNInput, enc: string, options?: SignOptions): Signature; - sign(msg: BNInput, options?: SignOptions): Signature; - verify(msg: BNInput, signature: Signature | SignatureOptions): boolean; - inspect(): string; - } + class KeyPair { + static fromPublic(ec: ec, pub: Buffer | KeyPair, enc?: string): KeyPair; + static fromPrivate(ec: ec, priv: Buffer | KeyPair, enc?: string): KeyPair; - class Signature { - constructor(options: SignatureOptions | Signature, enc?: string) - r: BN; - s: BN; - recoveryParam: number | null; - toDER(enc?: string | null): any; // ? - } + ec: ec; - interface SignatureOptions { - r: BNInput; - s: BNInput; - recoveryParam?: number; - } + constructor(ec: ec, options: KeyPairOptions) - interface KeyPairOptions { - priv?: Buffer; - privEnc?: string; - pub?: Buffer; - pubEnc?: string; - } + validate(): { readonly result: boolean, readonly reason: string }; + getPublic(compact: boolean, enc?: string): any; // ? + getPublic(enc?: string): any; // ? + getPrivate(enc?: 'hex'): Buffer | BN | string; + derive(pub: any): any; // ? + sign(msg: BNInput, enc: string, options?: SignOptions): Signature; + sign(msg: BNInput, options?: SignOptions): Signature; + verify(msg: BNInput, signature: Signature | SignatureOptions): boolean; + inspect(): string; + } + + class Signature { + r: BN; + s: BN; + recoveryParam: number | null; + + constructor(options: SignatureOptions | Signature, enc?: string) + + toDER(enc?: string | null): any; // ? + } + + interface SignatureOptions { + r: BNInput; + s: BNInput; + recoveryParam?: number; + } + + interface KeyPairOptions { + priv?: Buffer; + privEnc?: string; + pub?: Buffer; + pubEnc?: string; + } +} + +export class eddsa { + curve: curve.edwards; + + constructor(name: 'ed25519'); + + sign(message: eddsa.Bytes, secret: eddsa.Bytes): eddsa.Signature; + verify(message: eddsa.Bytes, sig: eddsa.Bytes | eddsa.Signature, pub: eddsa.Bytes | eddsa.Point | eddsa.KeyPair): boolean; + hashInt(): BN; + keyFromPublic(pub: eddsa.Bytes): eddsa.KeyPair; + keyFromSecret(secret: eddsa.Bytes): eddsa.KeyPair; + makeSignature(sig: eddsa.Signature | Buffer | string): eddsa.Signature; + encodePoint(point: eddsa.Point): Buffer; + decodePoint(bytes: eddsa.Bytes): eddsa.Point; + encodeInt(num: BN): Buffer; + decodeInt(bytes: BNInput): BN; + isPoint(val: any): boolean; +} + +export namespace eddsa { + type Point = curve.base.BasePoint; + type Bytes = string | Buffer; + + class Signature { + constructor(eddsa: eddsa, sig: Signature | Bytes); + + toBytes(): Buffer; + toHex(): string; + } + + class KeyPair { + constructor(eddsa: eddsa, params: KeyPairOptions); + + static fromPublic(eddsa: eddsa, pub: Bytes): KeyPair; + static fromSecret(eddsa: eddsa, secret: Bytes): KeyPair; + + secret(): Buffer; + sign(message: Bytes): Signature; + verify(message: Bytes, sig: Signature | Bytes): boolean; + getSecret(enc: 'hex'): string; + getSecret(): Buffer; + getPublic(enc: 'hex'): string; + getPublic(): Buffer; + } + + interface KeyPairOptions { + secret: Buffer; + pub: Buffer | Point; + } } diff --git a/types/ember-qunit/ember-qunit-tests.ts b/types/ember-qunit/ember-qunit-tests.ts index acd9650f98..9e85253ae9 100644 --- a/types/ember-qunit/ember-qunit-tests.ts +++ b/types/ember-qunit/ember-qunit-tests.ts @@ -139,4 +139,11 @@ module('foo service', function(hooks) { setupTest(hooks); }); +// RFC-232 equivalent of https://github.com/ember-engines/ember-engines#unitintegration-testing-for-in-repo-engines +module('engine foo component', function(hooks) { + setupTest(hooks, { + resolver: Ember.Resolver.create() + }); +}); + start(); diff --git a/types/ember-qunit/index.d.ts b/types/ember-qunit/index.d.ts index 6b3188fdfc..1ce6f90483 100644 --- a/types/ember-qunit/index.d.ts +++ b/types/ember-qunit/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Derek Wickern // Mike North // Steve Calvert +// Dan Freeman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -46,6 +47,13 @@ declare module 'ember-qunit' { */ export function setResolver(resolver: Ember.Resolver): void; + interface SetupTestOptions { + /** + * The resolver to use when instantiating container-managed entities in the test. + */ + resolver?: Ember.Resolver; + } + /** * Sets up acceptance tests. * @@ -58,7 +66,7 @@ declare module 'ember-qunit' { * * `this.pauseTest` and `this.resumeTest` - allow easy pausing/resuming of tests. * * `this.element` which returns the DOM element representing the application's root element. */ - export function setupApplicationTest(hooks: NestedHooks): void; + export function setupApplicationTest(hooks: NestedHooks, options?: SetupTestOptions): void; /** * Sets up tests that need to render snippets of templates. @@ -79,7 +87,7 @@ declare module 'ember-qunit' { * * this.$(...) - When jQuery is present, executes a jQuery selector with * the current this.element as its root */ - export function setupRenderingTest(hooks: NestedHooks): void; + export function setupRenderingTest(hooks: NestedHooks, options?: SetupTestOptions): void; /** * Sets up tests that do not need to render snippets of templates. @@ -94,7 +102,7 @@ declare module 'ember-qunit' { * * this.set / this.setProperties - Allows setting values on the test context. * * this.get / this.getProperties - Retrieves values from the test context. */ - export function setupTest(hooks: NestedHooks): void; + export function setupTest(hooks: NestedHooks, options?: SetupTestOptions): void; export class QUnitAdapter extends Ember.Test.Adapter { } diff --git a/types/ember__test-helpers/ember__test-helpers-tests.ts b/types/ember__test-helpers/ember__test-helpers-tests.ts index 9fe9e4c297..89b536e51f 100644 --- a/types/ember__test-helpers/ember__test-helpers-tests.ts +++ b/types/ember__test-helpers/ember__test-helpers-tests.ts @@ -11,6 +11,7 @@ import { blur, triggerEvent, triggerKeyEvent, + typeIn, fillIn, render, find, @@ -54,6 +55,7 @@ test('DOM interactions', async () => { await triggerEvent(messageElement, 'custom-event'); await triggerKeyEvent(messageElement, 'keydown', 'Enter', { ctrlKey: true }); await fillIn(messageElement, 'content'); + await typeIn(messageElement, 'content'); const allMessages = findAll('.message'); for (const element of allMessages) { diff --git a/types/ember__test-helpers/index.d.ts b/types/ember__test-helpers/index.d.ts index 8a3d6f0ef9..0c7dc544b9 100644 --- a/types/ember__test-helpers/index.d.ts +++ b/types/ember__test-helpers/index.d.ts @@ -22,6 +22,7 @@ declare module '@ember/test-helpers' { export { default as triggerEvent } from '@ember/test-helpers/dom/trigger-event'; export { default as triggerKeyEvent } from '@ember/test-helpers/dom/trigger-key-event'; export { default as fillIn } from '@ember/test-helpers/dom/fill-in'; + export { default as typeIn } from '@ember/test-helpers/dom/type-in'; // DOM Query Helpers @@ -117,6 +118,12 @@ declare module '@ember/test-helpers/dom/fill-in' { export default function(target: Target, text: string): Promise; } +declare module '@ember/test-helpers/dom/type-in' { + import { Target } from '@ember/test-helpers'; + + export default function(target: Target, text: string, options?: {delay: number}): Promise; +} + declare module '@ember/test-helpers/dom/find' { export default function(selector: string): Element | null; } diff --git a/types/eventsource/eventsource-tests.ts b/types/eventsource/eventsource-tests.ts index c1b53030cd..d06c79cdde 100644 --- a/types/eventsource/eventsource-tests.ts +++ b/types/eventsource/eventsource-tests.ts @@ -10,9 +10,9 @@ let openState: number = eventSource.OPEN; openState = EventSource.OPEN; let url: string = eventSource.url; let withCredentials: boolean = eventSource.withCredentials; -eventSource.onmessage = (event: Event) => {}; -eventSource.onerror = (event: Event) => {}; -eventSource.onopen = (event: Event) => {}; +eventSource.onmessage = (event: MessageEvent) => {}; +eventSource.onerror = (event: MessageEvent) => {}; +eventSource.onopen = (event: MessageEvent) => {}; eventSource.addEventListener = (type: string, listener: (e: Event) => void) => {}; eventSource.dispatchEvent = (event: Event) => true; eventSource.removeEventListener = (type: string, listener: (e: Event) => void) => {}; @@ -30,9 +30,9 @@ openState = eventSource.OPEN; openState = EventSource.OPEN; url = eventSourcePolyfill.url; withCredentials = eventSource.withCredentials; -eventSourcePolyfill.onmessage = (event: Event) => {}; -eventSourcePolyfill.onerror = (event: Event) => {}; -eventSourcePolyfill.onopen = (event: Event) => {}; +eventSourcePolyfill.onmessage = (event: MessageEvent) => {}; +eventSourcePolyfill.onerror = (event: MessageEvent) => {}; +eventSourcePolyfill.onopen = (event: MessageEvent) => {}; eventSourcePolyfill.addEventListener = (type: string, listener: (e: Event) => void) => {}; eventSourcePolyfill.dispatchEvent = (event: Event) => true; eventSourcePolyfill.removeEventListener = (type: string, listener: (e: Event) => void) => {}; diff --git a/types/eventsource/index.d.ts b/types/eventsource/index.d.ts index 1308515917..f0dcd7513f 100644 --- a/types/eventsource/index.d.ts +++ b/types/eventsource/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for eventsource 1.0 +// Type definitions for eventsource 1.1 // Project: http://github.com/EventSource/eventsource // Definitions by: Scott Lee Davis // Ali Afroozeh +// Pedro Gámez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -18,9 +19,9 @@ declare class EventSource { readonly url: string; readonly readyState: number; readonly withCredentials: boolean; - onopen: EventListener; - onmessage: EventListener; - onerror: EventListener; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; addEventListener(type: string, listener: EventListener): void; dispatchEvent(evt: Event): boolean; removeEventListener(type: string, listener?: EventListener): void; @@ -28,7 +29,7 @@ declare class EventSource { } declare namespace EventSource { - enum ReadyState {CONNECTING = 0, OPEN = 1, CLOSED = 2} + enum ReadyState { CONNECTING = 0, OPEN = 1, CLOSED = 2 } interface EventSourceInitDict { withCredentials?: boolean; diff --git a/types/eventsource/lib/eventsource-polyfill/index.d.ts b/types/eventsource/lib/eventsource-polyfill/index.d.ts index 86b82105cc..74e3e22faa 100644 --- a/types/eventsource/lib/eventsource-polyfill/index.d.ts +++ b/types/eventsource/lib/eventsource-polyfill/index.d.ts @@ -11,9 +11,9 @@ declare class EventSource { readonly url: string; readonly readyState: number; readonly withCredentials: boolean; - onopen: EventListener; - onmessage: EventListener; - onerror: EventListener; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; addEventListener(type: string, listener: EventListener): void; dispatchEvent(evt: Event): boolean; removeEventListener(type: string, listener?: EventListener): void; diff --git a/types/execall/execall-tests.ts b/types/execall/execall-tests.ts new file mode 100644 index 0000000000..8a9d3b7768 --- /dev/null +++ b/types/execall/execall-tests.ts @@ -0,0 +1,3 @@ +import execall = require('execall'); + +execall(/(\d+)/g, '$200 and $400'); // $ExpectType Match[] diff --git a/types/execall/index.d.ts b/types/execall/index.d.ts new file mode 100644 index 0000000000..29e7d3945e --- /dev/null +++ b/types/execall/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for execall 1.0 +// Project: https://github.com/sindresorhus/execall +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = execall; + +/** + * Find multiple RegExp matches in a string. Instead of having to iterate over + * `RegExp#exec`, immutable, and with a nicer result format. + * + * @param re Regular expression to match against the `input`. + * @returns An array of matches. + */ +declare function execall(re: RegExp, input: string): execall.Match[]; + +declare namespace execall { + interface Match { + match: string; + sub: string[]; + index: number; + } +} diff --git a/types/execall/tsconfig.json b/types/execall/tsconfig.json new file mode 100644 index 0000000000..70a42a9a18 --- /dev/null +++ b/types/execall/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", + "execall-tests.ts" + ] +} diff --git a/types/execall/tslint.json b/types/execall/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/execall/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/exif/exif-tests.ts b/types/exif/exif-tests.ts new file mode 100644 index 0000000000..57d29fc80b --- /dev/null +++ b/types/exif/exif-tests.ts @@ -0,0 +1,18 @@ +import Exif = require('exif'); +const ExifImage = Exif.ExifImage; + +new ExifImage({ image: 'myImage.jpg' }, (error, exifData) => { + if (error) { + console.log(`Error: ${error.message}`); + } else { + console.log(exifData); + } +}); + +Exif('myImage.jpg', (error, exifData, dataPath) => { + if (error) { + console.log(`Error: ${error.message}`); + } else { + console.log(exifData, dataPath); + } +}); diff --git a/types/exif/index.d.ts b/types/exif/index.d.ts new file mode 100644 index 0000000000..78a1859517 --- /dev/null +++ b/types/exif/index.d.ts @@ -0,0 +1,143 @@ +// Type definitions for exif 0.6 +// Project: https://github.com/gomfunkel/node-exif#readme +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Exif { + interface ExifData { + image: { + Copyright?: string; + ExifOffset?: number; + ImageHeight?: number; + ImageWidth?: number; + Make?: string; + Model?: string; + ModifyDate?: string; + Orientation?: number; + ResolutionUnit?: number; + Software?: string; + XResolution?: number; + YCbCrPositioning?: number; + YResolution?: number; + }; + thumbnail: { + Compression?: number; + Orientation?: number; + ResolutionUnit?: number; + ThumbnailLength?: number; + ThumbnailOffset?: number; + XResolution?: number; + YCbCrPositioning?: number; + YResolution?: number; + }; + exif: { + ApertureValue?: number; + BrightnessValue?: number; + ColorSpace?: number; + ComponentsConfiguration?: Buffer; + CompressedBitsPerPixel?: number; + CreateDate?: string; + DateTimeOriginal?: string; + ExifImageHeight?: number; + ExifImageWidth?: number; + ExifVersion?: Buffer; + ExposureCompensation?: number; + ExposureMode?: number; + ExposureProgram?: number; + ExposureTime?: number; + FileSource?: Buffer; + Flash?: number; + FlashpixVersion?: Buffer; + FNumber?: number; + FocalLength?: number; + FocalLengthIn35mmFormat?: number; + FocalPlaneResolutionUnit?: number; + FocalPlaneXResolution?: number; + FocalPlaneYResolution?: number; + ImageUniqueID?: string; + InteropOffset?: number; + ISO?: number; + MakerNote?: Buffer; + MaxApertureValue?: number; + MeteringMode?: number; + SceneCaptureType?: number; + SceneType?: Buffer; + SensingMethod?: number; + ShutterSpeedValue?: number; + UserComment?: Buffer; + WhiteBalance?: number; + }; + gps: { + GPSAltitude?: number; + GPSAltitudeRef?: number; + GPSDateStamp?: string; + GPSLatitude?: number[]; + GPSLatitudeRef?: string; + GPSLongitude?: number[]; + GPSLongitudeRef?: string; + GPSTimeStamp?: number[]; + GPSVersionId?: number[]; + }; + interoperability: { + InteropIndex?: string; + InteropVersion?: Buffer; + }; + makernote: { + AutoBracketing?: number; + BlurWarning?: number; + ExposureWarning?: number; + error?: string; + FlashExposureComp?: number; + FocusMode?: number; + FocusWarning?: number; + FujiFlashMode?: number; + Macro?: number; + Quality?: string; + Sharpness?: number; + SlowSync?: number; + Version?: Buffer; + WhiteBalance?: number; + }; + } + + interface ExifOptions { + agfaMaxEntries?: number; + epsonMaxEntries?: number; + /** node-exif corrects the thumbnail offset in order to have an offset from the start of the buffer/file. */ + fixThumbnailOffset?: boolean; + fujifilmMaxEntries?: number; + ifd0MaxEntries?: number; + ifd1MaxEntries?: number; + /** + * The image to get Exif data from can be either a filesystem path or a Buffer. + * + * If `image` is not specified, the developer must call `loadImage()` to parse the image. + */ + image?: string | Buffer; + /** Specifies the maximum entries to be parsed */ + maxEntries?: number; + maxGpsEntries?: number; + maxInteroperabilityEntries?: number; + noPadding?: boolean; + olympusMaxEntries?: number; + panasonicMaxEntries?: number; + sanyoMaxEntries?: number; + /** An object named "offsets" is added to exifData and contains lot of offsets needed to get thumbnail and other things. */ + tiffOffsets?: number; + } + + type ExifImageCallback = (error: Error | null, data: ExifData) => void; + type ExifCallback = (error: Error | null, data: ExifData, dataPath: string) => void; + + class ExifImage { + constructor(options: ExifOptions | string | Buffer, callback: ExifImageCallback); + constructor(); + loadImage(file: string | Buffer, callback: ExifImageCallback): void; + } +} + +declare function Exif(path: string, callback: Exif.ExifCallback): void; + +export = Exif; diff --git a/types/exif/tsconfig.json b/types/exif/tsconfig.json new file mode 100644 index 0000000000..4c0c12d69a --- /dev/null +++ b/types/exif/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", + "exif-tests.ts" + ] +} diff --git a/types/exif/tslint.json b/types/exif/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/exif/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 481c1b27c4..62a7dcbb91 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -262,13 +262,13 @@ async () => { ); -const barcodeReadCallback = () => {}; +const barCodeScannedCallback = () => {}; () => ( + onBarCodeScanned={barCodeScannedCallback} /> ); () => ( diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 171dbc52b6..1b24c3151c 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -26,7 +26,7 @@ import { Component, ComponentClass, ComponentType, Ref } from 'react'; import { ImageRequireSource, ImageURISource, LinkingStatic as ReactNativeLinkingStatic, StyleProp, ViewProps, ViewStyle } from 'react-native'; export type Axis = number; -export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type BarCodeScannedCallback = (params: { type: string; data: string; }) => void; export type Md5 = string; export type Orientation = 'portrait' | 'landscape'; export type RequireSource = ImageRequireSource; @@ -711,7 +711,7 @@ export interface BarCodeScannerProps extends ViewProps { type?: 'front' | 'back'; torchMode?: 'on' | 'off'; barCodeTypes?: string[]; - onBarCodeRead?: BarCodeReadCallback; + onBarCodeScanned?: BarCodeScannedCallback; } export class BarCodeScanner extends Component { @@ -805,7 +805,7 @@ export interface CameraProps extends ViewProps { flashMode?: string | number; /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ focusDepth?: number; - onBarCodeRead?: BarCodeReadCallback; + onBarCodeScanned?: BarCodeScannedCallback; onCameraReady?: () => void; onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; onMountError?: () => void; diff --git a/types/express-http-proxy/express-http-proxy-tests.ts b/types/express-http-proxy/express-http-proxy-tests.ts index 16e03cc974..56156369cc 100644 --- a/types/express-http-proxy/express-http-proxy-tests.ts +++ b/types/express-http-proxy/express-http-proxy-tests.ts @@ -16,5 +16,13 @@ proxy('www.google.com', { console.log(proxyReqOpts.headers, proxyReqOpts.method); console.log(srcReq.url, srcReq.cookies); return proxyReqOpts; + }, + userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) { + console.log(userReq.url, userRes.statusCode); + console.log(proxyReq.url, proxyRes.statusCode); + if (headers["content-type"] === "image/png") { + headers["x-custom-header"] = "additional-info"; + } + return headers; } }); diff --git a/types/express-http-proxy/index.d.ts b/types/express-http-proxy/index.d.ts index 031be01485..3a74bef6db 100644 --- a/types/express-http-proxy/index.d.ts +++ b/types/express-http-proxy/index.d.ts @@ -1,15 +1,18 @@ // Type definitions for express-http-proxy 1.5 // Project: https://github.com/villadora/express-http-proxy#readme -// Definitions by: ulrichb +// Definitions by: ulrichb +// Daniel Schopf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import { RequestHandler, Request } from "express"; -import { RequestOptions } from "http"; +import { RequestOptions, IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; +import { Response } from "express-serve-static-core"; interface ProxyOptions { proxyReqPathResolver?: (req: Request) => string; proxyReqOptDecorator?: (proxyReqOpts: RequestOptions, srcReq: Request) => RequestOptions; + userResHeaderDecorator?: (headers: IncomingHttpHeaders, userReq: Request, userRes: Response, proxyReq: Request, proxyRes: Response) => OutgoingHttpHeaders; } declare function proxy(host: string, options?: ProxyOptions): RequestHandler; diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index 96c4c233c2..773a1e065b 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -44,6 +44,7 @@ export type RequestHandlerParams = RequestHandler | ErrorRequestHandler | Array< export interface IRouterMatcher { (path: PathParams, ...handlers: RequestHandler[]): T; (path: PathParams, ...handlers: RequestHandlerParams[]): T; + (path: PathParams, subApplication: Application): T; } export interface IRouterHandler { diff --git a/types/express/express-tests.ts b/types/express/express-tests.ts index 07bf2fc5c3..37cf543df5 100644 --- a/types/express/express-tests.ts +++ b/types/express/express-tests.ts @@ -138,6 +138,9 @@ namespace express_tests { res.req; }); + // Test mounting sub-apps + app.use('/sub-app', express()); + // Test on mount event app.on('mount', (parent) => true); diff --git a/types/express/index.d.ts b/types/express/index.d.ts index 81821ca98c..ddc4509805 100644 --- a/types/express/index.d.ts +++ b/types/express/index.d.ts @@ -30,6 +30,13 @@ declare namespace e { */ var json: typeof bodyParser.json; + /** + * These are the exposed prototypes. + */ + var application: Application; + var request: Request; + var response: Response; + /** * This is a built-in middleware function in Express. It serves static files and is based on serve-static. */ diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 60ec11648f..d3c7f70a90 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -1801,10 +1801,12 @@ export class Image { initialize(element?: string | HTMLImageElement, options?: IImageOptions): void; /** - * Applies filters assigned to this image (from "filters" array) - * @param callback Callback is invoked when all filters have been applied and new image is generated + * Applies filters assigned to this image (from "filters" array) or from filter param + * @param {Array} filters to be applied + * @return {thisArg} return the fabric.Image object + * @chainable */ - applyFilters(callback: Function): void; + applyFilters(filters?: IBaseFilter[]): Image; /** * Returns a clone of an instance * @param callback Callback is invoked with a clone as a first argument @@ -3717,17 +3719,29 @@ interface IAllFilters { */ new(options?: any): IBaseFilter; }; - Blend: { + BlendColor: { /** * Constructor * @param [options] Options object */ - new(options?: { color?: string; mode?: string; alpha?: number; image?: Image }): IBlendFilter; + new(options?: { color?: string; mode?: string; alpha?: number; }): IBlendColorFilter; /** * Returns filter instance from an object representation * @param object Object to create an instance from */ - fromObject(object: any): IBlendFilter + fromObject(object: any): IBlendColorFilter + }; + BlendImage: { + /** + * Constructor + * @param [options] Options object + */ + new(options?: { image?: Image; mode?: string; alpha?: number; }): IBlendImageFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IBlendImageFilter }; Brightness: { new(options?: { @@ -3910,7 +3924,14 @@ interface IBaseFilter { */ toJSON(): string; } -interface IBlendFilter extends IBaseFilter { +interface IBlendColorFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IBlendImageFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to diff --git a/types/facebook-js-sdk/facebook-js-sdk-tests.ts b/types/facebook-js-sdk/facebook-js-sdk-tests.ts index 46b9f331f5..db8b13686e 100644 --- a/types/facebook-js-sdk/facebook-js-sdk-tests.ts +++ b/types/facebook-js-sdk/facebook-js-sdk-tests.ts @@ -22,6 +22,14 @@ FB.getLoginStatus(function(response: fb.StatusResponse) { const authResponse: fb.AuthResponse = FB.getAuthResponse(); console.log(authResponse.accessToken); +FB.login(); + +FB.login(function(response: fb.StatusResponse) { + console.log(response); + console.log(response.status); + console.log(response.authResponse.accessToken); +}); + FB.login(function(response: fb.StatusResponse) { console.log(response); console.log(response.status); diff --git a/types/facebook-js-sdk/index.d.ts b/types/facebook-js-sdk/index.d.ts index 86ca521c88..c4f3b78c31 100644 --- a/types/facebook-js-sdk/index.d.ts +++ b/types/facebook-js-sdk/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for the Facebook Javascript SDK 3.1 +// Type definitions for the Facebook Javascript SDK 3.2 // Project: https://developers.facebook.com/docs/javascript // Definitions by: Amrit Kahlon // Mahmoud Zohdi @@ -50,7 +50,7 @@ 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 @@ -61,12 +61,12 @@ declare namespace facebook { * * @param options optional ILoginOption to add params such as scope. */ - login(options: LoginOptions): void; + 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 + * @param callback optional function to handle the response */ logout(callback?: (response: StatusResponse) => void): void; diff --git a/types/faker/index.d.ts b/types/faker/index.d.ts index a9d044cfcb..55c20ce235 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -117,7 +117,7 @@ declare namespace Faker { image: { image(): string; avatar(): string; - imageUrl(width?: number, height?: number, category?: string): string; + imageUrl(width?: number, height?: number, category?: string, randomize?: boolean, https?: boolean): string; abstract(width?: number, height?: number): string; animals(width?: number, height?: number): string; business(width?: number, height?: number): string; diff --git a/types/feathersjs__authentication-jwt/index.d.ts b/types/feathersjs__authentication-jwt/index.d.ts index 7a555071d9..16d79bb885 100644 --- a/types/feathersjs__authentication-jwt/index.d.ts +++ b/types/feathersjs__authentication-jwt/index.d.ts @@ -52,9 +52,9 @@ export class Verifier { verify(req: Request, payload: any, done: (error: any, user?: any, info?: any) => void): void; } -export type JwtFromRequestFunction = (req: Request) => string; +export type JwtFromRequestFunction = (req: Request) => string | null; -export const ExtractJWT: { +export const ExtractJwt: { fromHeader(header_name: string): JwtFromRequestFunction; fromBodyField(field_name: string): JwtFromRequestFunction; fromUrlQueryParameter(param_name: string): JwtFromRequestFunction; diff --git a/types/feathersjs__rest-client/index.d.ts b/types/feathersjs__rest-client/index.d.ts index 22e5f1084b..65fdc93707 100644 --- a/types/feathersjs__rest-client/index.d.ts +++ b/types/feathersjs__rest-client/index.d.ts @@ -5,7 +5,7 @@ // todo: get rid of all the anys -export default function feathersRestClient(base: string): Transport; +export default function feathersRestClient(base?: string): Transport; export interface HandlerResult extends Function { /** diff --git a/types/fetch-mock/fetch-mock-tests.ts b/types/fetch-mock/fetch-mock-tests.ts index a5dc13c348..50b4d79252 100644 --- a/types/fetch-mock/fetch-mock-tests.ts +++ b/types/fetch-mock/fetch-mock-tests.ts @@ -1,4 +1,4 @@ -import * as fetchMock from "fetch-mock"; +import fetchMock = require('fetch-mock'); fetchMock.mock("http://test.com", 200); fetchMock.mock("http://test.com", 200, { @@ -141,3 +141,16 @@ sandbox.get("http://test.com", { const response: fetchMock.MockResponseObject = { throws: new Error('error'), }; + +fetchMock.config.sendAsJson = true; +fetchMock.config.includeContentLength = true; +fetchMock.config.fallbackToNetwork = true; +fetchMock.config.fallbackToNetwork = 'always'; +fetchMock.config.overwriteRoutes = true; +fetchMock.config.overwriteRoutes = undefined; +fetchMock.config.warnOnFallback = true; +fetchMock.config.Promise = Promise; +fetchMock.config.fetch = (): Promise => new Promise(() => { }); +fetchMock.config.Headers = Headers; +fetchMock.config.Request = Request; +fetchMock.config.Response = Response; diff --git a/types/fetch-mock/index.d.ts b/types/fetch-mock/index.d.ts index a872a824d9..c9984dea89 100644 --- a/types/fetch-mock/index.d.ts +++ b/types/fetch-mock/index.d.ts @@ -523,14 +523,83 @@ declare namespace fetchMock { options?: InspectionOptions, ): MockOptions | undefined; - /** - * Set some global config options, which include - * sendAsJson [default `true`] - by default fetchMock will - * convert objects to JSON before sending. This is overrideable - * for each call but for some scenarios, e.g. when dealing with a - * lot of array buffers, it can be useful to default to `false` - */ - configure(opts: {}): void; + config: { + /** + * Convert objects into JSON before delivering as stub reponses. + * Can be useful to set to false globally if e.g. dealing with a + * lot of array buffers. If true, will also add + * content-type: application/json header. + * @default true + */ + sendAsJson?: boolean; + + /** + * Automatically sets a content-length header on each response. + * @default true + */ + includeContentLength?: boolean; + + /** + * - true: Unhandled calls fall through to the network + * - false: Unhandled calls throw an error + * - 'always': All calls fall through to the network, effectively + * disabling fetch-mock. + * @default false + */ + fallbackToNetwork?: boolean | 'always'; + + /** + * Determines behaviour if a new route has the same name (or + * inferred name) as an existing one + * - undefined: An error will be throw when routes clash + * - true: Overwrites the existing route + * - false: Appends the new route to the list of routes + * @default undefined + */ + overwriteRoutes?: boolean; + + /** + * Print a warning if any call is caught by a fallback handler (set + * using the fallbackToNetwork option or catch()) + * @default true + */ + warnOnFallback?: boolean; + + /** + * Reference to the Promise constructor of a custom Promise + * implementation. + */ + Promise?: new (executor: ( + resolve: () => void, + reject: () => void, + ) => void) => Promise; + + /** + * Reference to a custom fetch implementation. + */ + fetch?: ( + input?: string | Request, + init?: RequestInit, + ) => Promise; + + /** + * Reference to the Headers constructor of a custom fetch + * implementation. + */ + Headers?: new () => Headers; + + /** + * Reference to the Request constructor of a custom fetch + * implementation. + */ + Request?: new (input: string | Request, init?: RequestInit) => Request; + + /** + * Reference to the Response constructor of a custom fetch + * implementation. + */ + Response?: new () => Response; + }; } interface FetchMockSandbox extends FetchMockStatic { diff --git a/types/filesize/index.d.ts b/types/filesize/index.d.ts index 511e2373af..e8905d906d 100644 --- a/types/filesize/index.d.ts +++ b/types/filesize/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for filesize 3.6 +// Type definitions for filesize 4.0 // Project: https://github.com/avoidwork/filesize.js // Definitions by: Giedrius Grabauskas // Renaud Chaput +// Roman Nuritdinov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var fileSize: Filesize.Filesize; @@ -80,11 +81,6 @@ declare namespace Filesize { * Dictionary of SI/JEDEC symbols to replace for localization, defaults to english if no match is found */ symbols?: SiJedec; - /** - * Dictionary of SI/JEDEC symbols to replace for localization, defaults to english if no match is found - * @deprecated: use `symbols` - */ - suffixes?: SiJedec; /** * Enables unix style human readable output, e.g ls -lh, default is false */ diff --git a/types/filter-console/filter-console-tests.ts b/types/filter-console/filter-console-tests.ts new file mode 100644 index 0000000000..18bb766d32 --- /dev/null +++ b/types/filter-console/filter-console-tests.ts @@ -0,0 +1,8 @@ +import filterConsole = require('filter-console'); + +const disableFilter = filterConsole(['🐼']); +disableFilter; // $ExpectType () => void +filterConsole([/🐼/]); +filterConsole([input => input === '🐼']); + +disableFilter(); diff --git a/types/filter-console/index.d.ts b/types/filter-console/index.d.ts new file mode 100644 index 0000000000..58ee621211 --- /dev/null +++ b/types/filter-console/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for filter-console 0.1 +// Project: https://github.com/sindresorhus/filter-console#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export = filterConsole; + +/** + * Filter out unwanted `console.log()` output. + * Can be useful when you don't control the output, for example, filtering out PropType warnings from a + * third-party React component. + * + * @param excludePatterns Console output that matches any of the given patterns are filtered from being logged. + * The patterns are matched against what would be logged and not the `console` method input arguments directly. + * Meaning an exclude pattern of `'foo bar'` will match `console.log('foo %s', 'bar')`. + * @returns A function, which when called, disables the filter. + */ +declare function filterConsole( + excludePatterns: Array boolean)>, + options?: filterConsole.Options +): () => void; + +declare namespace filterConsole { + interface Options { + /** + * Console methods to filter. + * @default ['log', 'debug', 'info', 'warn', 'error'] + */ + methods?: Array<'log' | 'debug' | 'info' | 'warn' | 'error'>; + + /** + * Use a custom `console` object. Can be useful for testing or mocking. + */ + console?: Console; + } + + type Console = Record< + 'log' | 'debug' | 'info' | 'warn' | 'error', + (message?: any, ...optionalParams: any[]) => void + >; +} diff --git a/types/filter-console/tsconfig.json b/types/filter-console/tsconfig.json new file mode 100644 index 0000000000..34ed881aab --- /dev/null +++ b/types/filter-console/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", + "filter-console-tests.ts" + ] +} diff --git a/types/filter-console/tslint.json b/types/filter-console/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/filter-console/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/first-run/first-run-tests.ts b/types/first-run/first-run-tests.ts new file mode 100644 index 0000000000..5451c7c88c --- /dev/null +++ b/types/first-run/first-run-tests.ts @@ -0,0 +1,6 @@ +import firstRun = require('first-run'); + +firstRun(); // $ExpectType boolean +firstRun({ name: 'foo' }); // $ExpectType boolean + +firstRun.clear(); diff --git a/types/first-run/index.d.ts b/types/first-run/index.d.ts new file mode 100644 index 0000000000..dc92053d03 --- /dev/null +++ b/types/first-run/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for first-run 1.2 +// Project: https://github.com/sindresorhus/first-run +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = firstRun; + +/** + * Check if it's the first time the process is run. + */ +declare function firstRun(options?: firstRun.Options): boolean; + +declare namespace firstRun { + /** + * Clear the state. + */ + function clear(): void; + + interface Options { + /** + * The name used to identify it. + * @default name field in your package.json + */ + name: string; + } +} diff --git a/types/first-run/tsconfig.json b/types/first-run/tsconfig.json new file mode 100644 index 0000000000..6a4ce007ab --- /dev/null +++ b/types/first-run/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", + "first-run-tests.ts" + ] +} diff --git a/types/first-run/tslint.json b/types/first-run/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/first-run/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fkill/fkill-tests.ts b/types/fkill/fkill-tests.ts new file mode 100644 index 0000000000..6e2b380a16 --- /dev/null +++ b/types/fkill/fkill-tests.ts @@ -0,0 +1,5 @@ +import fkill = require('fkill'); + +fkill(1337); // $ExpectType Promise +fkill('Safari'); // $ExpectType Promise +fkill([1337, 'Safari', ':8080']); // $ExpectType Promise diff --git a/types/fkill/index.d.ts b/types/fkill/index.d.ts new file mode 100644 index 0000000000..4b6663a10c --- /dev/null +++ b/types/fkill/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for fkill 5.3 +// Project: https://github.com/sindresorhus/fkill#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = fkill; + +/** + * Fabulously kill processes. Cross-platform. + * + * @param input One or more process IDs/names/ports to kill. + * To kill a port, prefix it with a colon. For example: `:8080`. + */ +declare function fkill( + input: number | string | Array, + options?: fkill.Options +): Promise; + +declare namespace fkill { + interface Options { + /** + * Force kill the process. + * @default false + */ + force?: boolean; + + /** + * Kill all child processes along with the parent process. *(Windows only)* + * @default true + */ + tree?: boolean; + + /** + * Ignore capitalization when killing a process. + * Note that the case is always ignored on Windows. + * @default false + */ + ignoreCase?: boolean; + } +} diff --git a/types/fkill/tsconfig.json b/types/fkill/tsconfig.json new file mode 100644 index 0000000000..2e36e29395 --- /dev/null +++ b/types/fkill/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", + "fkill-tests.ts" + ] +} diff --git a/types/fkill/tslint.json b/types/fkill/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fkill/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/forever-monitor/index.d.ts b/types/forever-monitor/index.d.ts index c9de58e7cc..cc666b65c0 100644 --- a/types/forever-monitor/index.d.ts +++ b/types/forever-monitor/index.d.ts @@ -25,7 +25,7 @@ export interface Options { sourceDir?: string; watch?: boolean; watchIgnoreDotFiles?: boolean; - watchIgnorePatters?: string[]; + watchIgnorePatterns?: string[]; watchDirectory?: string; spawnWith?: SpawnWith; env?: NodeJS.ProcessEnv; diff --git a/types/gapi.client.drive/index.d.ts b/types/gapi.client.drive/index.d.ts index 1b2a939a7d..ca28f228e7 100644 --- a/types/gapi.client.drive/index.d.ts +++ b/types/gapi.client.drive/index.d.ts @@ -1042,6 +1042,8 @@ declare namespace gapi.client { }): Request; /** Creates a new file. */ create(request: { + /** Resource Parameter for folder creation */ + resource?: any; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ diff --git a/types/geojson/geojson-tests.ts b/types/geojson/geojson-tests.ts index 4ea0f57a6f..82787c8c36 100644 --- a/types/geojson/geojson-tests.ts +++ b/types/geojson/geojson-tests.ts @@ -1,10 +1,10 @@ import { - BBox, Feature, FeatureCollection, GeometryCollection, LineString, - MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeometryObject + MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeoJsonGeometryTypes, + GeoJsonTypes, GeometryObject } from "geojson"; -let featureCollection: FeatureCollection = { +let featureCollection: FeatureCollection = { type: "FeatureCollection", features: [ { @@ -53,6 +53,17 @@ let featureCollection: FeatureCollection = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], @@ -65,6 +76,11 @@ const featureWithPolygon: Feature = { properties: null }; +featureWithPolygon.type; // $ExpectType "Feature" +featureWithPolygon.geometry; // $ExpectType Polygon +featureWithPolygon.geometry.type; // $ExpectType "Polygon" +featureWithPolygon.geometry.coordinates; // $ExpectType number[][][] + const point: Point = { type: "Point", coordinates: [100.0, 0.0] @@ -135,6 +151,8 @@ let feature: Feature = { properties: null }; +feature.properties; // $ExpectType GeoJsonProperties + feature = { type: "Feature", geometry: polygon, @@ -275,12 +293,16 @@ const featureGeometryNull: Feature = { geometry: null }; +featureGeometryNull.properties.foo; // $ExpectType "bar" | "baz" + const featureNoNull: Feature = { type: "Feature", properties: testProps, geometry: point }; +featureNoNull.geometry.type; // $ExpectType "Point" + const collectionAllNull: FeatureCollection = { type: "FeatureCollection", features: [featureAllNull], @@ -301,6 +323,8 @@ const collectionGeometryMaybeNull: FeatureCollection features: [featureGeometryNull, featureNoNull], }; +collectionGeometryMaybeNull.features[0].geometry; // $ExpectType Point | null + const collectionNoNull: FeatureCollection = { type: "FeatureCollection", features: [featureNoNull], @@ -311,6 +335,9 @@ const collectionDefault: FeatureCollection = { features: [] }; +collectionDefault.features[0].geometry; // $ExpectType Geometry +collectionDefault.features[0].properties!.foo; // $ExpectType any + isNull = featureAllNull.geometry; isPoint = featurePropertyNull.geometry; isNull = featureAllNull.properties; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index 93f66d3f27..db8074e242 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -4,6 +4,7 @@ // Arne Schubert // Jeff Jacobson // Ilia Choly +// Dan Vanderkam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -16,14 +17,13 @@ export as namespace GeoJSON; * The valid values for the "type" property of GeoJSON geometry objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ -export type GeoJsonGeometryTypes = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | - "MultiPolygon" | "GeometryCollection"; +export type GeoJsonGeometryTypes = Geometry['type']; /** * The value values for the "type" property of GeoJSON Objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ -export type GeoJsonTypes = "FeatureCollection" | "Feature" | GeoJsonGeometryTypes; +export type GeoJsonTypes = GeoJSON['type']; /** * Bounding box @@ -58,6 +58,10 @@ export interface GeoJsonObject { type: GeoJsonTypes; /** * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. + * The value of the bbox member is an array of length 2*n where n is the number of dimensions + * represented in the contained geometries, with all axes of the most southwesterly point + * followed by all axes of the more northeasterly point. + * The axes order of a bbox follows the axes order of geometries. * https://tools.ietf.org/html/rfc7946#section-5 */ bbox?: BBox; @@ -69,24 +73,17 @@ export interface GeoJsonObject { export type GeoJSON = Geometry | Feature | FeatureCollection; /** - * A geometry object. - * https://tools.ietf.org/html/rfc7946#section-3 - */ -export interface GeometryObject extends GeoJsonObject { - type: GeoJsonGeometryTypes; -} - -/** - * Union of geometry objects. + * Geometry object. * https://tools.ietf.org/html/rfc7946#section-3 */ export type Geometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon | GeometryCollection; +export type GeometryObject = Geometry; /** * Point geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.2 */ -export interface Point extends GeometryObject { +export interface Point extends GeoJsonObject { type: "Point"; coordinates: Position; } @@ -95,7 +92,7 @@ export interface Point extends GeometryObject { * MultiPoint geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.3 */ -export interface MultiPoint extends GeometryObject { +export interface MultiPoint extends GeoJsonObject { type: "MultiPoint"; coordinates: Position[]; } @@ -104,7 +101,7 @@ export interface MultiPoint extends GeometryObject { * LineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.4 */ -export interface LineString extends GeometryObject { +export interface LineString extends GeoJsonObject { type: "LineString"; coordinates: Position[]; } @@ -113,7 +110,7 @@ export interface LineString extends GeometryObject { * MultiLineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.5 */ -export interface MultiLineString extends GeometryObject { +export interface MultiLineString extends GeoJsonObject { type: "MultiLineString"; coordinates: Position[][]; } @@ -122,7 +119,7 @@ export interface MultiLineString extends GeometryObject { * Polygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.6 */ -export interface Polygon extends GeometryObject { +export interface Polygon extends GeoJsonObject { type: "Polygon"; coordinates: Position[][]; } @@ -131,7 +128,7 @@ export interface Polygon extends GeometryObject { * MultiPolygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.7 */ -export interface MultiPolygon extends GeometryObject { +export interface MultiPolygon extends GeoJsonObject { type: "MultiPolygon"; coordinates: Position[][][]; } @@ -140,7 +137,7 @@ export interface MultiPolygon extends GeometryObject { * Geometry Collection * https://tools.ietf.org/html/rfc7946#section-3.1.8 */ -export interface GeometryCollection extends GeometryObject { +export interface GeometryCollection extends GeoJsonObject { type: "GeometryCollection"; geometries: Geometry[]; } @@ -151,7 +148,7 @@ export type GeoJsonProperties = { [name: string]: any; } | null; * A feature object which contains a geometry and associated properties. * https://tools.ietf.org/html/rfc7946#section-3.2 */ -export interface Feature extends GeoJsonObject { +export interface Feature extends GeoJsonObject { type: "Feature"; /** * The feature's geometry @@ -172,7 +169,7 @@ export interface Feature extends GeoJsonObject { +export interface FeatureCollection extends GeoJsonObject { type: "FeatureCollection"; features: Array>; } diff --git a/types/google__maps/index.d.ts b/types/google__maps/index.d.ts index 4759d412dd..57cbe437b2 100644 --- a/types/google__maps/index.d.ts +++ b/types/google__maps/index.d.ts @@ -907,7 +907,9 @@ export interface DirectionsRoute { * contains a single `points` object that holds an encoded polyline representation of the route. * This polyline is an approximate (smoothed) path of the resulting directions. */ - overview_polyline: string; + overview_polyline: { + points: string; + }; /** contains the viewport bounding box of the `overview_polyline`. */ bounds: LatLngBounds; /** contains the copyrights text to be displayed for this route. You must handle and display this information yourself. */ diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index d80d0aadcf..afaac89ba4 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -265,10 +265,28 @@ 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() }); + +// Test retry options. got('http://todomvc.com', { retry: 2 }); -got('http://todomvc.com', { retry: { retries: 2, methods: ['GET'], statusCodes: [408, 504], maxRetryAfter: 1 } }); +got('http://todomvc.com', { + retry: { + retries: 2, + methods: ['GET'], + statusCodes: [408, 504], + maxRetryAfter: 1, + errorCodes: ['ETIMEDOUT'] + } +}); +// Test custom retry error code. See https://github.com/sindresorhus/got/blob/9f3a09948ff80057b12af0af60846cc5b8f0372d/test/retry.js#L155 +got('http://todomvc.com', { + retry: { + retries: 1, + methods: ['GET'], + errorCodes: ['OH_SNAP'] + } +}); + got('http://todomvc.com', { throwHttpErrors: false }); -got('http://todomvc.com', { hooks: { beforeRequest: [ () => 'foo']} }); // Test timeout options. got('http://todomvc.com', {timeout: 1}); @@ -288,6 +306,15 @@ got('http://todomvc.com', { got('http://todomvc.com', {timeout: 1}).catch((err) => err instanceof got.TimeoutError); // Test hooks. +got('example.com', { + hooks: { + beforeRequest: [ + options => { + options.headers!['x-foo'] = 'bar'; + } + ] + } +}); got('example.com', { hooks: { beforeRedirect: [ @@ -339,6 +366,11 @@ got('example.com', { got('example.com', { hooks: { + beforeRequest: [ + async () => { + await doSomethingAsync(); + } + ], beforeRedirect: [ async () => { await doSomethingAsync(); diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 09b451f4bb..0c847d6489 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for got 9.3 +// Type definitions for got 9.4 // Project: https://github.com/sindresorhus/got#readme // Definitions by: BendingBender // Linus Unnebäck @@ -226,6 +226,10 @@ declare namespace got { methods?: Array<'GET' | 'PUT' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE'>; statusCodes?: Array<408 | 413 | 429 | 500 | 502 | 503 | 504>; maxRetryAfter?: number; + /** + * Allowed error codes. + */ + errorCodes?: string[]; } interface AgentOptions { diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index 1df7c85690..97c16f305c 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -342,15 +342,15 @@ export interface GraphQLScalarTypeConfig { * }); * */ -export class GraphQLObjectType { +export class GraphQLObjectType { name: string; description: Maybe; astNode: Maybe; extensionASTNodes: Maybe>; - isTypeOf: Maybe>; + isTypeOf: Maybe>; - constructor(config: GraphQLObjectTypeConfig); - getFields(): GraphQLFieldMap; + constructor(config: GraphQLObjectTypeConfig); + getFields(): GraphQLFieldMap; getInterfaces(): GraphQLInterfaceType[]; toString(): string; toJSON(): string; @@ -371,7 +371,7 @@ export type GraphQLTypeResolver = ( value: TSource, context: TContext, info: GraphQLResolveInfo -) => MaybePromise>; +) => MaybePromise | string>>; export type GraphQLIsTypeOfFn = ( source: TSource, diff --git a/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts b/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts index 6a31efb820..38398d9830 100644 --- a/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts +++ b/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts @@ -1,3 +1,8 @@ -import invisibles, { hardBreak, paragraph, space } from 'guardian__prosemirror-invisibles'; +import { Node } from 'prosemirror-model'; +import { Plugin } from 'prosemirror-state'; -const plugin = invisibles([hardBreak, paragraph, space]); +import invisibles, { hardBreak, paragraph, space, Builder } from 'guardian__prosemirror-invisibles'; + +const plugin1: Plugin = invisibles([hardBreak((node: Node) => true), paragraph(), space((char: string) => false)]); + +const plugin2: Plugin = invisibles([hardBreak(), paragraph((node: Node) => false), space()]); diff --git a/types/guardian__prosemirror-invisibles/index.d.ts b/types/guardian__prosemirror-invisibles/index.d.ts index b2e2434662..f3453cd6ec 100644 --- a/types/guardian__prosemirror-invisibles/index.d.ts +++ b/types/guardian__prosemirror-invisibles/index.d.ts @@ -1,17 +1,25 @@ -// Type definitions for @guardian/prosemirror-invisibles 0.1 +// Type definitions for @guardian/prosemirror-invisibles 1.0 // Project: https://github.com/guardian/prosemirror-invisibles // Definitions by: Daniil Dotsev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Node } from 'prosemirror-model'; -import { DecorationSet } from "prosemirror-view"; +import { Decoration, DecorationSet } from "prosemirror-view"; import { Plugin } from 'prosemirror-state'; export type Builder = (from: number, to: number, doc: Node, decos: DecorationSet) => DecorationSet; +export interface TextBetweenPosition { + pos: number; + text: string; +} + export default function(builders: Builder[]): Plugin; -export const hardBreak: Builder; -export const paragraph: Builder; -export const space: Builder; +export function hardBreak(predicate?: (node: Node) => boolean): Builder; +export function paragraph(predicate?: (node: Node) => boolean): Builder; +export function space(predicate?: (char: string) => boolean): Builder; + +export function createDeco(pos: number, type: string): Decoration; +export function textBetween(from: number, to: number, doc: Node): TextBetweenPosition[]; diff --git a/types/h2o2/h2o2-tests.ts b/types/h2o2/h2o2-tests.ts index 9d0a590fa8..9da2899258 100644 --- a/types/h2o2/h2o2-tests.ts +++ b/types/h2o2/h2o2-tests.ts @@ -140,6 +140,18 @@ const badProtocolDemo: hapi.ServerRoute = { } }; +const replyViaToolkit: hapi.ServerRoute = { + method: 'GET', + path: '/', + async handler(req, h): Promise { + return h.proxy({ + host: '10.33.33.1', + port: '443', + protocol: 'https' + }); + } +}; + if (!module.parent) { main().then(() => console.log('done'), err => console.error(err.stack)); } diff --git a/types/h2o2/index.d.ts b/types/h2o2/index.d.ts index b6e5145eb6..58be5eb271 100644 --- a/types/h2o2/index.d.ts +++ b/types/h2o2/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for h2o2 8.1 // Project: https://github.com/hapijs/h2o2 -// Definitions by: Jason Swearingen , AJP +// Definitions by: Jason Swearingen , AJP , Garth Kidd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -83,13 +83,17 @@ declare namespace h2o2 { declare module 'hapi' { interface HandlerDecorations { - /** Proxies the request to an upstream endpoint */ + /** + * Proxies the request to an upstream endpoint. + */ proxy?: h2o2.ProxyHandlerOptions; } interface ResponseToolkit { - /** Proxies the request to an upstream endpoint */ - proxy(options: h2o2.ProxyHandlerOptions): void; + /** + * Proxies the request to an upstream endpoint. `async`, so you'll need to `await` the `ResponseObject` to work on it before returning it. + */ + proxy(options: h2o2.ProxyHandlerOptions): Promise; } } diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 65ce60be85..f66ae5a8ea 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi 17.8 +// Type definitions for hapi 18.0 // Project: https://github.com/hapijs/hapi // Definitions by: Rafael Souza Fijalkowski // Justin Simms @@ -29,9 +29,9 @@ import * as zlib from 'zlib'; import { MimosOptions } from 'mimos'; import { SealOptions, SealOptionsSub } from 'iron'; -import { AnySchema, ValidationOptions } from 'joi'; +import { ValidationOptions, SchemaMap, Schema } from 'joi'; import Podium = require('podium'); -import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy } from 'catbox'; +import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy, ClientApi, ClientOptions } from 'catbox'; /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -318,6 +318,8 @@ export interface RequestInfo { remotePort: string; /** request response timestamp (0 is not responded yet). */ responded: number; + /** request processing completion timestamp (0 is still processing). */ + completed: number; } /** @@ -503,9 +505,10 @@ export interface Request extends Podium { /** * Access: read / write (see limitations below). * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to - * override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). + * override with a different response. + * In case of an aborted request the status code will be set to `disconnectStatusCode`. */ - response: ResponseObject | Boom | null; + response: ResponseObject | Boom; /** * Same as pre but represented as the response object created by the pre method. @@ -513,10 +516,9 @@ export interface Request extends Podium { readonly preResponses: Util.Dictionary; /** - * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query - * attribute as an unparsed string). + * By default the object outputted from node's URL parse() method. */ - readonly query: RequestQuery | string; + readonly query: RequestQuery; /** * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. @@ -549,7 +551,7 @@ export interface Request extends Podium { /** * The parsed request URI. */ - readonly url: url.Url; + readonly url: url.URL; /** * Returns `true` when the request is active and processing should continue and `false` when the @@ -599,7 +601,7 @@ export interface Request extends Podium { * @return void * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) */ - setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; + setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; } /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1436,14 +1438,19 @@ export interface RouteOptionsPreObject { failAction?: Lifecycle.FailAction; } -export interface ValidationObject { - [key: string]: AnySchema; -} +export type ValidationObject = SchemaMap; +/** + * * true - any query parameter value allowed (no validation performed). false - no parameter value allowed. + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.* object containing the request parameters. + * * * options - options. + */ export type RouteOptionsResponseSchema = boolean | ValidationObject - | AnySchema + | Schema | ((value: object | Buffer | string, options: ValidationOptions) => Promise); /** @@ -1517,6 +1524,16 @@ export interface RouteOptionsResponse { * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) */ status?: Util.Dictionary; + + /** + * The default HTTP status code used to set a response error when the request is closed or aborted before the + * response is fully transmitted. + * Value can be any integer greater or equal to 400. + * The default value 499 is based on the non-standard nginx "CLIENT CLOSED REQUEST" error. + * The value is only used for logging as the request has already ended. + * @default 499 + */ + disconnectStatusCode?: number; } /** @@ -1630,21 +1647,15 @@ export interface RouteOptionsValidate { failAction?: Lifecycle.FailAction; /** - * Default value: true (no validation). * Validation rules for incoming request headers: - * * true - any headers allowed (no validation performed). - * * a joi validation object. - * * a validation function using the signature async function(value, options) where: - * * * value - the request.headers object containing the request headers. - * * * options - options. - * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error + * * If a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error * is thrown, the error is handled according to failAction. Note that all header field names must be in lowercase to match the headers normalized by node. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) + * @default true */ headers?: RouteOptionsResponseSchema; /** - * Default value: none. * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as @@ -1653,11 +1664,11 @@ export interface RouteOptionsValidate { * will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the * individual route settings override the routes defaults (the rules are not merged). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + * @default true */ options?: ValidationOptions | object; /** - * Default value: true (no validation). * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: * * true - any path parameter value allowed (no validation performed). * * a joi validation object. @@ -1667,39 +1678,37 @@ export interface RouteOptionsValidate { * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an * error is thrown, the error is handled according to failAction. Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + * @default true */ params?: RouteOptionsResponseSchema; /** - * Default value: true (no validation). * Validation rules for incoming request payload (request body), where: - * * true - any payload allowed (no validation performed). false - no payload allowed. - * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by - * setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). - * * a validation function using the signature async function(value, options) where: - * * * value - the request.query object containing the request query parameters. - * * * options - options. - * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is + * * If a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is * thrown, the error is handled according to failAction. Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well * as the significant performance cost of validating large amounts of data. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) + * @default true */ payload?: RouteOptionsResponseSchema; /** - * Default value: true (no validation). * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in * request.query prior to validation. Where: - * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. - * * a joi validation object. - * * a validation function using the signature async function(value, options) where: - * * * value - the request.query object containing the request query parameters. - * * * options - options. - * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error + * * If a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. + * If an error * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) + * @default true */ query?: RouteOptionsResponseSchema; + + /** + * Validation rules for incoming cookies. + * The cookie header is parsed and decoded into the request.state prior to validation. + * @default true + */ + state?: RouteOptionsResponseSchema; } /** @@ -2125,13 +2134,13 @@ export interface ServerAuth { * Tests a request against an authentication strategy where: * @param strategy - the strategy name registered with server.auth.strategy(). * @param request - the request object. - * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. + * @return an object containing the authentication credentials and artifacts if authentication was successful, otherwise throws an error. * Note that the test() method does not take into account the route authentication configuration. It also does not * perform payload authentication. It is limited to the basic strategy authentication execution. It does not * include verifying scope, entity, or other route properties. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) */ - test(strategy: string, request: Request): Promise; + test(strategy: string, request: Request): Promise; /** * Verify a request's authentication credentials against an authentication strategy. @@ -2647,15 +2656,24 @@ export interface ServerInfo { */ export interface ServerInjectOptions extends Shot.RequestOptions { /** - * an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via - * an authentication scheme. Defaults to no credentials. + * Authentication bypass options. */ - credentials?: AuthCredentials; - /** - * (an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received - * via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. - */ - artifacts?: object; + auth?: { + /** + * The authentication strategy name matching the provided credentials. + */ + strategy: string; + /** + * The credentials are used to bypass the default authentication strategies, + * and are validated directly as if they were received via an authentication scheme. + */ + credentials: AuthCredentials; + /** + * The artifacts are used to bypass the default authentication strategies, + * and are validated directly as if they were received via an authentication scheme. Defaults to no artifacts. + */ + artifacts?: object; + }; /** * sets the initial value of request.app, defaults to {}. */ @@ -2704,7 +2722,7 @@ export interface ServerInjectResponse extends Shot.ResponseObject { * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ -export type ServerMethod = (...args: any[]) => Promise; +export type ServerMethod = (...args: any[]) => any; /** * The same cache configuration used in server.cache(). @@ -2766,14 +2784,24 @@ export interface ServerMethodConfigurationObject { options?: ServerMethodOptions; } +export type CacheProvider = EnginePrototype | { + constructor: EnginePrototype; + options?: T; +}; + /** * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) */ export interface ServerOptionsCache extends PolicyOptions { - /** a class, a prototype function, or a catbox engine object. */ - engine?: EnginePrototypeOrObject; + /** catbox engine object. */ + engine?: ClientApi; + + /** + * a class or a prototype function + */ + provider?: CacheProvider; /** * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines @@ -2851,7 +2879,7 @@ export interface ServerOptions { * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) */ - cache?: EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; + cache?: CacheProvider | ServerOptionsCache | ServerOptionsCache[]; /** * Default value: { minBytes: 1024 }. @@ -2996,6 +3024,17 @@ export interface ServerOptions { * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. */ uri?: string; + + /** + * Query parameter configuration. + */ + query?: { + /** + * the method must return an object where each key is a parameter and matching value is the parameter value. + * If the method throws, the error is used as the response or returned when `request.setUrl` is called. + */ + parser(raw: Util.Dictionary): Util.Dictionary; + }; } /** diff --git a/types/hapi/test/request/info.ts b/types/hapi/test/request/info.ts new file mode 100644 index 0000000000..eae9d67d5f --- /dev/null +++ b/types/hapi/test/request/info.ts @@ -0,0 +1,4 @@ +import { Request } from "hapi"; + +const req: Request = {} as any; +const { completed, responded } = req.info; diff --git a/types/hapi/test/request/query.ts b/types/hapi/test/request/query.ts index 090ab3ae8d..26a886aa5f 100644 --- a/types/hapi/test/request/query.ts +++ b/types/hapi/test/request/query.ts @@ -6,10 +6,10 @@ const options: ServerOptions = { }; const handlerFn: Lifecycle.Method = (request, h) => { - const query1 = request.query as string; + const query1 = request.query; console.log(query1); - const query2 = request.query as RequestQuery; + const query2 = request.query; // http://localhost:8000/?name=test return `You asked for ${query2.name}`; }; diff --git a/types/hapi/test/response/response-events.ts b/types/hapi/test/response/response-events.ts index ec1b070b18..c78611cd2a 100644 --- a/types/hapi/test/response/response-events.ts +++ b/types/hapi/test/response/response-events.ts @@ -4,7 +4,7 @@ import * as Crypto from "crypto"; const preResponse: Lifecycle.Method = (request, h) => { // In onPreResponse, the response object will be defined. - const response = request.response!; + const response = request.response; const hash = Crypto.createHash('sha1'); response.events.on('peek', (chunk, encoding) => { diff --git a/types/hapi/test/route/route-options.ts b/types/hapi/test/route/route-options.ts index 438ef77d62..5f718a9c68 100644 --- a/types/hapi/test/route/route-options.ts +++ b/types/hapi/test/route/route-options.ts @@ -89,6 +89,7 @@ const routeOptionsResponse: RouteOptionsResponse = { 302: true, 404: false, }, + disconnectStatusCode: 123, }; const routeOptionSecure: RouteOptionsSecureObject = { diff --git a/types/hapi/test/route/validation.ts b/types/hapi/test/route/validation.ts index 6cc4ed186d..79b8effbb1 100644 --- a/types/hapi/test/route/validation.ts +++ b/types/hapi/test/route/validation.ts @@ -8,12 +8,30 @@ const options: ServerOptions = { const routeOptions: RouteOptions = { validate: { + payload: { + id: Joi.string().uuid().required(), + name: Joi.object({ + firstName: Joi.string().required(), + lastName: Joi.string().allow(null) + }), + firstName: Joi.ref("name.firstName") + }, params: { - name: Joi.string().min(3).max(10) - } + name: Joi.string().min(3).max(10), + nameRef: Joi.ref("name") + }, + state: { + woop: Joi.string().allow('doop'), + }, }, response: { - schema: Joi.string() + schema: Joi.object({ + a: Joi.string(), + b: Joi.object({ + c: Joi.number() + }), + d: Joi.ref("b.c") + }) } }; diff --git a/types/hapi/test/server/server-auth-test.ts b/types/hapi/test/server/server-auth-test.ts index 4e2a175e1a..c9f25fdfac 100644 --- a/types/hapi/test/server/server-auth-test.ts +++ b/types/hapi/test/server/server-auth-test.ts @@ -34,7 +34,7 @@ server.route({ path: '/', handler: async (request: Request, h: ResponseToolkit) => { try { - const credentials = await request.server.auth.test('default', request); + const { credentials } = await request.server.auth.test('default', request); return { status: true, user: credentials.name }; } catch (err) { return { status: false }; diff --git a/types/hapi/test/server/server-inject.ts b/types/hapi/test/server/server-inject.ts index a2ae777a71..c7c7565ccf 100644 --- a/types/hapi/test/server/server-inject.ts +++ b/types/hapi/test/server/server-inject.ts @@ -25,6 +25,14 @@ declare module 'hapi' { } server.inject({ + auth: { + strategy: 'test', + credentials: { + user: { + a: 1, + }, + }, + }, url: "test", app: { injectState: 1 diff --git a/types/hapi/test/server/server-method.ts b/types/hapi/test/server/server-method.ts index bb729516b7..39c3fdb9d7 100644 --- a/types/hapi/test/server/server-method.ts +++ b/types/hapi/test/server/server-method.ts @@ -6,7 +6,7 @@ const server = new Server({ }); server.start(); -const add = (a: any, b: any) => { +const add = (a: any, b: any): number => { return a + b; }; diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index 9df329c575..f47f0d8dfb 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -22,6 +22,7 @@ "test/request/catch-all.ts", "test/request/event-types.ts", "test/request/get-log.ts", + "test/request/info.ts", "test/request/methods.ts", "test/request/parameters.ts", "test/request/query.ts", diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts new file mode 100644 index 0000000000..d3262f5285 --- /dev/null +++ b/types/hapi/v17/index.d.ts @@ -0,0 +1,4005 @@ +// Type definitions for hapi 17.8 +// Project: https://github.com/hapijs/hapi +// Definitions by: Rafael Souza Fijalkowski +// Justin Simms +// Simon Schick +// Rodrigo Saboya +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WARNING: BACKWARDS INCOMPATIBLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/// + +import * as Boom from 'boom'; +import * as http from 'http'; +import * as https from 'https'; +import * as Shot from 'shot'; +import * as stream from 'stream'; +import * as url from 'url'; +import * as zlib from 'zlib'; + +import { MimosOptions } from 'mimos'; +import { SealOptions, SealOptionsSub } from 'iron'; +import { ValidationOptions, SchemaMap, Schema } from 'joi'; +import Podium = require('podium'); +import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy } from 'catbox'; + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Plugin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * one of + * a single plugin name string. + * an array of plugin name strings. + * an object where each key is a plugin name and each matching value is a + * {@link https://www.npmjs.com/package/semver version range string} which must match the registered + * plugin version. + */ +export type Dependencies = string | string[] | { + [key: string]: string; +}; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginsListRegistered { +} + +/** + * An object of the currently registered plugins where each key is a registered plugin name and the value is an + * object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ +export interface PluginRegistered { + /** + * the plugin version. + */ + version: string; + + /** + * the plugin name. + */ + name: string; + + /** + * options used to register the plugin. + */ + options: object; +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginsStates { +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginSpecificConfiguration { +} + +export interface PluginNameVersion { + /** + * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm + * registry) should use the same name as the name field in their 'package.json' file. Names must be + * unique within each application. + */ + name: string; + + /** + * optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's + * 'package.json' file. + */ + version?: string; +} + +export interface PluginPackage { + /** + * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included + */ + pkg: any; +} + +/** + * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each + * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox + * certain properties. For example, setting a file path in one plugin doesn't affect the file path set + * in another plugin. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins) + * + * The type T is the type of the plugin options. + */ +export interface PluginBase { + /** + * (required) the registration function with the signature async function(server, options) where: + * * server - the server object with a plugin-specific server.realm. + * * options - any options passed to the plugin during registration via server.register(). + */ + register: (server: Server, options: T) => void | Promise; + + /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ + multiple?: boolean; + + /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ + dependencies?: Dependencies; + + /** + * Allows defining semver requirements for node and hapi. + * @default Allows all. + */ + requirements?: { + node?: string; + hapi?: string; + }; + + /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ + once?: boolean; +} + +export type Plugin = PluginBase & (PluginNameVersion | PluginPackage); + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Request + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * User extensible types user credentials. + */ +// tslint:disable-next-line:no-empty-interface +export interface UserCredentials { +} + +/** + * User extensible types app credentials. + */ +// tslint:disable-next-line:no-empty-interface +export interface AppCredentials { +} + +/** + * User-extensible type for request.auth credentials. + */ +export interface AuthCredentials { + /** + * The application scopes to be granted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) + */ + scope?: string[]; + /** + * If set, will only work with routes that set `access.entity` to `user`. + */ + user?: UserCredentials; + + /** + * If set, will only work with routes that set `access.entity` to `app`. + */ + app?: AppCredentials; +} + +/** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed + * authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ +export interface RequestAuth { + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: object; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: AuthCredentials; + /** the authentication error is failed and mode set to 'try'. */ + error: Error; + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** + * true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, + * set to false. + */ + isAuthorized: boolean; + /** the route authentication mode. */ + mode: string; + /** the name of the strategy used. */ + strategy: string; +} + +/** + * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export type RequestEventType = 'peek' | 'finish' | 'disconnect'; + +/** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export interface RequestEvents extends Podium { + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + on(criteria: 'peek', listener: PeekListener): void; + + on(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + once(criteria: 'peek', listener: PeekListener): void; + + once(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void; +} + +/** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only + * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ +export interface RequestInfo { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after + * the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + */ + isOriginMatch?: boolean; + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com'). */ + hostname: string; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */ + id: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** remote client port. */ + remotePort: string; + /** request response timestamp (0 is not responded yet). */ + responded: number; +} + +/** + * The request route information object, where: + * * method - the route HTTP method. + * * path - the route path. + * * vhost - the route vhost option if configured. + * * realm - the active realm associated with the route. + * * settings - the route options object with all defaults applied. + * * fingerprint - the route internal normalized string representing the normalized path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + */ +export interface RequestRoute { + /** the route HTTP method. */ + method: Util.HTTP_METHODS_PARTIAL; + + /** the route path. */ + path: string; + + /** the route vhost option if configured. */ + vhost?: string | string[]; + + /** the active realm associated with the route. */ + realm: ServerRealm; + + /** the route options object with all defaults applied. */ + settings: RouteOptions; + + /** the route internal normalized string representing the normalized path. */ + fingerprint: string; + + auth: { + /** + * Validates a request against the route's authentication access configuration, where: + * @param request - the request object. + * @return Return value: true if the request would have passed the route's access requirements. + * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access + * configuration. If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may + * not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route + * requires any authentication. + * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) + */ + access(request: Request): boolean; + }; +} + +/** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) + */ +export interface RequestOrig { + params: object; + query: object; + payload: object; +} + +export interface RequestLog { + request: string; + timestamp: number; + tags: string[]; + data: string | object; + channel: string; +} + +export interface RequestQuery { + [key: string]: string | string[]; +} + +/** + * The request object is created internally for each incoming request. It is not the same object received from the node + * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout + * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle). + */ +export interface Request extends Podium { + /** + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) + */ + app: ApplicationState; + + /** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed + * authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ + readonly auth: RequestAuth; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + events: RequestEvents; + + /** + * The raw request headers (references request.raw.req.headers). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only + * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ + readonly info: RequestInfo; + + /** + * An array containing the logged request events. + * Note that this array will be empty if route log.collect is set to false. + */ + readonly logs: RequestLog[]; + + /** + * The request method in lower case (e.g. 'get', 'post'). + */ + readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE; + + /** + * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. + */ + readonly mime: string; + + /** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + */ + readonly orig: RequestOrig; + + /** + * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). + */ + readonly params: Util.Dictionary; + + /** + * An array containing all the path params values in the order they appeared in the path. + */ + readonly paramsArray: string[]; + + /** + * The request URI's pathname component. + */ + readonly path: string; + + /** + * The request payload based on the route payload.output and payload.parse settings. + * TODO check this typing and add references / links. + */ + readonly payload: stream.Readable | Buffer | string | object; + + /** + * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. + */ + plugins: PluginsStates; + + /** + * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response + * object, use responses. + */ + readonly pre: Util.Dictionary; + + /** + * Access: read / write (see limitations below). + * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to + * override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). + */ + response: ResponseObject | Boom | null; + + /** + * Same as pre but represented as the response object created by the pre method. + */ + readonly preResponses: Util.Dictionary; + + /** + * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query + * attribute as an unparsed string). + */ + readonly query: RequestQuery | string; + + /** + * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. + * * req - the node request object. + * * res - the node response object. + */ + readonly raw: { + req: http.IncomingMessage; + res: http.ServerResponse; + }; + + /** + * The request route information object and method + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest) + */ + readonly route: RequestRoute; + + /** + * Access: read only and the public server interface. + * The server object. + */ + server: Server; + + /** + * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. + */ + readonly state: Util.Dictionary; + + /** + * The parsed request URI. + */ + readonly url: url.Url; + + /** + * Returns `true` when the request is active and processing should continue and `false` when the + * request terminated early or completed its lifecycle. Useful when request processing is a + * resource-intensive operation and should be terminated early if the request is no longer active + * (e.g. client disconnected or aborted early). + */ + active(): boolean; + + /** + * Returns a response which you can pass into the reply interface where: + * @param source - the value to set as the source of the reply interface, optional. + * @param options - options for the method, optional. + * @return ResponseObject + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) + */ + /* tslint:disable-next-line:max-line-length */ + generateResponse(source: string | object | null, options?: { variety?: string; prepare?: (response: ResponseObject) => Promise; marshal?: (response: ResponseObject) => Promise; close?: (response: ResponseObject) => void; }): ResponseObject; + + /** + * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + * @param tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism + * for describing and filtering events. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return + * value) the actual data emitted to the listeners. Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag + * set to true. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) + */ + log(tags: string | string[], data?: string | object | (() => string | object)): void; + + /** + * Changes the request method before the router begins processing the request where: + * @param method - is the request HTTP method (e.g. 'GET'). + * @return void + * Can only be called from an 'onRequest' extension method. + * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) + */ + setMethod(method: Util.HTTP_METHODS_PARTIAL): void; + + /** + * Changes the request URI before the router begins processing the request where: + * Can only be called from an 'onRequest' extension method. + * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL + * parse() method output. + * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false. + * @return void + * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) + */ + setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseEvents extends Podium { + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + on(criteria: 'peek', listener: PeekListener): void; + + on(criteria: 'finish', listener: (data: undefined) => void): void; + + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + once(criteria: 'peek', listener: PeekListener): void; + + once(criteria: 'finish', listener: (data: undefined) => void): void; +} + +/** + * Object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + */ +export interface ResponseObjectHeaderOptions { + append?: boolean; + separator?: string; + override?: boolean; + duplicate?: boolean; +} + +/** + * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle + * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status + * code). In order to customize a response before it is returned, the h.response() method is provided. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseObject extends Podium { + /** + * Default value: {}. + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) + */ + app: ApplicationState; + + /** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ + readonly events: ResponseEvents; + + /** + * Default value: {}. + * An object containing the response headers where each key is a header field name and the value is the string header value or array of string. + * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Default value: {}. + * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins) + */ + plugins: PluginsStates; + + /** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ + readonly settings: ResponseSettings; + + /** + * The raw value returned by the lifecycle method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource) + */ + readonly source: Lifecycle.ReturnValue; + + /** + * Default value: 200. + * The HTTP response status code. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode) + */ + readonly statusCode: number; + + /** + * A string indicating the type of source with available values: + * * 'plain' - a plain response such as string, number, null, or simple object. + * * 'buffer' - a Buffer. + * * 'stream' - a Stream. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety) + */ + readonly variety: 'plain' | 'buffer' | 'stream'; + + /** + * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + * @param length - the header value. Must match the actual payload size. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength) + */ + bytes(length: number): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * @param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset) + */ + charset(charset: string): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * $param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) + */ + code(statusCode: number): ResponseObject; + + /** + * Sets the HTTP status message where: + * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200). + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) + */ + message(httpMessage: string): ResponseObject; + + /** + * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) + */ + created(uri: string): ResponseObject; + + /** + * Sets the string encoding scheme used to serial data into the HTTP payload where: + * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). + * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. + * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. + * * 'ucs2' - Alias of 'utf16le'. + * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. + * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). + * * 'binary' - Alias for 'latin1'. + * * 'hex' - Encode each byte as two hexadecimal characters. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) + */ + encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; + + /** + * Sets the representation entity tag where: + * @param tag - the entity tag string without the double-quote. + * @param options - (optional) settings where: + * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by + * a '-' character). Ignored when weak is true. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) + */ + etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; + + /** + * Sets an HTTP header where: + * @param name - the header name. + * @param value - the header value. + * @param options - (optional) object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + */ + header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; + + /** + * Sets the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) + */ + location(uri: string): ResponseObject; + + /** + * Sets an HTTP redirection response (302) and decorates the response with additional methods, where: + * @param uri - an absolute or relative URI used to redirect the client to another resource. + * @return Return value: the current response object. + * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) + */ + redirect(uri: string): ResponseObject; + + /** + * Sets the JSON.stringify() replacer argument where: + * @param method - the replacer function or array. Defaults to none. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) + */ + replacer(method: Json.StringifyReplacer): ResponseObject; + + /** + * Sets the JSON.stringify() space argument where: + * @param count - the number of spaces to indent nested object keys. Defaults to no indentation. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) + */ + spaces(count: number): ResponseObject; + + /** + * Sets an HTTP cookie where: + * @param name - the cookie name. + * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values. + * @param options - (optional) configuration. If the state was previously registered with the server using server.state(), the specified keys in options are merged with the default server + * definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) + */ + state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Sets a string suffix when the response is process via JSON.stringify() where: + * @param suffix - the string suffix. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) + */ + suffix(suffix: string): ResponseObject; + + /** + * Overrides the default route cache expiration rule for this response instance where: + * @param msec - the time-to-live value in milliseconds. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) + */ + ttl(msec: number): ResponseObject; + + /** + * Sets the HTTP 'Content-Type' header where: + * @param mimeType - is the mime type. + * @return Return value: the current response object. + * Should only be used to override the built-in default for each response type. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) + */ + type(mimeType: string): ResponseObject; + + /** + * Clears the HTTP cookie by setting an expired value where: + * @param name - the cookie name. + * @param options - (optional) configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified options are merged with the server + * definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: + * @param header - the HTTP request header name. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) + */ + vary(header: string): ResponseObject; + + /** + * Marks the response object as a takeover response. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) + */ + takeover(): ResponseObject; + + /** + * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where: + * @param isTemporary - if false, sets status to permanent. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) + */ + temporary(isTemporary: boolean): ResponseObject; + + /** + * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where: + * @param isPermanent - if false, sets status to temporary. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) + */ + permanent(isPermanent: boolean): ResponseObject; + + /** + * Sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' + * to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments: + * @param isRewritable - if false, sets to non-rewritable. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) + */ + rewritable(isRewritable: boolean): ResponseObject; +} + +/** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ +export interface ResponseSettings { + /** + * Defaults value: true. + * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response. + */ + readonly passThrough: boolean; + + /** + * Default value: null (use route defaults). + * Override the route json options used when source value requires stringification. + */ + readonly stringify: Json.StringifyArguments; + + /** + * Default value: null (use route defaults). + * If set, overrides the route cache with an expiration value in milliseconds. + */ + readonly ttl: number; + + /** + * Default value: false. + * If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. + */ + varyEtag: boolean; +} + +/** + * See more about Lifecycle + * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle + * + */ + +export type ResponseValue = string | object; + +export interface AuthenticationData { + credentials: AuthCredentials; + artifacts?: object; +} + +export interface Auth { + readonly isAuth: true; + readonly error?: Error | null; + readonly data?: AuthenticationData; +} + +/** + * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the + * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this + * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) + */ +export interface ResponseToolkit { + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step + * without further interaction with the node response stream. It is the developer's responsibility to write + * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw). + */ + readonly abandon: symbol; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after + * calling request.raw.res.end()) to close the the node response stream. + */ + readonly close: symbol; + + /** + * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) + * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). + */ + readonly context: any; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. + */ + readonly continue: symbol; + + /** + * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching + * route. Defaults to the root server realm in the onRequest step. + */ + readonly realm: ServerRealm; + + /** + * Access: read only and public request interface. + * The [request] object. This is a duplication of the request lifecycle method argument used by + * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. + */ + readonly request: Readonly; + + /** + * Used by the [authentication] method to pass back valid credentials where: + * @param data - an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return Return value: an internal authentication object. + */ + authenticated(data: AuthenticationData): Auth; + + /** + * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if + * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request + * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will + * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined. + * The method argumetns are: + * @param options - a required configuration object with: + * * etag - the ETag string. Required if modified is not present. Defaults to no header. + * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. + * * vary - same as the response.etag() option. Defaults to true. + * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. + * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, + * it should be used as the return value (but may be customize using the response methods). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) + */ + entity(options?: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; + + /** + * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). + * @param url + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) + */ + redirect(uri?: string): ResponseObject; + + /** + * Wraps the provided value and returns a response object which allows customizing the response + * (e.g. setting the HTTP status code, custom headers, etc.), where: + * @param value - (optional) return value. Defaults to null. + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) + */ + response(value?: ResponseValue): ResponseObject; + + /** + * Sets a response cookie using the same arguments as response.state(). + * @param name of the cookie + * @param value of the cookie + * @param (optional) ServerStateCookieOptions object. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) + */ + state(name: string, value: string | object, options?: ServerStateCookieOptions): void; + + /** + * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: + * @param error - (required) the authentication error. + * @param data - (optional) an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return void. + * The method is used to pass both the authentication error and the credentials. For example, if a request included + * expired credentials, it allows the method to pass back the user information (combined with a 'try' + * authentication mode) for error customization. + * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) + */ + unauthenticated(error: Error, data?: AuthenticationData): void; + + /** + * Clears a response cookie using the same arguments as + * @param name of the cookie + * @param options (optional) ServerStateCookieOptions object. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Route + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +export type RouteOptionsAccessScope = false | string | string[]; + +export type RouteOptionsAccessEntity = 'any' | 'user' | 'app'; + +export interface RouteOptionsAccessScopeObject { + scope: RouteOptionsAccessScope; +} + +export interface RouteOptionsAccessEntityObject { + entity: RouteOptionsAccessEntity; +} + +export type RouteOptionsAccessObject = + RouteOptionsAccessScopeObject + | RouteOptionsAccessEntityObject + | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject); + +/** + * Route Authentication Options + */ +export interface RouteOptionsAccess { + /** + * Default value: none. + * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object + * must include at least one of scope or entity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) + */ + access?: RouteOptionsAccessObject | RouteOptionsAccessObject[]; + + /** + * Default value: false (no scope requirements). + * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least + * one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For + * example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access + * properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) + */ + scope?: RouteOptionsAccessScope; + + /** + * Default value: 'any'. + * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values: + * * 'any' - the authentication can be on behalf of a user or application. + * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy. + * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication + * strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) + */ + entity?: RouteOptionsAccessEntity; + + /** + * Default value: 'required'. + * The authentication mode. Available values: + * * 'required' - authentication is required. + * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. + * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) + */ + mode?: 'required' | 'optional' | 'try'; + + /** + * Default value: false, unless the scheme requires payload authentication. + * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' + * when the scheme sets the authentication options.payload to true. Available values: + * * false - no payload authentication. + * * 'required' - payload authentication required. + * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) + */ + payload?: false | 'required' | 'optional'; + + /** + * Default value: the default strategy set via server.auth.default(). + * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies) + */ + strategies?: string[]; + + /** + * Default value: the default strategy set via server.auth.default(). + * A string strategy names. Cannot be used together with strategies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy) + */ + strategy?: string; +} + +/** + * Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ +export type RouteOptionsCache = { + privacy?: 'default' | 'public' | 'private'; + statuses?: number[]; + otherwise?: string; +} & ( + { + expiresIn?: number; + expiresAt?: undefined; + } | { + expiresIn?: undefined; + expiresAt?: string; +} | { + expiresIn?: undefined; + expiresAt?: undefined; +} + ); + +/** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain + * than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a + * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. + * Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. + * Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ +export interface RouteOptionsCors { + /** + * an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' + * character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any + * origin ['*']. + */ + origin?: string[] | '*' | 'ignore'; + /** + * number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. + * Defaults to 86400 (one day). + */ + maxAge?: number; + /** + * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + */ + headers?: string[]; + /** + * a strings array of additional headers to headers. Use this to keep the default headers in place. + */ + additionalHeaders?: string[]; + /** + * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + */ + exposedHeaders?: string[]; + /** + * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + */ + additionalExposedHeaders?: string[]; + /** + * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + */ + credentials?: boolean; +} + +/** + * The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw + * Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are + * provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart + * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the + * multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are + * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of + * which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ +export type PayloadOutput = 'data' | 'stream' | 'file'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ +export type PayloadCompressionDecoderSettings = object; + +/** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ +export interface RouteOptionsPayload { + /** + * Default value: allows parsing of the following mime types: + * * application/json + * * application/*+json + * * application/octet-stream + * * application/x-www-form-urlencoded + * * multipart/form-data + * * text/* + * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed + * above will not enable them to be parsed, and if parse is true, the request will result in an error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow) + */ + allow?: string | string[]; + + /** + * Default value: none. + * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: 'application/json'. + * The default content type if the 'Content-Type' request header is missing. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype) + */ + defaultContentType?: string; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle payload parsing errors. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: 1048576 (1MB). + * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes) + */ + maxBytes?: number; + + /** + * Default value: none. + * Overrides payload processing for multipart requests. Value can be one of: + * * false - disable multipart processing. + * an object with the following required options: + * * output - same as the output option with an additional value option: + * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? + * * * * headers - the part headers. + * * * * filename - the part file name. + * * * * payload - the processed part payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart) + */ + multipart?: false | { + output: PayloadOutput | 'annotated'; + }; + + /** + * Default value: 'data'. + * The processed payload format. The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw + * Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files + * are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart + * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the + * multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are + * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track + * of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ + output?: PayloadOutput; + + /** + * Default value: none. + * A mime type string overriding the 'Content-Type' header value received. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride) + */ + override?: string; + + /** + * Default value: true. + * Determines if the incoming payload is processed or presented raw. Available values: + * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the + * format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. + * * false - the raw payload is returned unmodified. + * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse) + */ + parse?: boolean | 'gunzip'; + + /** + * Default value: to 10000 (10 seconds). + * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) + * error response. Set to false to disable. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout) + */ + timeout?: false | number; + + /** + * Default value: os.tmpdir(). + * The directory used for writing file uploads. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads) + */ + uploads?: string; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method; + +/** + * An object with: + * * method - a lifecycle method. + * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export interface RouteOptionsPreObject { + /** + * a lifecycle method. + */ + method: Lifecycle.Method; + /** + * key name used to assign the response of the method to in request.pre and request.preResponses. + */ + assign?: string; + /** + * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + */ + failAction?: Lifecycle.FailAction; +} + +export type ValidationObject = SchemaMap; + +export type RouteOptionsResponseSchema = + boolean + | ValidationObject + | Schema + | ((value: object | Buffer | string, options: ValidationOptions) => Promise); + +/** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ +export interface RouteOptionsResponse { + /** + * Default value: 200. + * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the + * response status code will remain 200 throughout the request lifecycle unless manually set). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) + */ + emptyStatusCode?: 200 | 204; + + /** + * Default value: 'error' (return an Internal Server Error (500) error response). + * A failAction value which defines what to do when a response fails payload validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: false. + * If true, applies the validation rule changes to the response payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify) + */ + modify?: boolean; + + /** + * Default value: none. + * [joi](http://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a + * custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions) + */ + options?: ValidationOptions; // TODO needs validation + + /** + * Default value: true. + * If false, payload range support is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges) + */ + ranges?: boolean; + + /** + * Default value: 100 (all responses). + * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample) + */ + sample?: number; + + /** + * Default value: true (no validation). + * The default response payload validation rules (for all non-error responses) expressed as one of: + * * true - any payload allowed (no validation). + * * false - no payload allowed. + * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. + * * a validation function using the signature async function(value, options) where: + * * * value - the pending response payload. + * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }). + * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error + * output.payload. If an error is thrown, the error is processed according to failAction. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) + */ + schema?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema. + * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) + */ + status?: Util.Dictionary; +} + +/** + * @see https://www.w3.org/TR/referrer-policy/ + */ +export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'unsafe-url' | + 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin'; + +/** + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically + * changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively + * support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ +export interface RouteOptionsSecureObject { + /** + * hsts - controls the 'Strict-Transport-Security' header + */ + hsts?: boolean | number | { + /** + * the max-age portion of the header, as a number. Default is 15768000. + */ + maxAge: number; + /** + * a boolean specifying whether to add the includeSubDomains flag to the header. + */ + includeSubdomains: boolean; + /** + * a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + */ + preload: boolean; + }; + /** + * controls the 'X-Frame-Options' header + */ + xframe?: true | 'deny' | 'sameorigin' | { + /** + * an object for specifying the 'allow-from' rule, + */ + rule: 'deny' | 'sameorigin' | 'allow-from'; + /** + * when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed + * to 'sameorigin'. + */ + source: string; + }; + /** + * boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively + * support old versions of IE, it may be wise to explicitly set this flag to false. + */ + xss: boolean; + /** + * boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + */ + noOpen?: boolean; + /** + * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + */ + noSniff?: boolean; + + /** + * Controls the `Referrer-Policy` header, which has the following possible values. + * @default false Header will not be send. + */ + referrer?: false | ReferrerPolicy; +} + +export type RouteOptionsSecure = boolean | RouteOptionsSecureObject; + +/** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ +export interface RouteOptionsValidate { + /** + * Default value: none. + * An optional object with error fields copied into every validation error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) + */ + errorFields?: object; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: true (no validation). + * Validation rules for incoming request headers: + * * true - any headers allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.headers object containing the request headers. + * * * options - options. + * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error + * is thrown, the error is handled according to failAction. Note that all header field names must be in lowercase to match the headers normalized by node. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) + */ + headers?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). + * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. + * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as + * Joi.ref('$query.key')). + * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated + * will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the + * individual route settings override the routes defaults (the rules are not merged). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + options?: ValidationOptions | object; + + /** + * Default value: true (no validation). + * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: + * * true - any path parameter value allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.params object containing the request path parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an + * error is thrown, the error is handled according to failAction. Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + params?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request payload (request body), where: + * * true - any payload allowed (no validation performed). false - no payload allowed. + * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by + * setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is + * thrown, the error is handled according to failAction. Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well + * as the significant performance cost of validating large amounts of data. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) + */ + payload?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in + * request.query prior to validation. Where: + * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error + * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) + */ + query?: RouteOptionsResponseSchema; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ +export type RouteCompressionEncoderSettings = object; + +/** + * Empty interface to allow for user-defined augmentations. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface RouteOptionsApp { +} + +/** + * Each route can be customized to change the default behavior of the request lifecycle. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) + */ +export interface RouteOptions { + /** + * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + app?: RouteOptionsApp; + + /** + * Route authentication configuration. Value can be: + * false to disable authentication if a default strategy is set. + * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. + * an authentication configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + auth?: false | string | RouteOptionsAccess; + + /** + * Default value: null. + * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) + */ + bind?: object | null; + + /** + * Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. + * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: + * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * The default Cache-Control: no-cache header can be disabled by setting cache to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ + cache?: false | RouteOptionsCache; + + /** + * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different + * domain than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a + * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. + * Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in + * policy. Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ + cors?: boolean | RouteOptionsCors; + + /** + * Default value: none. + * Route description used for generating documentation (string). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription) + */ + description?: string; + + /** + * Default value: none. + * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the + * server.ext(events) event argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ + ext?: { + [key in RouteRequestExtType]?: RouteExtObject | RouteExtObject[]; + }; + + /** + * Default value: { relativeTo: '.' }. + * Defines the behavior for accessing files: + * * relativeTo - determines the folder relative paths are resolved against. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles) + */ + files?: { + relativeTo: string; + }; + + /** + * Default value: none. + * The route handler function performs the main business logic of the route and sets the response. handler can be assigned: + * * a lifecycle method. + * * an object with a single property using the name of a handler type registred with the server.handler() method. The matching property value is passed as options to the registered handler + * generator. Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) + */ + handler?: Lifecycle.Method | object; + + /** + * Default value: none. + * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid) + */ + id?: string; + + /** + * Default value: false. + * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should + * not be accessible to the outside world. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal) + */ + isInternal?: boolean; + + /** + * Default value: none. + * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: + * * replacer - the replacer function or array. Defaults to no action. + * * space - number of spaces to indent nested object keys. Defaults to no indentation. + * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix. + * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + json?: Json.StringifyArguments; + + /** + * Default value: none. + * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. + * For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream + * responses. The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if + * explicitly set by response.type(). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp) + */ + jsonp?: string; + + /** + * Default value: { collect: false }. + * Request logging options: + * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog) + */ + log?: { + collect: boolean; + }; + + /** + * Default value: none. + * Route notes used for generating documentation (string or array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes) + */ + notes?: string | string[]; + + /** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ + payload?: RouteOptionsPayload; + + /** + * Default value: {}. + * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) + */ + plugins?: PluginSpecificConfiguration; + + /** + * Default value: none. + * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared + * ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). pre is assigned an ordered array of methods which + * are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of + * the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. pre can be assigned a mixed array of: + * * an array containing the elements listed below, which are executed in parallel. + * * an object with: + * * * method - a lifecycle method. + * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be + * assigned. + * * a method function - same as including an object with a single method key. + * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used + * to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other + * lifecycle methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ + pre?: RouteOptionsPreArray; + + /** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ + response?: RouteOptionsResponse; + + /** + * Default value: false (security headers disabled). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ + security?: RouteOptionsSecure; + + /** + * Default value: { parse: true, failAction: 'error' }. + * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following + * options: parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. failAction - A failAction value which determines how to handle cookie parsing + * errors. Defaults to 'error' (return a Bad Request (400) error response). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate) + */ + state?: { + parse?: boolean; + failAction?: Lifecycle.FailAction; + }; + + /** + * Default value: none. + * Route tags used for generating documentation (array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags) + */ + tags?: string[]; + + /** + * Default value: { server: false }. + * Timeouts for processing durations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout) + */ + timeout?: { + /** + * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error + * response. + */ + server?: boolean | number; + + /** + * Default value: none (use node default of 2 minutes). + * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts. + */ + socket?: boolean | number; + }; + + /** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ + validate?: RouteOptionsValidate; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Server + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ +export type ServerAuthSchemeOptions = object; + +/** + * the method implementing the scheme with signature function(server, options) where: + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + * @param server - a reference to the server object the scheme is added to. + * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + */ +export type ServerAuthScheme = (server: Server, options?: ServerAuthSchemeOptions) => ServerAuthSchemeObject; + +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerAuthSchemeObjectApi { +} + +/** + * The scheme method must return an object with the following + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme) + */ +export interface ServerAuthSchemeObject { + /** + * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. + */ + api?: ServerAuthSchemeObjectApi; + + /** + * A lifecycle method function called for each incoming request configured with the authentication scheme. The + * method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result: + * * h.authenticated() - indicate request authenticated successfully. + * * h.unauthenticated() - indicate request failed to authenticate. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to authenticate the request payload. + * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad + * payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), + * authentication may still be successful if the route auth.payload configuration is set to 'optional'. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * a method used to verify the authentication credentials provided + * are still valid (e.g. not expired or revoked after the initial authentication). + * the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or + * revoked). Note that the method does not have access to the original request, only to the + * credentials and artifacts produced by the `authenticate()` method. + */ + verify?(auth: RequestAuth): Promise; + + /** + * An object with the following keys: + * * payload + */ + options?: { + /** + * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. + */ + payload?: boolean; + }; +} + +/** + * An authentication configuration object using the same format as the route auth handler options. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerAuthConfig extends RouteOptionsAccess { +} + +export interface ServerAuth { + /** + * An object where each key is an authentication strategy name and the value is the exposed strategy API. + * Available only when the authentication scheme exposes an API by returning an api key in the object + * returned from its implementation function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) + */ + api: Util.Dictionary; + + /** + * Contains the default authentication configuration is a default strategy was set via + * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). + */ + readonly settings: { + default: ServerAuthConfig; + }; + + /** + * Sets a default strategy which is applied to every route where: + * @param options - one of: + * * a string with the default strategy name + * * an authentication configuration object using the same format as the route auth handler options. + * @return void. + * The default does not apply when a route config specifies auth as false, or has an authentication strategy + * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication + * config is applied to the defaults. + * Note that if the route has authentication configured, the default only applies at the time of adding the route, + * not at runtime. This means that calling server.auth.default() after adding a route with some authentication + * config will have no impact on the routes added prior. However, the default will apply to routes added + * before server.auth.default() is called if those routes lack any authentication config. + * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active + * authentication configuration of a route, use server.auth.lookup(request.route). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ + default(options: string | ServerAuthConfig): void; + + /** + * Registers an authentication scheme where: + * @param name the scheme name. + * @param scheme - the method implementing the scheme with signature function(server, options) where: + * * server - a reference to the server object the scheme is added to. + * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ + scheme(name: string, scheme: ServerAuthScheme): void; + + /** + * Registers an authentication strategy where: + * @param name - the strategy name. + * @param scheme - the scheme name (must be previously registered using server.auth.scheme()). + * @param options - scheme options based on the scheme requirements. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) + */ + strategy(name: string, scheme: string, options?: object): void; + + /** + * Tests a request against an authentication strategy where: + * @param strategy - the strategy name registered with server.auth.strategy(). + * @param request - the request object. + * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. + * Note that the test() method does not take into account the route authentication configuration. It also does not + * perform payload authentication. It is limited to the basic strategy authentication execution. It does not + * include verifying scope, entity, or other route properties. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) + */ + test(strategy: string, request: Request): Promise; + + /** + * Verify a request's authentication credentials against an authentication strategy. + * Returns nothing if verification was successful, otherwise throws an error. + * + * Note that the `verify()` method does not take into account the route authentication configuration + * or any other information from the request other than the `request.auth` object. It also does not + * perform payload authentication. It is limited to verifying that the previously valid credentials + * are still valid (e.g. have not been revoked or expired). It does not include verifying scope, + * entity, or other route properties. + */ + verify(request: Request): Promise; +} + +export type CachePolicyOptions = PolicyOptionVariants & { + /** + * @default '_default' + */ + cache?: string; + segment?: string; +}; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerCache { + /** + * Provisions a cache segment within the server cache facility where: + * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: + * - `id` - the `id` string or object provided to the `get()` method. + * - `flags` - an object used to pass back additional flags to the cache where: + * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. + * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + * * staleTimeout - number of milliseconds to wait before checking if an item is stale. + * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it + * is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. + * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. + * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. + * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. + * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of + * concurrent generateFunc calls beyond staleTimeout). + * * cache - the cache name configured in server.cache. Defaults to the default cache. + * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a + * server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. + * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. + * @return Catbox Policy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + = CachePolicyOptions>(options: O): Policy; + + /** + * Provisions a server cache as described in server.cache where: + * @param options - same as the server cache configuration options. + * @return Return value: none. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) + */ + provision(options: ServerOptionsCache): Promise; +} + +/** + * an event name string. + * an event options object. + * a podium emitter object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; + +/** + * Object that it will be used in Event + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export interface ServerEventsApplicationObject { + /** the event name string (required). */ + name: string; + /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ + channels?: string | string[]; + /** + * if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). + */ + clone?: boolean; + /** + * if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified + * by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). + */ + spread?: boolean; + /** + * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to + * the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + */ + tags?: boolean; + /** + * if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first + * configuration is used. Defaults to false (a duplicate registration will throw an error). + */ + shared?: boolean; +} + +/** + * A criteria object with the following optional keys (unless noted otherwise): + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * + * The type parameter T is the type of the name of the event. + */ +export interface ServerEventCriteria { + /** (required) the event name string. */ + name: T; + /** + * a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed + * channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. + */ + channels?: string | string[]; + /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ + clone?: boolean; + /** + * a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once(). + * Defaults to no limit. + */ + count?: number; + /** + * filter - the event tags (if present) to subscribe to which can be one of: + * * a tag string. + * * an array of tag strings. + * * an object with the following: + * * * tags - a tag string or array of tag strings. + * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). + */ + filter?: string | string[] | {tags: string | string[], all?: boolean}; + /** + * if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used + * when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). + */ + spread?: boolean; + /** + * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended + * to the arguments list at the end. Defaults to the event registration option (which defaults to false). + */ + tags?: boolean; +} + +export interface LogEvent { + /** the event timestamp. */ + timestamp: string; + /** an array of tags identifying the event (e.g. ['error', 'http']) */ + tags: string[]; + /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ + channel: 'internal' | 'app'; + /** the request identifier. */ + request: string; + /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ + data: object; + /** the error object related to the event if applicable. Cannot appear together with data */ + error: object; +} + +export interface RequestEvent { + /** the event timestamp. */ + timestamp: string; + /** an array of tags identifying the event (e.g. ['error', 'http']) */ + tags: string[]; + /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ + channel: 'internal' | 'app' | 'error'; + /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ + data: object; + /** the error object related to the event if applicable. Cannot appear together with data */ + error: object; +} + +export type LogEventHandler = (event: LogEvent, tags: { [key: string]: true }) => void; +export type RequestEventHandler = (request: Request, event: RequestEvent, tags: { [key: string]: true }) => void; +export type ResponseEventHandler = (request: Request) => void; +export type RouteEventHandler = (route: RequestRoute) => void; +export type StartEventHandler = () => void; +export type StopEventHandler = () => void; + +export interface PodiumEvent { + emit(criteria: K, listener: (value: T) => void): void; + + on(criteria: K, listener: (value: T) => void): void; + + once(criteria: K, listener: (value: T) => void): void; + + once(criteria: K): Promise; + + removeListener(criteria: K, listener: Podium.Listener): this; + + removeAllListeners(criteria: K): this; + + hasListeners(criteria: K): this; +} + +/** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events. + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ +export interface ServerEvents extends Podium { + /** + * Subscribe to an event where: + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) + * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) + * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) + * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) + * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) + * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) + */ + on(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): void; + + on(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): void; + + on(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): void; + + on(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): void; + + on(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): void; + + on(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): void; + + /** + * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) + */ + once(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): void; + + once(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): void; + + once(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): void; + + once(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): void; + + once(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): void; + + once(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): void; + + /** + * Same as calling server.events.on() with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @return Return value: a promise that resolves when the event is emitted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) + */ + once(criteria: string | ServerEventCriteria): Promise; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeListener(name: string, listener: Podium.Listener): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeAllListeners(name: string): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + hasListeners(name: string): boolean; +} + +/** + * The extension point event name. The available extension points include the request extension points as well as the following server extension points: + * 'onPreStart' - called before the connection listeners are started. + * 'onPostStart' - called after the connection listeners are started. + * 'onPreStop' - called before the connection listeners are stopped. + * 'onPostStop' - called after the connection listeners are stopped. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ +export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; +export type RouteRequestExtType = 'onPreAuth' + | 'onCredentials' + | 'onPostAuth' + | 'onPreHandler' + | 'onPostHandler' + | 'onPreResponse'; + +export type ServerRequestExtType = + RouteRequestExtType + | 'onRequest'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + */ + type: ServerExtType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: ServerExtPointFunction | ServerExtPointFunction[]; + options?: ServerExtOptions; +} + +export interface RouteExtObject { + method: Lifecycle.Method; + options?: ServerExtOptions; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsRequestObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + * * 'onPostStop' - called after the connection listeners are stopped. + */ + type: ServerRequestExtType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: Lifecycle.Method | Lifecycle.Method[]; + /** + * (optional) an object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, + * or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + options?: ServerExtOptions; +} + +export type ServerExtPointFunction = (server: Server) => void; + +/** + * An object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ +export interface ServerExtOptions { + /** + * a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + */ + before?: string | string[]; + /** + * a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + */ + after?: string | string[]; + /** + * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + */ + bind?: object; + /** + * if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when + * adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + sandbox?: 'server' | 'plugin'; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + * An object containing information about the server where: + */ +export interface ServerInfo { + /** + * a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + */ + id: string; + + /** + * server creation timestamp. + */ + created: number; + + /** + * server start timestamp (0 when stopped). + */ + started: number; + + /** + * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules: + * * before the server has been started: the configured port value. + * * after the server has been started: the actual port assigned when no port is configured or was set to 0. + */ + port: number | string; + + /** + * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value. + */ + host: string; + + /** + * the active IP address the connection was bound to after starting. Set to undefined until the server has been + * started or when using a non TCP port (e.g. UNIX domain socket). + */ + address: undefined | string; + + /** + * the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + */ + protocol: 'http' | 'https' | 'socket'; + + /** + * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains + * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set + * to 0, the uri will not include a port component until the server is started. + */ + uri: string; +} + +/** + * An object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload + * processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if + * they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as + * if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested + * separately. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectOptions extends Shot.RequestOptions { + /** + * an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via + * an authentication scheme. Defaults to no credentials. + */ + credentials?: AuthCredentials; + /** + * (an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received + * via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + */ + artifacts?: object; + /** + * sets the initial value of request.app, defaults to {}. + */ + app?: ApplicationState; + /** + * sets the initial value of request.plugins, defaults to {}. + */ + plugins?: PluginsStates; + /** + * allows access to routes with config.isInternal set to true. Defaults to false. + */ + allowInternals?: boolean; +} + +/** + * A response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of + * the internal objects returned (instead of parsing the response string). + * * request - the request object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectResponse extends Shot.ResponseObject { + /** + * the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the + * internal objects returned (instead of parsing the response string). + */ + result: object | undefined; + /** + * the request object. + */ + request: Request; +} + +/** + * The method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export type ServerMethod = (...args: any[]) => any; + +/** + * The same cache configuration used in server.cache(). + * The generateTimeout option is required. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerMethodCache extends PolicyOptions { + generateTimeout: number | false; +} + +/** + * Configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an + * arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically + * generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided + * which takes the same arguments as the function and returns a unique string (or null if no key can be generated). For reference [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export interface ServerMethodOptions { + /** + * a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow + * function. + */ + bind?: object; + /** + * the same cache configuration used in server.cache(). The generateTimeout option is required. + */ + cache?: ServerMethodCache; + /** + * a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a + * unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which + * takes the same arguments as the function and returns a unique string (or null if no key can be generated). + */ + generateKey?(...args: any[]): string | null; +} + +/** + * An object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ +export interface ServerMethodConfigurationObject { + /** + * the method name. + */ + name: string; + /** + * the method function. + */ + method: ServerMethod; + /** + * (optional) settings. + */ + options?: ServerMethodOptions; +} + +/** + * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, + * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) + */ +export interface ServerOptionsCache extends PolicyOptions { + /** a class, a prototype function, or a catbox engine object. */ + engine?: EnginePrototypeOrObject; + + /** + * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines + * the default cache. If every cache includes a name, a default memory cache is provisioned as well. + */ + name?: string; + + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; + + /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */ + partition?: string; + + /** other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). */ + [s: string]: any; +} + +export interface ServerOptionsCompression { + minBytes: number; +} + +/** + * Empty interface to allow for custom augmentation. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerOptionsApp { +} + +/** + * The server options control the behavior of the server object. Note that the options object is deeply cloned + * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. + * All options are optionals. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options) + */ +export interface ServerOptions { + /** + * Default value: '0.0.0.0' (all available network interfaces). + * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to + * restrict the server to only those coming from the same host. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress) + */ + address?: string; + + /** + * Default value: {}. + * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available + * anywhere a server reference is provided. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time + * state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) + */ + app?: ServerOptionsApp; + + /** + * Default value: true. + * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. + * Cannot be set to true along with a port value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten) + */ + autoListen?: boolean; + + /** + * Default value: { engine: require('catbox-memory' }. + * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and + * capabilities. hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized + * if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. The configuration can be assigned one or more + * (array): + * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this + * function. + * * a configuration object with the following: + * * * engine - a class, a prototype function, or a catbox engine object. + * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines + * the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. + * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) + */ + cache?: EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; + + /** + * Default value: { minBytes: 1024 }. + * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server. + */ + compression?: boolean | ServerOptionsCompression; + + /** + * Default value: { request: ['implementation'] }. + * Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to false to + * disable all console logging, or to an object with: + * * log - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. Defaults to no output. + * * request - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to + * display all errors, set the option to ['error']. To turn off all console debug messages set it to false. To display all request logs, set it to '*'. Defaults to uncaught errors thrown in + * external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. For example, to display all errors, set the log + * or request to ['error']. To turn off all output set the log or request to false. To display all server logs, set the log or request to '*'. To disable all debug information, set debug to + * false. + */ + debug?: false | { + log?: string[] | false; + request?: string[] | false; + }; + + /** + * Default value: the operating system hostname and if not available, to 'localhost'. + * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided. + */ + host?: string; + + /** + * Default value: none. + * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface). + * If the listener needs to be manually started, set autoListen to false. + * If the listener uses TLS, set tls to true. + */ + listener?: http.Server; + + /** + * Default value: { sampleInterval: 0 }. + * Server excessive load handling limits where: + * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). + * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + */ + load?: { + /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */ + sampleInterval?: number; + + /** + * Max concurrent requests. + */ + concurrent?: number; + + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes?: number; + /** + * maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + */ + maxRssBytes?: number; + /** + * maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. + * Defaults to 0 (no limit). + */ + maxEventLoopDelay?: number; + }; + + /** + * Default value: none. + * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime): + * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain: + * * key - the lower-cased mime-type string (e.g. 'application/javascript'). + * * value - an object following the specifications outlined here. Additional values include: + * * * type - specify the type value of result objects, defaults to key. + * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime) + */ + mime?: MimosOptions; + + /** + * Default value: {}. + * Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the + * difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. + */ + plugins?: PluginSpecificConfiguration; + + /** + * Default value: 0 (an ephemeral port). + * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port). + * If port is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\.\pipe', it is used as a Windows named pipe. + */ + port?: number | string; + + /** + * Default value: { isCaseSensitive: true, stripTrailingSlash: false }. + * Controls how incoming request URIs are matched against the routing table: + * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. + * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false. + */ + router?: { + isCaseSensitive?: boolean; + stripTrailingSlash?: boolean; + }; + + /** + * Default value: none. + * A route options object used as the default configuration for every route. + */ + routes?: RouteOptions; + + /** + * Default value: + * { + * strictHeader: true, + * ignoreErrors: false, + * isSecure: true, + * isHttpOnly: true, + * isSameSite: 'Strict', + * encoding: 'none' + * } + * Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object. + */ + // TODO I am not sure if I need to use all the server.state() definition (like the default value) OR only the options below. The v16 use "any" here. + // state?: ServerStateCookieOptions; + state?: { + strictHeader?: boolean, + ignoreErrors?: boolean, + isSecure?: boolean, + isHttpOnly?: boolean, + isSameSite?: false | 'Strict' | 'Lax', + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron' + }; + + /** + * Default value: none. + * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation. + */ + tls?: boolean | https.ServerOptions; + + /** + * Default value: constructed from runtime server information. + * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. + */ + uri?: string; +} + +/** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided + * with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. For example, a plugin can set a + * default file path for local resources without breaking other plugins' configured paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by routes + * and extensions added at the same level (server root or plugin). + * + * https://github.com/hapijs/hapi/blob/master/API.md#server.realm + */ +export interface ServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ + modifiers: { + /** routes preferences: */ + route: { + /** + * the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include + * the trailing slash. + */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + } + }; + /** the realm of the parent server object, or null for the root server. */ + parent: ServerRealm | null; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** the plugin options object passed at registration. */ + pluginOptions: object; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: PluginsStates; + /** settings overrides */ + settings: { + files: { + relativeTo: string; + }; + bind: object; + }; +} + +/** + * Registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific + * prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ +export interface ServerRegisterOptions { + /** + * if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second + * time a plugin is registered on the server. + */ + once?: boolean; + /** + * modifiers applied to each route added by the plugin: + */ + routes?: { + /** + * string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + */ + prefix: string; + /** + * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + */ + vhost?: string | string[]; + }; +} + +/** + * An object with the following: + * * plugin - a plugin object. + * * options - (optional) options passed to the plugin during registration. + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific + * prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + * + * The type parameter T is the type of the plugin configuration options. + */ +export interface ServerRegisterPluginObject extends ServerRegisterOptions { + /** + * a plugin object. + */ + plugin: Plugin; + /** + * options passed to the plugin during registration. + */ + options?: T; +} + +export interface ServerRegisterPluginObjectArray extends Array + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | undefined> { + 0: ServerRegisterPluginObject; + 1?: ServerRegisterPluginObject; + 2?: ServerRegisterPluginObject; + 3?: ServerRegisterPluginObject; + 4?: ServerRegisterPluginObject; + 5?: ServerRegisterPluginObject; + 6?: ServerRegisterPluginObject; +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface HandlerDecorations { +} + +/** + * A route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The + * path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP + * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same + * result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the + * header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being + * added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ +export interface ServerRoute { + /** + * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path + * can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters) + */ + path: string; + + /** + * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method + * (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same + * result as adding the same route with different methods manually. + */ + method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[]; + + /** + * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header + * only (excluding the port). Defaults to all hosts. + */ + vhost?: string | string[]; + + /** + * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + */ + handler?: Lifecycle.Method | HandlerDecorations; + + /** + * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to + * and this is bound to the current realm's bind option. + */ + options?: RouteOptions | ((server: Server) => RouteOptions); + + /** + * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + */ + rules?: object; +} + +/** + * Optional cookie settings + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ +export interface ServerStateCookieOptions { + /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ + ttl?: number | null; + /** sets the 'Secure' flag. Defaults to true. */ + isSecure?: boolean; + /** sets the 'HttpOnly' flag. Defaults to true. */ + isHttpOnly?: boolean; + /** + * sets the 'SameSite' flag. The value must be one of: + * * false - no flag. + * * 'Strict' - sets the value to 'Strict' (this is the default value). + * * 'Lax' - sets the value to 'Lax'. + */ + isSameSite?: false | 'Strict' | 'Lax'; + /** the path scope. Defaults to null (no path). */ + path?: string | null; + /** the domain scope. Defaults to null (no domain). */ + domain?: string | null; + + /** + * if present and the cookie was not received from the client or explicitly set by the route handler, the + * cookie is automatically added to the response with the provided value. The value can be + * a function with signature async function(request) where: + */ + autoValue?(request: Request): void; + + /** + * encoding performs on the provided value before serialization. Options are: + * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + * * 'base64' - string value is encoded using Base64. + * * 'base64json' - object value is JSON-stringified then encoded using Base64. + * * 'form' - object value is encoded using the x-www-form-urlencoded method. + * * 'iron' - Encrypts and sign the value using iron. + */ + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; + /** + * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean + * to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: + * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. + * * password - password used for HMAC key generation (must be at least 32 characters long). + */ + sign?: { + integrity?: SealOptionsSub; + password: string; + }; + /** password used for 'iron' encoding (must be at least 32 characters long). */ + password?: string; + /** options for 'iron' encoding. Defaults to require('iron').defaults. */ + iron?: SealOptions; + /** if true, errors are ignored and treated as missing cookies. */ + ignoreErrors?: boolean; + /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ + clearInvalid?: boolean; + /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ + strictHeader?: boolean; + /** used by proxy plugins (e.g. h2o2). */ + passThrough?: any; +} + +/** + * A single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + */ +export interface ServerStateFormat { + name: string; + value: string; + options: ServerStateCookieOptions; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate) + */ +export interface ServerState { + /** + * The server cookies manager. + * Access: read only and statehood public interface. + */ + readonly states: object; + + /** + * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). + */ + readonly settings: ServerStateCookieOptions; + + /** + * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the + * cookie name and value is the configuration object. + */ + readonly cookies: { + [key: string]: ServerStateCookieOptions; + }; + + /** + * An array containing the names of all configued cookies. + */ + readonly names: string[]; + + /** + * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). + */ + add(name: string, options?: ServerStateCookieOptions): void; + + /** + * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: + * @param cookies - a single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + * @return Return value: a header string. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) + */ + format(cookies: ServerStateFormat | ServerStateFormat[]): Promise; + + /** + * Parses an HTTP 'Cookies' header based on the server.options.state where: + * @param header - the HTTP header. + * @return Return value: an object where each key is a cookie name and value is the parsed cookie. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) + */ + parse(header: string): Promise>; +} + +/** + * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. + * If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + */ +export interface HandlerDecorationMethod { + (route: RouteOptions, options: any): Lifecycle.Method; + defaults?: RouteOptions | ((method: any) => RouteOptions); +} + +/** + * The general case for decorators added via server.decorate. + */ +export type DecorationMethod = (this: T, ...args: any[]) => any; + +/** + * An empty interface to allow typings of custom plugin properties. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginProperties { +} + +export type DecorateName = string | symbol; + +/** + * The server object is the main application container. The server manages all incoming requests along with all + * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) + */ +export class Server { + /** + * Creates a new server object + * @param options server configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) + */ + constructor(options?: ServerOptions); + + /** + * Provides a safe place to store server-specific run-time application data without potential conflicts with + * the framework internals. The data can be accessed whenever the server is accessible. + * Initialized with an empty object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) + */ + app: ApplicationState; + + /** + * Server Auth: properties and methods + */ + readonly auth: ServerAuth; + + /** + * Links another server to the initialize/start/stop state of the current server by calling the + * controlled server `initialize()`/`start()`/`stop()` methods whenever the current server methods + * are called, where: + */ + control(server: Server): void; + + /** + * Provides access to the decorations already applied to various framework interfaces. The object must not be + * modified directly, but only through server.decorate. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations) + */ + readonly decorations: { + /** + * decorations on the request object. + */ + request: string[], + /** + * decorations on the response toolkit. + */ + toolkit: string[], + /** + * decorations on the server object. + */ + server: string[] + }; + + /** + * Register custom application events where: + * @param events must be one of: + * * an event name string. + * * an event options object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). + * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is + * passed as-is). + * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override + * specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its + * type). + * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is + * appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only + * the first configuration is used. Defaults to false (a duplicate registration will throw an error). + * * a podium emitter object. + * * an array containing any of the above. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + event(events: ServerEventsApplication | ServerEventsApplication[]): void; + + /** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + events: ServerEvents; + + /** + * An object containing information about the server where: + * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + * * created - server creation timestamp. + * * started - server start timestamp (0 when stopped). + * * port - the connection port based on the following rules: + * * host - The host configuration value. + * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). + * * protocol - the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available + * settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + */ + readonly info: ServerInfo; + + /** + * Access: read only and listener public interface. + * The node HTTP server object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener) + */ + listener: http.Server; + + /** + * An object containing the process load metrics (when load.sampleInterval is enabled): + * * eventLoopDelay - event loop delay milliseconds. + * * heapUsed - V8 heap usage. + * * rss - RSS memory usage. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload) + */ + readonly load: { + /** + * event loop delay milliseconds. + */ + eventLoopDelay: number; + + /** + * Max concurrent requests. + */ + concurrent: number + /** + * V8 heap usage. + */ + heapUsed: number; + /** + * RSS memory usage. + */ + rss: number; + }; + + /** + * Server methods are functions registered with the server and used throughout the application as a common utility. + * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request + * handlers without having to create a common module. + * sever.methods is an object which provides access to the methods registered via server.method() where each + * server method name is an object property. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods + */ + readonly methods: Util.Dictionary; + + /** + * Provides access to the server MIME database used for setting content-type information. The object must not be + * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) + */ + mime: any; + + /** + * An object containing the values exposed by each registered plugin where each key is a plugin name and the values + * are the exposed properties by each plugin using server.expose(). Plugins may set the value of + * the server.plugins[name] object directly or via the server.expose() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) + */ + plugins: PluginProperties; + + /** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When + * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm + * container specific to that registration. It allows each plugin to maintain its own settings without leaking + * and affecting other plugins. + * For example, a plugin can set a default file path for local resources without breaking other plugins' configured + * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by + * routes and extensions added at the same level (server root or plugin). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) + */ + readonly realm: ServerRealm; + + /** + * An object of the currently registered plugins where each key is a registered plugin name and the value is + * an object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ + readonly registrations: PluginsListRegistered; + + /** + * The server configuration object after defaults applied. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings) + */ + readonly settings: ServerOptions; + + /** + * The server cookies manager. + * Access: read only and statehood public interface. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates) + */ + readonly states: ServerState; + + /** + * A string indicating the listener type where: + * * 'socket' - UNIX domain socket or Windows named pipe. + * * 'tcp' - an HTTP listener. + */ + readonly type: 'socket' | 'tcp'; + + /** + * The hapi module version number. + */ + readonly version: string; + + /** + * Sets a global context used as the default bind object when adding a route or an extension where: + * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. + * @return Return value: none. + * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + * Ignored if the method being bound is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) + */ + bind(context: object): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + cache: ServerCache; + + /** + * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the decoder name string. + * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the + * return value is an object compatible with the output of node's zlib.createGunzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) + */ + decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; + + /** + * Extends various framework interfaces with custom methods where: + * @param type - the interface being decorated. Supported types: + * 'handler' - adds a new handler type to be used in routes handlers. + * 'request' - adds methods to the Request object. + * 'server' - adds methods to the Server object. + * 'toolkit' - adds methods to the response toolkit. + * @param property - the object decoration key name. + * @param method - the extension function or other value. + * @param options - (optional) supports the following optional settings: + * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned + * as the decoration. extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: existing - is the previously set + * decoration method value. must return the new decoration function or value. cannot be used to extend handler decorations. + * @return void; + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) + */ + decorate(type: 'handler', property: DecorateName, method: HandlerDecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'request', property: DecorateName, method: (existing: ((...args: any[]) => any)) => (request: Request) => DecorationMethod, options: {apply: true, extend: true}): void; + decorate(type: 'request', property: DecorateName, method: (request: Request) => DecorationMethod, options: {apply: true, extend?: boolean}): void; + decorate(type: 'request', property: DecorateName, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'toolkit', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean, extend: true}): void; + decorate(type: 'toolkit', property: DecorateName, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'server', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean, extend: true}): void; + decorate(type: 'server', property: DecorateName, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + + /** + * Used within a plugin to declare a required dependency on other plugins where: + * @param dependencies - plugins which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is + * initialized or started. + * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is + * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on. + * @return Return value: none. + * The after method is identical to setting a server extension point on 'onPreStart'. + * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). + * The method does not provide version dependency which should be implemented using npm peer dependencies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) + */ + dependency(dependencies: Dependencies, after?: ((server: Server) => Promise)): void; + + /** + * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the encoder name string. + * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object + * compatible with the output of node's zlib.createGzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ + encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void; + + /** + * Used within a plugin to expose a property via server.plugins[name] where: + * @param key - the key assigned (server.plugins[name][key]). + * @param value - the value assigned. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) + */ + expose(key: string, value: any): void; + + /** + * Merges an object into to the existing content of server.plugins[name] where: + * @param obj - the object merged into the exposed properties container. + * @return Return value: none. + * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method + * for exposing large objects that may be expensive to clone or singleton objects such as database client + * objects. Instead favor server.expose(key, value), which only copies a reference to value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) + */ + expose(obj: object): void; + + /** + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level + * extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ + ext(events: ServerExtEventsObject | ServerExtEventsObject[] | ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; + + /** + * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) + */ + ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions): void; + ext(event: ServerRequestExtType, method: Lifecycle.Method, options?: ServerExtOptions): void; + + /** + * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and + * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and + * other event listeners will get confused by repeated attempts to start the server or make assumptions about the + * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. + * If you must try to resume after an error, call server.stop() first to reset the server state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) + */ + initialize(): Promise; + + /** + * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic + * internally without the overhead and limitations of the network stack. The method utilizes the shot module for performing injections, with some additional options and response properties: + * @param options - can be assigned a string with the requested URI, or an object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload + * processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as + * if they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly + * as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested + * separately. + * @return Return value: a response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse + * of the internal objects returned (instead of parsing the response string). + * * request - the request object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + */ + inject(options: string | ServerInjectOptions): Promise; + + /** + * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or + * output to the console. The arguments are: + * @param tags - (required) a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive + * mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return + * value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) + */ + log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void; + + /** + * Looks up a route configuration where: + * @param id - the route identifier. + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid) + */ + lookup(id: string): RequestRoute | null; + + /** + * Looks up a route configuration where: + * @param method - the HTTP method (e.g. 'GET', 'POST'). + * @param path - the requested path (must begin with '/'). + * @param host - (optional) hostname (to match against routes with vhost). + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) + */ + match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null; + + /** + * Registers a server method where: + * @param name - a unique method name used to invoke the method via server.methods[name]. + * @param method - the method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * @param options - (optional) configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is + * an arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will + * automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation + * function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + * @return Return value: none. + * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get). + * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear + * the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + + /** + * Registers a server method function as described in server.method() using a configuration object where: + * @param methods - an object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ + method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void; + + /** + * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + * @param relativeTo - the path prefix added to any relative file path starting with '.'. + * @return Return value: none. + * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The + * path only applies to routes added after it has been set. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto) + */ + path(relativeTo: string): void; + + /** + * Registers a plugin where: + * @param plugins - one or an array of: + * * a plugin object. + * * an object with the following: + * * * plugin - a plugin object. + * * * options - (optional) options passed to the plugin during registration. + * * * once, routes - (optional) plugin-specific registration options as defined below. + * @param options - (optional) registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the + * child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ + /* tslint:disable-next-line:no-unnecessary-generics */ + register(plugin: ServerRegisterPluginObject, options?: ServerRegisterOptions): Promise; + /* tslint:disable-next-line:no-unnecessary-generics */ + register(plugins: ServerRegisterPluginObjectArray, options?: ServerRegisterOptions): Promise; + register(plugins: Array>, options?: ServerRegisterOptions): Promise; + /* tslint:disable-next-line:unified-signatures */ + register(plugins: Plugin | Array>, options?: ServerRegisterOptions): Promise; + + /** + * Adds a route where: + * @param route - a route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. + * The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP + * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has + * the same result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the + * header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being + * added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * @return Return value: none. + * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ + route(route: ServerRoute | ServerRoute[]): void; + + /** + * Defines a route rules processor for converting route rules object into route configuration where: + * @param processor - a function using the signature function(rules, info) where: + * * rules - + * * info - an object with the following properties: + * * * method - the route method. + * * * path - the route path. + * * * vhost - the route virtual host (if any defined). + * * returns a route config object. + * @param options - optional settings: + * * validate - rules object validation: + * * * schema - joi schema. + * * * options - optional joi validation options. Defaults to { allowUnknown: true }. + * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. + * Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated + * by the root processor if they overlap. The route config overrides the rules config if the overlap. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) + */ + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options?: {validate: object}): void; // TODO needs implementation + + /** + * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the + * various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is + * recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. If a started server + * is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart) + */ + start(): Promise; + + /** + * HTTP state management uses client cookies to persist a state across multiple requests. + * @param name - the cookie name string. + * @param options - are the optional cookie settings + * @return Return value: none. + * State defaults can be modified via the server default state configuration option. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ + state(name: string, options?: ServerStateCookieOptions): void; + + /** + * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + * @param options - (optional) object with: + * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) + */ + stop(options?: {timeout: number}): Promise; + + /** + * Returns a copy of the routing table where: + * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + * @return Return value: an array of routes where each route contains: + * * settings - the route config with defaults applied. + * * method - the HTTP method in lower case. + * * path - the route path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) + */ + table(host?: string): RequestRoute[]; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Utils + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * User-extensible type for application specific state. + */ + /* tslint:disable-next-line:no-empty-interface */ +export interface ApplicationState { +} + +export type PeekListener = (chunk: string, encoding: string) => void; + +export namespace Json { + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + type StringifyReplacer = ((key: string, value: any) => any) | Array<(string | number)> | undefined; + + /** + * Any value greater than 10 is truncated. + */ + type StringifySpace = number | string; + + /** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + /* string suffix added after conversion to JSON string. Defaults to no suffix. */ + suffix?: string; + /* calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. */ + escape?: boolean; + } +} + +export namespace Lifecycle { + /** + * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: + * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods + * provided by the developer and executed by the framework. + * Each lifecycle method is a function with the signature await function(request, h, [err]) where: + * * request - the request object. + * * h - the response toolkit the handler must call to set a response and return control back to the framework. + * * err - an error object availble only when the method is used as a failAction value. + */ + type Method = (request: Request, h: ResponseToolkit, err?: Error) => ReturnValue; + + /** + * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns + * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. + * The return value must be one of: + * - Plain value: null, string, number, boolean + * - Buffer object + * - Error object: plain Error OR a Boom object. + * - Stream object + * - any object or array + * - a toolkit signal: + * - a toolkit method response: + * - a promise object that resolve to any of the above values + * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + */ + type ReturnValue = ReturnValueTypes | (Promise); + type ReturnValueTypes = + (null | string | number | boolean) | + (Buffer) | + (Error | Boom) | + (stream.Stream) | + (object | object[]) | + symbol | + ResponseToolkit; + + /** + * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be + * configured to perform another action. When supported the failAction option supports the following values: + * * 'error' - return the error object as the response. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action and continue processing the request. + * * a lifecycle method with the signature async function(request, h, err) where: + * * * request - the request object. + * * * h - the response toolkit. + * * * err - the error object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) + */ + type FailAction = 'error' | 'log' | 'ignore' | Method; +} + +export namespace Util { + interface Dictionary { + [key: string]: T; + } + + type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; + type HTTP_METHODS_PARTIAL = + 'GET' + | 'POST' + | 'PUT' + | 'PATCH' + | 'DELETE' + | 'OPTIONS' + | HTTP_METHODS_PARTIAL_LOWERCASE; + type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; +} diff --git a/types/hapi/v17/test/request/auth.ts b/types/hapi/v17/test/request/auth.ts new file mode 100644 index 0000000000..cb6c04ad28 --- /dev/null +++ b/types/hapi/v17/test/request/auth.ts @@ -0,0 +1,18 @@ +import { Request } from 'hapi'; + +declare module 'hapi' { + interface UserCredentials { + a: number; + } + + interface AppCredentials { + b: number; + } +} + +const req: Request = {} as any; +const scope: string[] | undefined = req.auth.credentials.scope; +const user = req.auth.credentials.user!; +console.log(user.a); +const app = req.auth.credentials.app!; +console.log(app.b); diff --git a/types/hapi/v17/test/request/catch-all.ts b/types/hapi/v17/test/request/catch-all.ts new file mode 100644 index 0000000000..3ee4e74c42 --- /dev/null +++ b/types/hapi/v17/test/request/catch-all.ts @@ -0,0 +1,14 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route +import { Request, ResponseToolkit, Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; +const server = new Server(options); + +server.route({ method: '*', path: '/{p*}', handler(request, h) { + return h.response('The page was not found').code(404); +}}); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/request/event-types.ts b/types/hapi/v17/test/request/event-types.ts new file mode 100644 index 0000000000..4d4f3f01ca --- /dev/null +++ b/types/hapi/v17/test/request/event-types.ts @@ -0,0 +1,67 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +// https://github.com/hapijs/hapi/blob/master/API.md#-requestevents +import { Lifecycle, Request, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Crypto from 'crypto'; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request) { + return 'ok: ' + request.path; + } +}; + +const onRequest: Lifecycle.Method = (request, h) => { + /* + * Server events + */ + request.server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(request.paramsArray); + console.log(event); + console.log(tags); + }); + + request.server.events.on('response', (request: Request) => { + console.log('Response sent for request: ' + request.path); + }); + + request.server.events.on('start', () => { + console.log('Server started'); + }); + + request.server.events.once('stop', () => { + console.log('Server stoped'); + }); + + /* + * Request events + */ + const hash = Crypto.createHash('sha1'); + + request.events.on("peek", (chunk) => { + hash.update(chunk); + }); + + request.events.once("finish", () => { + console.log(hash.digest('hex')); + }); + + request.events.once("disconnect", () => { + console.error('request aborted'); + }); + + return h.continue; +}; + +const server = new Server(options); +server.route(serverRoute); +server.ext('onRequest', onRequest, { + before: 'test', +}); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/request/get-log.ts b/types/hapi/v17/test/request/get-log.ts new file mode 100644 index 0000000000..3ba2658136 --- /dev/null +++ b/types/hapi/v17/test/request/get-log.ts @@ -0,0 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data +import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const handlerFn: Lifecycle.Method = (request, h) => { + request.log(['test', 'error'], 'Test event'); + return 'path: ' + request.path; +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handlerFn +}; + +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); + +server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(tags); + if (tags.error) { + console.log(event); + } +}); diff --git a/types/hapi/v17/test/request/methods.ts b/types/hapi/v17/test/request/methods.ts new file mode 100644 index 0000000000..22b58aac7f --- /dev/null +++ b/types/hapi/v17/test/request/methods.ts @@ -0,0 +1,4 @@ +import { Request } from 'hapi'; + +declare const req: Request; +const act: boolean = req.active(); diff --git a/types/hapi/v17/test/request/parameters.ts b/types/hapi/v17/test/request/parameters.ts new file mode 100644 index 0000000000..3f19a02d45 --- /dev/null +++ b/types/hapi/v17/test/request/parameters.ts @@ -0,0 +1,37 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-requestparams +import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +// Example 1 +// http://localhost:8000/album-name/song-optional +const getAlbum: Lifecycle.Method = (request, h) => { + console.log(request.params); + return 'ok: ' + request.path; +}; +const serverRoute1: ServerRoute = { + path: '/{album}/{song?}', + method: 'GET', + handler: getAlbum +}; + +// Example 2 +// http://localhost:8000/person/rafael/fijalkowski +const getPerson: Lifecycle.Method = (request, h) => { + const nameParts = request.params.name.split('/'); + return { first: nameParts[0], last: nameParts[1] }; +}; +const serverRoute2: ServerRoute = { + path: '/person/{name*2}', + method: 'GET', + handler: getPerson +}; + +const server = new Server(options); +server.route(serverRoute1); +server.route(serverRoute2); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/request/query.ts b/types/hapi/v17/test/request/query.ts new file mode 100644 index 0000000000..090ab3ae8d --- /dev/null +++ b/types/hapi/v17/test/request/query.ts @@ -0,0 +1,26 @@ +// Added test in addition to docs, for request.query +import { Lifecycle, Request, RequestQuery, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const handlerFn: Lifecycle.Method = (request, h) => { + const query1 = request.query as string; + console.log(query1); + + const query2 = request.query as RequestQuery; + // http://localhost:8000/?name=test + return `You asked for ${query2.name}`; +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handlerFn +}; + +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/continue.ts b/types/hapi/v17/test/response/continue.ts new file mode 100644 index 0000000000..15a0f5e35b --- /dev/null +++ b/types/hapi/v17/test/response/continue.ts @@ -0,0 +1,25 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/test', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } +}; + +const server = new Server(options); +server.route(serverRoute); + +server.ext("onRequest", (request, h) => { + request.setUrl('/test'); + return h.continue; +}); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/error.ts b/types/hapi/v17/test/response/error.ts new file mode 100644 index 0000000000..513f5fbbe5 --- /dev/null +++ b/types/hapi/v17/test/response/error.ts @@ -0,0 +1,30 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#errors +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Boom from "boom"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoutes: ServerRoute[] = [ + { + path: '/badRequest', + method: 'GET', + handler(request, h) { + throw Boom.badRequest('Unsupported parameter'); + } + }, + { + path: '/internal', + method: 'GET', + handler(request, h) { + throw new Error('unexpect error'); + } + }, +]; + +const server = new Server(options); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/redirect.ts b/types/hapi/v17/test/response/redirect.ts new file mode 100644 index 0000000000..dc1b904ce3 --- /dev/null +++ b/types/hapi/v17/test/response/redirect.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return h.redirect('http://example.com'); + } +}; + +const server = new Server(options); +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/response-events.ts b/types/hapi/v17/test/response/response-events.ts new file mode 100644 index 0000000000..ec1b070b18 --- /dev/null +++ b/types/hapi/v17/test/response/response-events.ts @@ -0,0 +1,28 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-responseevents +import { Lifecycle, Request, ResponseObject, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Crypto from "crypto"; + +const preResponse: Lifecycle.Method = (request, h) => { + // In onPreResponse, the response object will be defined. + const response = request.response!; + + const hash = Crypto.createHash('sha1'); + response.events.on('peek', (chunk, encoding) => { + hash.update(chunk); + }); + + response.events.once('finish', () => { + console.log(hash.digest('hex')); + }); + + return h.continue; +}; + +const server = new Server({ + port: 8000, +}); + +server.ext('onPreResponse', preResponse); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/response.ts b/types/hapi/v17/test/response/response.ts new file mode 100644 index 0000000000..368b6fa80b --- /dev/null +++ b/types/hapi/v17/test/response/response.ts @@ -0,0 +1,36 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoutes: ServerRoute[] = [ + // Detailed notation + { + path: '/test1', + method: 'GET', + handler(request, h) { + const response = h.response('success'); + response.type('text/plain'); + response.header('X-Custom', 'some-value'); + return response; + } + }, + // Chained notation + { + path: '/test2', + method: 'GET', + handler(request, h) { + return h.response('success') + .type('text/plain') + .header('X-Custom', 'some-value'); + } + }, +]; + +const server = new Server(options); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/route/adding-routes.ts b/types/hapi/v17/test/route/adding-routes.ts new file mode 100644 index 0000000000..ac4c895842 --- /dev/null +++ b/types/hapi/v17/test/route/adding-routes.ts @@ -0,0 +1,38 @@ +// from https://hapijs.com/tutorials/getting-started#adding-routes +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } +}; + +const serverRoutes: ServerRoute[] = [ + { + path: '/test1', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } + }, + { + path: '/test2', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } + }, +]; + +const server = new Server(options); +server.route(serverRoute); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/route/config.ts b/types/hapi/v17/test/route/config.ts new file mode 100644 index 0000000000..8cebaec269 --- /dev/null +++ b/types/hapi/v17/test/route/config.ts @@ -0,0 +1,52 @@ +import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +// different methods +const routeConfig: ServerRoute = { + path: '/signin', + method: 'PUT', + vhost: 'site.coms', +}; +const routeConfigTest1: ServerRoute = { + path: '/signin', + method: '*' +}; +const routeConfigTest2: ServerRoute = { + path: '/signin', + method: ['OPTIONS', '*'] +}; + +// different handlers +const routeConfigTest3: ServerRoute = { + path: '/signin', + method: 'PUT', + handler(request, h) { + return 'ok'; + } +}; +const routeConfigTest4: ServerRoute = { + path: '/signin', + method: 'PUT', + handler(request, h) { + return 'ok'; + } +}; + +const server = new Server(options); +server.route(routeConfig); + +// Handler in config +const user: RouteOptions = { + cache: { expiresIn: 5000 }, + handler(request, h) { + return { name: 'John' }; + } +}; + +server.route({method: 'GET', path: '/user', options: user }); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/route/ext.ts b/types/hapi/v17/test/route/ext.ts new file mode 100644 index 0000000000..b8dff44699 --- /dev/null +++ b/types/hapi/v17/test/route/ext.ts @@ -0,0 +1,22 @@ +import { Server } from "hapi"; + +const server = new Server(); + +server.route({ + method: 'get', + path: "/test", + options: { + ext: { + onPreResponse: { + method(_request, h) { + return h.continue; + }, + }, + onPostHandler: [{ + method(_request, h) { + return h.continue; + }, + }], + } + } +}); diff --git a/types/hapi/v17/test/route/handler.ts b/types/hapi/v17/test/route/handler.ts new file mode 100644 index 0000000000..6fced10078 --- /dev/null +++ b/types/hapi/v17/test/route/handler.ts @@ -0,0 +1,9 @@ +import { Lifecycle, Request, ResponseToolkit } from "hapi"; + +const handler: Lifecycle.Method = (request, h) => { + return 'success'; +}; + +const strictHandler: Lifecycle.Method = (request, h) => { + return 123; +}; diff --git a/types/hapi/v17/test/route/route-options-pre.ts b/types/hapi/v17/test/route/route-options-pre.ts new file mode 100644 index 0000000000..897f4a8ef5 --- /dev/null +++ b/types/hapi/v17/test/route/route-options-pre.ts @@ -0,0 +1,42 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre +import { Lifecycle, Request, ResponseToolkit, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const pre1: Lifecycle.Method = (request, h) => { + return 'Hello'; +}; + +const pre2: Lifecycle.Method = (request, h) => { + return 'World'; +}; + +const pre3: Lifecycle.Method = (request, h) => { + return `request.pre.m1 request.pre.m2`; +}; + +server.route({ + method: 'GET', + path: '/', + options: { + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + handler(request, h) { + return request.pre.m3 + '!\n'; + } + } +}); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/route/route-options.ts b/types/hapi/v17/test/route/route-options.ts new file mode 100644 index 0000000000..438ef77d62 --- /dev/null +++ b/types/hapi/v17/test/route/route-options.ts @@ -0,0 +1,193 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#route-options +import { + Lifecycle, + Request, + ResponseToolkit, + RouteOptions, + RouteOptionsAccess, + RouteOptionsCors, + RouteOptionsPayload, + RouteOptionsResponse, + RouteOptionsValidate, + Server, + RouteOptionsSecureObject +} from "hapi"; + +const routeOptionsAccess: RouteOptionsAccess = { + access: [ + { + scope: false + }, + { + entity: 'user' + } + ], + scope: false, + entity: 'user', + mode: 'optional', + payload: 'optional', + strategies: ['', ''], + strategy: '' +}; + +const corsOption: RouteOptionsCors = { + origin: 'ignore', + maxAge: 5000, + headers: ['test', 'test', 'test'], + additionalHeaders: ['test', 'test', 'test'], + exposedHeaders: ['test', 'test', 'test'], + additionalExposedHeaders: ['test', 'test', 'test'], + credentials: false +}; + +const payloadOptions: RouteOptionsPayload = { + allow: 'string', + compression: { + test1: { + test: 2 + } + }, + defaultContentType: 'application/json', + failAction(request, h) { + return 'ok: ' + request.path; + }, + maxBytes: 1048576, + multipart: { + output: 'annotated' + }, + output: 'stream', + override: '', + parse: 'gunzip', + timeout: 5000, + uploads: 'dir/' +}; + +const pre1: Lifecycle.Method = (request, h) => { + return 'Hello'; +}; + +const pre2: Lifecycle.Method = (request, h) => { + return 'World'; +}; + +const pre3: Lifecycle.Method = (request, h) => { + return `request.pre.m1 request.pre.m2`; +}; + +const routeOptionsResponse: RouteOptionsResponse = { + emptyStatusCode: 200, + failAction(request, h) { + return 'ok: ' + request.path; + }, + modify: false, + options: undefined, + ranges: true, + sample: 100, + schema: true, + status: { + 200: true, + 302: true, + 404: false, + }, +}; + +const routeOptionSecure: RouteOptionsSecureObject = { + referrer: 'origin', + noSniff: true, + xframe: "deny", + hsts: { + includeSubdomains: true, + maxAge: 1111, + preload: false, + }, + noOpen: false, + xss: true, +}; + +const routeOptionsValidate: RouteOptionsValidate = { + errorFields: {}, + failAction(request, h) { + return 'ok: ' + request.path; + }, + headers: false, + options: {}, + params: false, + payload: true, + query: true, +}; + +declare module 'hapi' { + interface RouteOptionsApp { + one: number; + two: string; + } +} + +const routeOptions: RouteOptions = { + app: { + one: 1, + two: "2" + }, + auth: routeOptionsAccess, + bind: null, + cache: { + privacy: 'default', + statuses: [200], + otherwise: 'no-cache' + }, + compression: { + test1: { + test: 2 + } + }, + cors: corsOption, + description: 'description here', + ext: undefined, + files: { relativeTo: '.' }, + handler(request, h) { + return 'ok: ' + request.path; + }, + id: 'test', + isInternal: false, + json: undefined, + jsonp: 'callback', + log: { collect: false }, + notes: ['test', 'test', 'test'], + payload: payloadOptions, + plugins: { + plugin1: {}, + plugin2: {}, + }, + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + response: routeOptionsResponse, + security: false, + state: { + parse: true, + failAction(request, h) { + return 'ok: ' + request.path; + }, + }, + tags: ['test', 'test', 'test'], + timeout: { + server: 10000, + socket: false + }, + validate: routeOptionsValidate +}; + +const server = new Server({ + port: 8000, + routes: routeOptions +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/route/validation.ts b/types/hapi/v17/test/route/validation.ts new file mode 100644 index 0000000000..2151371c5f --- /dev/null +++ b/types/hapi/v17/test/route/validation.ts @@ -0,0 +1,48 @@ +// from https://hapijs.com/tutorials/validation?lang=en_US +import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Joi from "joi"; + +const options: ServerOptions = { + port: 8000, +}; + +const routeOptions: RouteOptions = { + validate: { + payload: { + id: Joi.string().uuid().required(), + name: Joi.object({ + firstName: Joi.string().required(), + lastName: Joi.string().allow(null) + }), + firstName: Joi.ref("name.firstName") + }, + params: { + name: Joi.string().min(3).max(10), + nameRef: Joi.ref("name") + } + }, + response: { + schema: Joi.object({ + a: Joi.string(), + b: Joi.object({ + c: Joi.number() + }), + d: Joi.ref("b.c") + }) + } +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + }, + options: routeOptions +}; + +const server = new Server(options); +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-app.ts b/types/hapi/v17/test/server/server-app.ts new file mode 100644 index 0000000000..69bac86e2f --- /dev/null +++ b/types/hapi/v17/test/server/server-app.ts @@ -0,0 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverapp +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +declare module "hapi" { + // Demonstrate augmenting the application state. + interface ApplicationState { + key?: string; + } +} + +const server = new Server(options); +server.app.key = 'value2'; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'key: ' + request.server.app.key; + } +}; + +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-auth-api.ts b/types/hapi/v17/test/server/server-auth-api.ts new file mode 100644 index 0000000000..4508c641c9 --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-api.ts @@ -0,0 +1,40 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi +import { + Server, + ServerAuthScheme, +} from "hapi"; +import * as Boom from "boom"; + +declare module 'hapi' { + interface ServerAuthSchemeObjectApi { + settings: { + x: number; + }; + } +} + +const scheme: ServerAuthScheme = (server, options) => { + return { + api: { + settings: { + x: 5 + } + }, + authenticate(request, h) { + const authorization = request.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: { a: 1 } } }); + } + }; +}; + +const server = new Server({ + port: 8000, +}); +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.start(); + +console.log(server.auth.api.default.settings.x); // 5 diff --git a/types/hapi/v17/test/server/server-auth-default.ts b/types/hapi/v17/test/server/server-auth-default.ts new file mode 100644 index 0000000000..0a2da56efc --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-default.ts @@ -0,0 +1,41 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; +import * as Boom from "boom"; + +declare module 'hapi' { + interface UserCredentials { + a: number; + } +} + +const server = new Server({ + port: 8000, +}); + +const scheme: ServerAuthScheme = (server, options) => { + return { + authenticate(request, h) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: { a: 1 }, scope: ['test'] } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.auth.default('default'); + +server.route({ + method: 'GET', + path: '/', + handler(request, h) { + return request.auth.credentials.user || 'not authed'; + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-auth-test.ts b/types/hapi/v17/test/server/server-auth-test.ts new file mode 100644 index 0000000000..4e2a175e1a --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-test.ts @@ -0,0 +1,45 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; +import * as Boom from "boom"; + +declare module 'hapi' { + interface AuthCredentials { + name?: string; + } +} + +const server = new Server({ + port: 8000, +}); + +const scheme: ServerAuthScheme = (server, options) => { + return { + authenticate(request, h) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { name: 'john', } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + handler: async (request: Request, h: ResponseToolkit) => { + try { + const credentials = await request.server.auth.test('default', request); + return { status: true, user: credentials.name }; + } catch (err) { + return { status: false }; + } + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-auth-verify.ts b/types/hapi/v17/test/server/server-auth-verify.ts new file mode 100644 index 0000000000..ec788fcb59 --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-verify.ts @@ -0,0 +1,26 @@ +import { Request, Server, RequestAuth } from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +server.auth.scheme('custom', () => ({ + authenticate() { + throw Boom.unauthorized(null, 'hurr'); + }, + async verify(_auth: RequestAuth) { + throw Boom.unauthorized(null, 'durr'); + } +})); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + async handler(request: Request) { + request.server.auth.verify(request); + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-bind.ts b/types/hapi/v17/test/server/server-bind.ts new file mode 100644 index 0000000000..1fbd37c4c2 --- /dev/null +++ b/types/hapi/v17/test/server/server-bind.ts @@ -0,0 +1,27 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext +import { Lifecycle, Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions } from "hapi"; + +const server = new Server({ + port: 8000, +}); +const handler: Lifecycle.Method = (request, h) => { + return h.context.message; // Or h.context.message +}; + +const plugin: Plugin = { + name: 'example', + register: async (server, options) => { + const bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler }); + } +}; + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-cache-provision.ts b/types/hapi/v17/test/server/server-cache-provision.ts new file mode 100644 index 0000000000..8c28ca48de --- /dev/null +++ b/types/hapi/v17/test/server/server-cache-provision.ts @@ -0,0 +1,19 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions +import { Server } from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); +server.initialize(); +server.cache.provision({engine: require('catbox-memory'), name: 'countries' }); + +const cache = server.cache({segment: 'countries', cache: 'countries', expiresIn: 60 * 60 * 1000 }); +cache.set('norway', 'oslo', 10 * 1000).then(() => {}); +const value = cache.get('norway').then(() => {}); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-cache.ts b/types/hapi/v17/test/server/server-cache.ts new file mode 100644 index 0000000000..0872b287df --- /dev/null +++ b/types/hapi/v17/test/server/server-cache.ts @@ -0,0 +1,23 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions +import { Server, ServerOptionsCache } from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); + +const catboxOptions: ServerOptionsCache = { + segment: 'countries', + expiresIn: 60 * 60 * 1000 +}; +const cache = server.cache(catboxOptions); +cache.set('norway', 'oslo', 10 * 1000).then(() => {}); + +const value = cache.get('norway').then(() => {}); +console.log("Value: " + value); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-control.ts b/types/hapi/v17/test/server/server-control.ts new file mode 100644 index 0000000000..8b145f1388 --- /dev/null +++ b/types/hapi/v17/test/server/server-control.ts @@ -0,0 +1,3 @@ +import { Server } from "hapi"; + +new Server().control(new Server()); diff --git a/types/hapi/v17/test/server/server-decoder.ts b/types/hapi/v17/test/server/server-decoder.ts new file mode 100644 index 0000000000..965745ee7c --- /dev/null +++ b/types/hapi/v17/test/server/server-decoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder +import { Server } from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.decoder('special', (options) => Zlib.createGunzip(options)); + +server.start(); diff --git a/types/hapi/v17/test/server/server-decorations.ts b/types/hapi/v17/test/server/server-decorations.ts new file mode 100644 index 0000000000..7c060735a9 --- /dev/null +++ b/types/hapi/v17/test/server/server-decorations.ts @@ -0,0 +1,111 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options +import { Request, ResponseToolkit, Server } from "hapi"; + +declare module 'hapi' { + interface HandlerDecorations { + test?: { + test: number; + }; + } +} + +// Test basic types. + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.decorate('toolkit', 'success', function() { + return this.response({ status: 'ok' }); +}); +server.decorate('handler', 'test', (route, options) => (req, h) => 123); +server.route({ + method: 'GET', + path: '/', + handler: { + test: { + test: 123, + }, + asd: 1, + } +}); + +console.log(server.decorations.toolkit); + +// Test decorators with additional arguments + +declare module 'hapi' { + interface Server { + withParams(x: number, y: string): string; + } + + interface ResponseToolkit { + withParams(x: number, y: string): string; + } +} + +function decorateServerWithParams(this: Server, x: number, y: string) { + return `${x} ${y}`; +} + +server.decorate('server', 'withParams', decorateServerWithParams); +server.withParams(1, "one"); + +function decorateToolkitWithParams(this: ResponseToolkit, x: number, y: string) { + return `${x} ${y}`; +} + +server.decorate('toolkit', 'withParams', decorateToolkitWithParams); + +server.decorate('toolkit', Symbol('hi'), decorateToolkitWithParams); + +server.route({ + method: 'GET', + path: '/toolkitWithParams', + handler: (r, h) => { + return h.withParams(1, "one"); + } +}); + +// Test request + apply option types + +declare module 'hapi' { + interface Request { + withApply(x: string, y: number): string; + } +} + +function decorateRequestWithApply(request: Request) { + return (x: string, y: number) => { + return `${x} ${y}`; + }; +} + +server.decorate('request', 'withApply', decorateRequestWithApply, {apply: true}); + +server.route({ + method: 'GET', + path: '/requestWithApply', + handler: (r, h) => { + return r.withApply("one", 1); + } +}); + +// Test extend option type + +declare module 'hapi' { + interface Server { + withExtend(x: string, y: number): string; + } +} + +const decorateServerWithExtend = (existing: () => void) => { + return (x: string, y: number) => { + existing(); + return `${x} ${y}`; + }; +}; + +server.decorate('server', 'withExtend', decorateServerWithExtend, {extend: true}); +server.withExtend("one", 1); diff --git a/types/hapi/v17/test/server/server-encoder.ts b/types/hapi/v17/test/server/server-encoder.ts new file mode 100644 index 0000000000..dd9f12f4db --- /dev/null +++ b/types/hapi/v17/test/server/server-encoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder +import { Server } from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.encoder('special', (options) => Zlib.createGzip(options)); + +server.start(); diff --git a/types/hapi/v17/test/server/server-events-once.ts b/types/hapi/v17/test/server/server-events-once.ts new file mode 100644 index 0000000000..a4903ee6dc --- /dev/null +++ b/types/hapi/v17/test/server/server-events-once.ts @@ -0,0 +1,31 @@ +// from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener +import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'oks: ' + request.path; + } +}; + +declare module 'hapi' { + interface ServerEvents { + once(event: 'test1', listener: (update: string) => void): this; + once(event: 'test2', listener: (...updates: string[]) => void): this; + } +} + +const server = new Server({ + port: 8000, +}); +server.route(serverRoute); +server.event('test1'); +server.event('test2'); +server.events.once('test1', update => { console.log(update); }); +server.events.once('test2', (...args) => { console.log(args); }); +server.events.emit('test1', 'hello-1'); +server.events.emit('test2', 'hello-2'); // Ignored + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-events.ts b/types/hapi/v17/test/server/server-events.ts new file mode 100644 index 0000000000..4e6d8103f1 --- /dev/null +++ b/types/hapi/v17/test/server/server-events.ts @@ -0,0 +1,24 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +import { Server, ServerEvents } from "hapi"; +import Podium = require('podium'); +import 'hapi/definitions/server/server'; + +declare module 'hapi' { + interface ServerEvents { + on(event: 'test', listener: (update: string) => void): this; + } +} + +const server = new Server({ + port: 8000, +}); + +server.events.on('route', route => { + console.log(route.path, route.vhost, route.realm, route.method, route.settings, route.fingerprint); +}); + +server.event('test'); +server.events.on('test', (update: any) => console.log(update)); +server.events.emit('test', 'hello'); + +server.start(); diff --git a/types/hapi/v17/test/server/server-expose.ts b/types/hapi/v17/test/server/server-expose.ts new file mode 100644 index 0000000000..43d6cfdaa6 --- /dev/null +++ b/types/hapi/v17/test/server/server-expose.ts @@ -0,0 +1,38 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import { Plugin, Server, ServerRegisterOptions } from "hapi"; + +declare module 'hapi' { + interface PluginProperties { + example1: { + util(): void; + }; + example2: { + util(): void; + }; + } +} + +const plugin1: Plugin = { + name: 'example1', + async register(server: Server, options: ServerRegisterOptions) { + server.expose('util', () => console.log('something')); + } +}; + +const plugin2: Plugin = { + name: 'example2', + async register(server: Server, options: ServerRegisterOptions) { + server.expose('util', () => console.log('something')); + } +}; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.register(plugin1); +server.register(plugin2); + +server.plugins.example1.util(); +server.plugins.example2.util(); diff --git a/types/hapi/v17/test/server/server-info.ts b/types/hapi/v17/test/server/server-info.ts new file mode 100644 index 0000000000..58045b19da --- /dev/null +++ b/types/hapi/v17/test/server/server-info.ts @@ -0,0 +1,10 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +console.log(server.info); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-inject.ts b/types/hapi/v17/test/server/server-inject.ts new file mode 100644 index 0000000000..a2ae777a71 --- /dev/null +++ b/types/hapi/v17/test/server/server-inject.ts @@ -0,0 +1,32 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions +import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'Success!'; + } +}; + +server.route(serverRoute); +server.start(); + +server.inject('/').then(res => console.log(res.result)); + +declare module 'hapi' { + interface ApplicationState { + injectState?: number; + } +} + +server.inject({ + url: "test", + app: { + injectState: 1 + } +}); diff --git a/types/hapi/v17/test/server/server-listener.ts b/types/hapi/v17/test/server/server-listener.ts new file mode 100644 index 0000000000..160821f505 --- /dev/null +++ b/types/hapi/v17/test/server/server-listener.ts @@ -0,0 +1,14 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener +import { Server } from "hapi"; +import * as SocketIO from "socket.io"; + +const server = new Server({ + port: 8000, +}); + +const io = SocketIO.listen(server.listener); +io.sockets.on('connection', (socket) => { + socket.emit('welcome'); +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-load.ts b/types/hapi/v17/test/server/server-load.ts new file mode 100644 index 0000000000..8ac89fa006 --- /dev/null +++ b/types/hapi/v17/test/server/server-load.ts @@ -0,0 +1,17 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverload +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, + load: { + sampleInterval: 1000, + concurrent: 123, + } +}); +server.start(); + +setTimeout(() => { + console.log(server.load.rss); + console.log(server.load.eventLoopDelay); + console.log(server.load.heapUsed); +}, 5 * 1000); diff --git a/types/hapi/v17/test/server/server-lookup.ts b/types/hapi/v17/test/server/server-lookup.ts new file mode 100644 index 0000000000..2bbaf5713b --- /dev/null +++ b/types/hapi/v17/test/server/server-lookup.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid +import { RequestRoute, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + options: { + id: 'root', + handler: () => 'ok' + } +}); + +const route: RequestRoute | null = server.lookup('root'); +console.log(route); + +server.start(); diff --git a/types/hapi/v17/test/server/server-match.ts b/types/hapi/v17/test/server/server-match.ts new file mode 100644 index 0000000000..5fc8605ad4 --- /dev/null +++ b/types/hapi/v17/test/server/server-match.ts @@ -0,0 +1,23 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host +import { RequestRoute, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + options: { + id: 'root', + handler: () => 'ok' + } +}); + +const route: RequestRoute | null = server.match('get', '/'); + +if (route !== null) { + console.log(route.path); +} + +server.start(); diff --git a/types/hapi/v17/test/server/server-method.ts b/types/hapi/v17/test/server/server-method.ts new file mode 100644 index 0000000000..39c3fdb9d7 --- /dev/null +++ b/types/hapi/v17/test/server/server-method.ts @@ -0,0 +1,25 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods +import { Server, ServerMethodConfigurationObject } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +const add = (a: any, b: any): number => { + return a + b; +}; + +const methodObject: ServerMethodConfigurationObject = { + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000, + generateTimeout: 100 + }, + generateKey: (a: string | undefined) => a === undefined ? null : a + } +}; + +server.method(methodObject); diff --git a/types/hapi/v17/test/server/server-methods.ts b/types/hapi/v17/test/server/server-methods.ts new file mode 100644 index 0000000000..f9a2d08e6c --- /dev/null +++ b/types/hapi/v17/test/server/server-methods.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethods +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.method('add', (a, b) => (a + b)); +const result = server.methods.add(1, 2); // 3 +console.log(result); diff --git a/types/hapi/v17/test/server/server-mime.ts b/types/hapi/v17/test/server/server-mime.ts new file mode 100644 index 0000000000..3a50da2154 --- /dev/null +++ b/types/hapi/v17/test/server/server-mime.ts @@ -0,0 +1,22 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermime +import { Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } +}; + +const server = new Server(options); +console.log(server.mime.path('code.js').type); // 'application/javascript' +console.log(server.mime.path('file.npm').type); // 'node/module' + +server.start(); diff --git a/types/hapi/v17/test/server/server-options.ts b/types/hapi/v17/test/server/server-options.ts new file mode 100644 index 0000000000..f72f98a55e --- /dev/null +++ b/types/hapi/v17/test/server/server-options.ts @@ -0,0 +1,114 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-server-options +import { Plugin, RouteOptions, Server, ServerOptions, ServerRegisterOptions } from "hapi"; +import { MimosOptions, MimosOptionsValue } from "mimos"; + +const mimeOptions: MimosOptions = { + override: { + 'node/module': { + source: 'iana', + compressible: true, + extensions: ['node', 'modsule', 'npm'], + type: 'node/module' + }, + 'application/javascript': { + source: 'iana', + charset: 'UTF-8', + compressible: true, + extensions: ['js', 'javascript'], + type: 'text/javascript' + }, + 'text/html': { + predicate: (mime: MimosOptionsValue) => { + if (1 === 1) { + // mime.foo = 'test'; + } else { + // mime.foo = 'bar'; + } + return mime; + } + } + } +}; + +const plugin: Plugin = { + name: 'example', + register: async (server: Server, options: ServerRegisterOptions) => { + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + } +}; + +const routeOptions: RouteOptions = { + compression: { + test: { + some: 'option' + } + }, + files: { + relativeTo: __dirname + }, + cors: { + origin: ['http://test.example.com', 'http://www.example.com', 'http://*.a.com'] + }, +}; + +declare module 'hapi' { + interface ServerOptionsApp { + key1?: string; + key2?: string; + any_thing?: string; + } +} + +const options: ServerOptions = { + address: '0.0.0.0', + app: { + key1: 'value1', + key2: 'value2', + any_thing: 'any_value', + }, + autoListen: true, + cache: { + engine: require('catbox-memory'), + name: 'test', + shared: true, + partition: 'hapi-cache', + any_thing_1: 'any_thing_1', + any_thing_2: 'any_thing_2' + }, + compression: { + minBytes: 1024 + }, + debug: { + request: ['implementation'] + }, + host: 'localhost', + listener: undefined, + load: { sampleInterval: 0 }, + mime: mimeOptions, + plugins: plugin, + port: 8000, + router: { + isCaseSensitive: true, + stripTrailingSlash: false + }, + routes: routeOptions, + state: { + strictHeader: true, + ignoreErrors: false, + isSecure: true, + isHttpOnly: true, + isSameSite: 'Strict', + encoding: 'none' + }, + tls: true +}; + +const server = new Server(options); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-path.ts b/types/hapi/v17/test/server/server-path.ts new file mode 100644 index 0000000000..8a2ebf85dc --- /dev/null +++ b/types/hapi/v17/test/server/server-path.ts @@ -0,0 +1,37 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto +import { Plugin, Server, ServerRegisterOptions, ServerRoute } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +// Definition for INERT +declare module 'hapi' { + interface HandlerDecorations { + file?: string; + } +} + +const serverRouteOption: ServerRoute = { + path: '/file', + method: 'GET', + handler: { + file: './test.html' + } +}; + +const plugin: Plugin = { + name: 'example', + register: async (server: Server, options: ServerRegisterOptions) => { + // Assuming the Inert plugin was registered previously + server.path(__dirname + '../static'); + server.route(serverRouteOption); + } +}; + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-plugins.ts b/types/hapi/v17/test/server/server-plugins.ts new file mode 100644 index 0000000000..03a3c76907 --- /dev/null +++ b/types/hapi/v17/test/server/server-plugins.ts @@ -0,0 +1,116 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import { Plugin, Server, ServerRegisterOptions } from "hapi"; + +interface Plugin1 { + one: 1; +} + +interface Plugin2 { + two: 2; +} + +interface Plugin3 { + three: 3; +} + +interface Plugin4 { + four: 4; +} + +declare module 'hapi' { + interface PluginProperties { + example: { + other: string; + key: string; + }; + } +} + +const plugin1: Plugin = { + name: 'plugin1', + register: async (server: Server, options: Plugin1) => { + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + }, +}; + +const plugin2: Plugin = { + name: 'plugin2', + register: async (server: Server, options: Plugin2) => {}, + dependencies: { + plugin1: '*', + }, + requirements: { + node: '>=8', + hapi: '>=1337', + }, +}; + +const plugin3: Plugin = { + name: 'plugin3', + register: async (server: Server, options: Plugin3) => {}, + dependencies: ['plugin2'], +}; + +const plugin4: Plugin = { + name: 'plugin4', + register: (server: Server, options: Plugin4) => {}, + dependencies: 'plugin3', +}; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.register(plugin1); + +server.register({ + plugin: plugin1, + options: {one: 1} +}); + +server.register([ + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin4, + options: {four: 4} + } +]); diff --git a/types/hapi/v17/test/server/server-settings.ts b/types/hapi/v17/test/server/server-settings.ts new file mode 100644 index 0000000000..f0619d95da --- /dev/null +++ b/types/hapi/v17/test/server/server-settings.ts @@ -0,0 +1,18 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serversettings +import { Server } from "hapi"; + +declare module 'hapi' { + interface ServerOptionsApp { + key?: string; + } +} + +const server = new Server({ + port: 8000, + app: { + key: 'value' + } +}); +server.start(); + +console.log(server.settings.app); // { key: 'value' } diff --git a/types/hapi/v17/test/server/server-start.ts b/types/hapi/v17/test/server/server-start.ts new file mode 100644 index 0000000000..f41349e88c --- /dev/null +++ b/types/hapi/v17/test/server/server-start.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-state.ts b/types/hapi/v17/test/server/server-state.ts new file mode 100644 index 0000000000..ba4ffe344c --- /dev/null +++ b/types/hapi/v17/test/server/server-state.ts @@ -0,0 +1,28 @@ +// from https://hapijs.com/tutorials/cookies?lang=en_US +import { Server, ServerOptions, ServerRoute, ServerStateCookieOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/say-hello', + method: 'GET', + handler(_request, h) { + h.state('test', { test: true }); + return h.response('Hello').state('data', { firstVisit: false }); + } +}; + +const server = new Server(options); +server.route(serverRoute); + +const stateOption: ServerStateCookieOptions = { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: false, + isHttpOnly: false, + encoding: 'base64json', +}; +server.state('data', stateOption); +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-stop.ts b/types/hapi/v17/test/server/server-stop.ts new file mode 100644 index 0000000000..7922fa944e --- /dev/null +++ b/types/hapi/v17/test/server/server-stop.ts @@ -0,0 +1,17 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); +server.events.on('stop', () => { + console.log('Server stoped.'); +}); +setTimeout(() => { + server.stop({ timeout: 10 * 1000 }); +}, 5 * 1000); diff --git a/types/hapi/v17/test/server/server-table.ts b/types/hapi/v17/test/server/server-table.ts new file mode 100644 index 0000000000..79726118b5 --- /dev/null +++ b/types/hapi/v17/test/server/server-table.ts @@ -0,0 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost +import { Request, ResponseToolkit, Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const server = new Server(options); +server.app.key = 'value2'; + +server.route({ + path: '/', + method: 'GET', + handler(request, h) { + return h.response("Hello World"); + } +}); + +server.start(); +const table = server.table(); +console.log(table); +console.log(table[0].method); +console.log(table[0].path); +console.log(table[0].vhost); +console.log(table[0].realm); +console.log(table[0].settings); +console.log(table[0].fingerprint); +console.log(table[0].auth); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-version.ts b/types/hapi/v17/test/server/server-version.ts new file mode 100644 index 0000000000..b8e59497fc --- /dev/null +++ b/types/hapi/v17/test/server/server-version.ts @@ -0,0 +1,9 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverversion +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +console.log(server.version); // 17.x.x diff --git a/types/hapi/v17/tsconfig.json b/types/hapi/v17/tsconfig.json new file mode 100644 index 0000000000..c0e48eaa17 --- /dev/null +++ b/types/hapi/v17/tsconfig.json @@ -0,0 +1,79 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "hapi": [ + "hapi/v17" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/request/auth.ts", + "test/request/catch-all.ts", + "test/request/event-types.ts", + "test/request/get-log.ts", + "test/request/methods.ts", + "test/request/parameters.ts", + "test/request/query.ts", + "test/response/continue.ts", + "test/response/error.ts", + "test/response/redirect.ts", + "test/response/response-events.ts", + "test/response/response.ts", + "test/route/adding-routes.ts", + "test/route/config.ts", + "test/route/ext.ts", + "test/route/handler.ts", + "test/route/route-options-pre.ts", + "test/route/route-options.ts", + "test/route/validation.ts", + "test/server/server-app.ts", + "test/server/server-auth-api.ts", + "test/server/server-auth-default.ts", + "test/server/server-auth-test.ts", + "test/server/server-auth-verify.ts", + "test/server/server-bind.ts", + "test/server/server-cache-provision.ts", + "test/server/server-cache.ts", + "test/server/server-control.ts", + "test/server/server-decoder.ts", + "test/server/server-decorations.ts", + "test/server/server-encoder.ts", + "test/server/server-events-once.ts", + "test/server/server-events.ts", + "test/server/server-expose.ts", + "test/server/server-info.ts", + "test/server/server-inject.ts", + "test/server/server-listener.ts", + "test/server/server-load.ts", + "test/server/server-lookup.ts", + "test/server/server-match.ts", + "test/server/server-method.ts", + "test/server/server-methods.ts", + "test/server/server-mime.ts", + "test/server/server-options.ts", + "test/server/server-path.ts", + "test/server/server-plugins.ts", + "test/server/server-settings.ts", + "test/server/server-start.ts", + "test/server/server-state.ts", + "test/server/server-stop.ts", + "test/server/server-table.ts", + "test/server/server-version.ts" + ] +} diff --git a/types/hapi/v17/tslint.json b/types/hapi/v17/tslint.json new file mode 100644 index 0000000000..1c36270d47 --- /dev/null +++ b/types/hapi/v17/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/hex-rgb/hex-rgb-tests.ts b/types/hex-rgb/hex-rgb-tests.ts new file mode 100644 index 0000000000..f9bbf5ea71 --- /dev/null +++ b/types/hex-rgb/hex-rgb-tests.ts @@ -0,0 +1,4 @@ +import hexRgb = require('hex-rgb'); + +hexRgb('#cd2222cc'); // $ExpectType RgbaObj +hexRgb('#cd2222cc', { format: 'array' }); // $ExpectType [number, number, number, number] diff --git a/types/hex-rgb/index.d.ts b/types/hex-rgb/index.d.ts new file mode 100644 index 0000000000..ab1de9bf24 --- /dev/null +++ b/types/hex-rgb/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for hex-rgb 3.0 +// Project: https://github.com/sindresorhus/hex-rgb#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = hexRgb; + +declare function hexRgb(hex: string): hexRgb.RgbaObj; +declare function hexRgb(hex: string, options: hexRgb.Options): hexRgb.RgbaArr; + +declare namespace hexRgb { + interface Options { + format: 'array'; + } + + interface RgbaObj { + red: number; + green: number; + blue: number; + alpha: number; + } + + type RgbaArr = [number, number, number, number]; +} diff --git a/types/hex-rgb/tsconfig.json b/types/hex-rgb/tsconfig.json new file mode 100644 index 0000000000..c20c71b94f --- /dev/null +++ b/types/hex-rgb/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", + "hex-rgb-tests.ts" + ] +} diff --git a/types/hex-rgb/tslint.json b/types/hex-rgb/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hex-rgb/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hls.js/hls.js-tests.ts b/types/hls.js/hls.js-tests.ts index 934ee1fd9c..90176ae6b7 100644 --- a/types/hls.js/hls.js-tests.ts +++ b/types/hls.js/hls.js-tests.ts @@ -23,7 +23,14 @@ class pLoader extends Hls.DefaultConfig.loader { if (Hls.isSupported()) { const video = document.getElementById('video'); - const hls = new Hls({ pLoader, startFragPrefetch: true }); + const hls = new Hls({ + pLoader, + startFragPrefetch: true, + debug: { + log: (...args: any[]) => console.log(...args) + } + }); + const version: string = Hls.version; hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8'); hls.attachMedia(video); diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 721f4a3dce..9b7986b99f 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for hls.js 0.10 +// Type definitions for hls.js 0.12 // Project: https://github.com/video-dev/hls.js // Definitions by: John G. Gainfort, Jr. +// Johan Brook // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.4 // Event Keys type K_MEDIA_ATTACHING = "hlsMediaAttaching"; @@ -307,6 +308,16 @@ declare namespace Hls { // interface SubtitleTracks {} + type CustomLogger = (...args: any[]) => void; + + interface CustomLoggerObject { + warn?: CustomLogger; + info?: CustomLogger; + log?: CustomLogger; + debug?: CustomLogger; + error?: CustomLogger; + } + interface Config { /** * (default: false) @@ -319,7 +330,7 @@ declare namespace Hls { * setting config.debug = true; will turn on debug logs on JS console. * a logger object could also be provided for custom logging: config.debug = customLogger; */ - debug: boolean; + debug: boolean | CustomLoggerObject; /** * (default: true) * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event @@ -475,6 +486,14 @@ declare namespace Hls { * Android Google Chrome, etc. set this value to true. */ liveDurationInfinity: boolean; + /** + * (default: Infinity) + * Sets the maximum length of the buffer, in seconds, to keep during a live stream. Any video + * buffered past this time will be evicted. Infinity means no restriction on back buffer length; + * 0 keeps the minimum amount. The minimum amount is equal to the target duration of a segment + * to ensure that current playback is not interrupted. + */ + liveBackBufferLength: number; /** * (default: true) * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. diff --git a/types/html-tags/html-tags-tests.ts b/types/html-tags/html-tags-tests.ts new file mode 100644 index 0000000000..802dbb665e --- /dev/null +++ b/types/html-tags/html-tags-tests.ts @@ -0,0 +1,9 @@ +import htmlTags = require('html-tags'); +import voidHtmlTags = require('html-tags/void'); +import htmlTagsJson = require('html-tags/html-tags.json'); +import voidHtmlTagsJson = require('html-tags/html-tags-void.json'); + +htmlTags; // $ExpectType string[] +voidHtmlTags; // $ExpectType string[] +htmlTagsJson; // $ExpectType string[] +voidHtmlTagsJson; // $ExpectType string[] diff --git a/types/html-tags/html-tags-void.json.d.ts b/types/html-tags/html-tags-void.json.d.ts new file mode 100644 index 0000000000..3e194ddf27 --- /dev/null +++ b/types/html-tags/html-tags-void.json.d.ts @@ -0,0 +1,3 @@ +export = voidHtmlTags; + +declare const voidHtmlTags: string[]; diff --git a/types/html-tags/html-tags.json.d.ts b/types/html-tags/html-tags.json.d.ts new file mode 100644 index 0000000000..888779dc9c --- /dev/null +++ b/types/html-tags/html-tags.json.d.ts @@ -0,0 +1,3 @@ +export = htmlTags; + +declare const htmlTags: string[]; diff --git a/types/html-tags/index.d.ts b/types/html-tags/index.d.ts new file mode 100644 index 0000000000..635ce4820f --- /dev/null +++ b/types/html-tags/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for html-tags 2.0 +// Project: https://github.com/sindresorhus/html-tags#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = htmlTags; + +declare const htmlTags: string[]; diff --git a/types/html-tags/tsconfig.json b/types/html-tags/tsconfig.json new file mode 100644 index 0000000000..971c9bb630 --- /dev/null +++ b/types/html-tags/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "void.d.ts", + "html-tags.json.d.ts", + "html-tags-void.json.d.ts", + "html-tags-tests.ts" + ] +} diff --git a/types/html-tags/tslint.json b/types/html-tags/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/html-tags/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/html-tags/void.d.ts b/types/html-tags/void.d.ts new file mode 100644 index 0000000000..3e194ddf27 --- /dev/null +++ b/types/html-tags/void.d.ts @@ -0,0 +1,3 @@ +export = voidHtmlTags; + +declare const voidHtmlTags: string[]; diff --git a/types/http-proxy-middleware/http-proxy-middleware-tests.ts b/types/http-proxy-middleware/http-proxy-middleware-tests.ts index aae082a956..9967dedcd9 100644 --- a/types/http-proxy-middleware/http-proxy-middleware-tests.ts +++ b/types/http-proxy-middleware/http-proxy-middleware-tests.ts @@ -140,3 +140,6 @@ proxy({ proxy({ headers: {host: 'www.example.org'} }); + +// Shorthands +proxy('/'); diff --git a/types/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts index 09b80e21c4..13f2669e5f 100644 --- a/types/http-proxy-middleware/index.d.ts +++ b/types/http-proxy-middleware/index.d.ts @@ -15,7 +15,7 @@ import * as httpProxy from "http-proxy"; import { Readable } from 'stream'; declare function proxy(config: proxy.Config): proxy.Proxy; -declare function proxy(contextOrUri: string | string[] | proxy.Filter, config: proxy.Config): proxy.Proxy; +declare function proxy(contextOrUri: string | string[] | proxy.Filter, config?: proxy.Config): proxy.Proxy; declare namespace proxy { type Filter = (pathname: string, req: http.IncomingMessage) => boolean; diff --git a/types/http-rx/http-rx-tests.ts b/types/http-rx/http-rx-tests.ts index 082585fdf9..b76ba67832 100644 --- a/types/http-rx/http-rx-tests.ts +++ b/types/http-rx/http-rx-tests.ts @@ -1,13 +1,14 @@ import { Observable } from 'rxjs'; import httpRx = require('http-rx'); +import request = require('request'); -const httpGet: Observable = httpRx.get(''); +const httpGet: Observable<{response: request.Response}> = httpRx.get(''); -const httpHead: Observable = httpRx.head(''); +const httpHead: Observable<{body: any}> = httpRx.head(''); -const httpPatch: Observable = httpRx.patch(''); +const httpPatch: Observable<{response: request.Response, body: any}> = httpRx.patch(''); -const httpPost: Observable = httpRx.post(''); +const httpPost: Observable<{response: request.Response, body: any}> = httpRx.post('', {json: true}); const httpPut: Observable<{}> = httpRx.put(''); diff --git a/types/http-rx/index.d.ts b/types/http-rx/index.d.ts index 3b0c734fb0..c752427b8a 100644 --- a/types/http-rx/index.d.ts +++ b/types/http-rx/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for http-rx 1.1 +// Type definitions for http-rx 2.0 // Project: https://github.com/JasonRammoray/HttpRx // Definitions by: L2jLiga // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,18 +7,23 @@ import { Observable } from 'rxjs'; import request = require('request'); +interface ResponseWrapper { + response: request.Response; + body: any; +} + interface HttpRx { - get(url: string, options?: request.CoreOptions): Observable; + get(url: string, options?: request.CoreOptions): Observable; - head(url: string, options?: request.CoreOptions): Observable; + head(url: string, options?: request.CoreOptions): Observable; - patch(url: string, options?: request.CoreOptions): Observable; + patch(url: string, options?: request.CoreOptions): Observable; - post(url: string, options?: request.CoreOptions): Observable; + post(url: string, options?: request.CoreOptions): Observable; - put(url: string, options?: request.CoreOptions): Observable; + put(url: string, options?: request.CoreOptions): Observable; - 'delete'(url: string, options?: request.CoreOptions): Observable; + delete(url: string, options?: request.CoreOptions): Observable; } declare const httpRx: HttpRx; diff --git a/types/image-size/image-size-tests.ts b/types/image-size/image-size-tests.ts index 058ed7934f..633169105d 100644 --- a/types/image-size/image-size-tests.ts +++ b/types/image-size/image-size-tests.ts @@ -4,11 +4,11 @@ import sizeOf = require("image-size"); // Synchronous const dimensions = sizeOf("images/funny-cats.png"); -console.log(dimensions.width, dimensions.height); +console.log(dimensions.width, dimensions.height, dimensions.orientation); // Asynchronous sizeOf("images/funny-cats.png", (err, dimensions) => { - console.log(dimensions.width, dimensions.height); + console.log(dimensions.width, dimensions.height, dimensions.orientation); }); // From URL diff --git a/types/image-size/index.d.ts b/types/image-size/index.d.ts index 9e8681d514..443c319fb2 100644 --- a/types/image-size/index.d.ts +++ b/types/image-size/index.d.ts @@ -1,23 +1,20 @@ -// Type definitions for image-size +// Type definitions for image-size 0.7 // Project: https://github.com/image-size/image-size // Definitions by: Elisée MAURER // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - - interface ImageInfo { width: number; height: number; type: string; + orientation?: number; } -declare function sizeOf(path: string): ImageInfo; +declare function sizeOf(pathOrBuffer: string | Buffer): ImageInfo; declare function sizeOf(path: string, callback: (err: Error, dimensions: ImageInfo) => void): void; -declare function sizeOf(buffer: Buffer): ImageInfo; - declare namespace sizeOf { } export = sizeOf; diff --git a/types/image-size/tsconfig.json b/types/image-size/tsconfig.json index 7a864603b7..7c8d0db7d1 100644 --- a/types/image-size/tsconfig.json +++ b/types/image-size/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/image-size/tslint.json b/types/image-size/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/image-size/tslint.json +++ b/types/image-size/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/inboxsdk/inboxsdk-tests.ts b/types/inboxsdk/inboxsdk-tests.ts index 4f51bae92c..19329b9d63 100644 --- a/types/inboxsdk/inboxsdk-tests.ts +++ b/types/inboxsdk/inboxsdk-tests.ts @@ -571,6 +571,7 @@ InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { sdk.Router.createLink('1234', {p1: 1, 0: 1}).toLowerCase(); sdk.Router.goto('1234', {p1: 1, 0: 1}); + sdk.Router.goto(sdk.Router.NativeRouteIDs.ALL_MAIL, {p1: 1, 0: 1}); const unregister1 = sdk.Router.handleCustomRoute('1234', customRouteView => { customRouteView.getParams(); @@ -591,7 +592,7 @@ InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { unregister2(); - const unregister3 = sdk.Router.handleListRoute('ALL_MAIL', listRouteView => { + const unregister3 = sdk.Router.handleListRoute(sdk.Router.NativeListRouteIDs.DRAFTS, listRouteView => { const sectionDescriptor: SectionDescriptor = { contentElement: new HTMLElement(), footerLinkText: 'text', diff --git a/types/inboxsdk/index.d.ts b/types/inboxsdk/index.d.ts index 4ced3ce6bd..abdfe413bf 100644 --- a/types/inboxsdk/index.d.ts +++ b/types/inboxsdk/index.d.ts @@ -657,6 +657,9 @@ declare namespace InboxSDK { handleCustomListRoute(routeID: string, handler: (offset: number, max: number) => CustomListDescriptor | Promise): () => void; getCurrentRouteView(): RouteView; + + NativeListRouteIDs: typeof NativeListRouteIDs; + NativeRouteIDs: typeof NativeRouteIDs; } interface CustomListDescriptor { @@ -754,43 +757,45 @@ declare namespace InboxSDK { onClick?: () => void; } - type NativeRouteIDs = - 'INBOX' | - 'ALL_MAIL' | - 'SENT' | - 'STARRED' | - 'DRAFTS' | - 'SNOOZED' | - 'DONE' | - 'REMINDERS' | - 'LABEL' | - 'TRASH' | - 'SPAM' | - 'IMPORTANT' | - 'SEARCH' | - 'THREAD' | - 'CHATS' | - 'CHAT' | - 'CONTACTS' | - 'CONTACT' | - 'SETTINGS' | - 'ANY_LIST'; + enum NativeRouteIDs { + INBOX, + ALL_MAIL, + SENT, + STARRED, + DRAFTS, + SNOOZED, + DONE, + REMINDERS, + LABEL, + TRASH, + SPAM, + IMPORTANT, + SEARCH, + THREAD, + CHATS, + CHAT, + CONTACTS, + CONTACT, + SETTINGS, + ANY_LIST + } - type NativeListRouteIDs = - 'INBOX' - | 'ALL_MAIL' - | 'SENT' - | 'STARRED' - | 'DRAFTS' - | 'SNOOZED' - | 'DONE' - | 'REMINDERS' - | 'LABEL' - | 'TRASH' - | 'SPAM' - | 'IMPORTANT' - | 'SEARCH' - | 'ANY_LIST'; + enum NativeListRouteIDs { + INBOX, + ALL_MAIL, + SENT, + STARRED, + DRAFTS, + SNOOZED, + DONE, + REMINDERS, + LABEL, + TRASH, + SPAM, + IMPORTANT, + SEARCH, + ANY_LIST + } } export namespace NavMenu { diff --git a/types/intl-tel-input/index.d.ts b/types/intl-tel-input/index.d.ts index 667a210087..f0c8407f18 100644 --- a/types/intl-tel-input/index.d.ts +++ b/types/intl-tel-input/index.d.ts @@ -1,9 +1,21 @@ // Type definitions for intl-tel-input 14.0 // Project: https://github.com/jackocnr/intl-tel-input -// Definitions by: Fidan Hakaj , Leonard Thieu , Márton Molnár +// Definitions by: Fidan Hakaj +// Leonard Thieu +// Márton Molnár // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +export as namespace intlTelInput; + +export = IntlTelInput; + +/** + * initialise the plugin with optional options. + * @param options options that can be provided during initialization. + */ +declare function IntlTelInput(node: Element, options?: IntlTelInput.Options): IntlTelInput.Plugin; + declare namespace IntlTelInput { interface Static { /** @@ -25,6 +37,8 @@ declare namespace IntlTelInput { } interface Plugin { + promise: Promise; + /** * Remove the plugin from the input, and unbind any event listeners. */ @@ -386,16 +400,50 @@ declare namespace intlTelInputUtils { | "VOIP"; } -interface Window { - intlTelInputGlobals: IntlTelInput.Static; +declare global { + namespace intlTelInputUtils { + enum numberFormat { + E164 = 0, + INTERNATIONAL = 1, + NATIONAL = 2, + RFC3966 = 3 + } - /** - * initialise the plugin with optional options. - * @param options options that can be provided during initialization. - */ - intlTelInput(node: Element, options?: IntlTelInput.Options): IntlTelInput.Plugin; -} + enum numberType { + FIXED_LINE = 0, + MOBILE = 1, + FIXED_LINE_OR_MOBILE = 2, + TOLL_FREE = 3, + PREMIUM_RATE = 4, + SHARED_COST = 5, + VOIP = 6, + PERSONAL_NUMBER = 7, + PAGER = 8, + UAN = 9, + VOICEMAIL = 10, + UNKNOWN = -1 + } -interface JQuery { - intlTelInput: IntlTelInput.JQueryPlugin; + enum validationError { + IS_POSSIBLE = 0, + INVALID_COUNTRY_CODE = 1, + TOO_SHORT = 2, + TOO_LONG = 3, + NOT_A_NUMBER = 4 + } + } + + interface Window { + intlTelInputGlobals: IntlTelInput.Static; + + /** + * initialise the plugin with optional options. + * @param options options that can be provided during initialization. + */ + intlTelInput(node: Element, options?: IntlTelInput.Options): IntlTelInput.Plugin; + } + + interface JQuery { + intlTelInput: IntlTelInput.JQueryPlugin; + } } diff --git a/types/intl-tel-input/intl-tel-input-tests.ts b/types/intl-tel-input/intl-tel-input-tests.ts index ab6808bbed..6bb705cafb 100644 --- a/types/intl-tel-input/intl-tel-input-tests.ts +++ b/types/intl-tel-input/intl-tel-input-tests.ts @@ -1,5 +1,10 @@ /// +// Global + +// $ExpectType (node: Element, options?: Options) => Plugin +intlTelInput; + // Normal version const input = document.querySelector("#phone"); diff --git a/types/intl-tel-input/test/module-tests.ts b/types/intl-tel-input/test/module-tests.ts new file mode 100644 index 0000000000..4bfdd3c6a7 --- /dev/null +++ b/types/intl-tel-input/test/module-tests.ts @@ -0,0 +1,24 @@ +import intlTelInput = require('intl-tel-input'); + +function test_import() { + // $ExpectType (node: Element, options?: Options) => Plugin + intlTelInput; +} + +function test_IntlTelInput_not_visible() { + // $ExpectError + const options: IntlTelInput.Options = { + allowDropdown: true + }; +} + +function test_intlTelInputUtils_global() { + const input = document.querySelector('#phone'); + const iti = intlTelInput(input, { + utilsScript: 'node_modules/intl-tel-input/build/js/utils.js' + }); + + iti.promise.then(() => { + console.log(intlTelInputUtils.numberFormat.E164); + }); +} diff --git a/types/intl-tel-input/tsconfig.json b/types/intl-tel-input/tsconfig.json index e067880440..302c298ef8 100644 --- a/types/intl-tel-input/tsconfig.json +++ b/types/intl-tel-input/tsconfig.json @@ -19,6 +19,7 @@ }, "files": [ "index.d.ts", - "intl-tel-input-tests.ts" + "intl-tel-input-tests.ts", + "test/module-tests.ts" ] } diff --git a/types/iopipe__iopipe/index.d.ts b/types/iopipe__iopipe/index.d.ts new file mode 100644 index 0000000000..338de9ca58 --- /dev/null +++ b/types/iopipe__iopipe/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for iopipe__iopipe 1.12 +// Project: https://github.com/iopipe/iopipe (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: Javon Harper +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function iopipe(config?: iopipe.LibraryConfig): iopipe.FunctionWrapper; + +declare namespace iopipe { + function label(label: string): void; + + function metric(label: string, value: number): void; + + namespace mark { + function start(label: string): void; + function end(label: string): void; + } + + interface LibraryConfig { + debug?: boolean; + token?: string; + networkTimeout?: number; + timeoutWindow?: number; + } + + type FunctionWrapper = (handler: any) => void; +} + +export = iopipe; diff --git a/types/iopipe__iopipe/iopipe__iopipe-tests.ts b/types/iopipe__iopipe/iopipe__iopipe-tests.ts new file mode 100644 index 0000000000..f5bd387dc8 --- /dev/null +++ b/types/iopipe__iopipe/iopipe__iopipe-tests.ts @@ -0,0 +1,17 @@ +import iopipe = require('iopipe__iopipe'); + +const config = { + token: "ABCDEFG" +}; + +function run(event: any, context: any, callback?: any) { + iopipe.label('my label'); + + iopipe.metric("magic number", 42); + + iopipe.mark.start("my-db-call"); + // an expensive database query + iopipe.mark.end("my-db-call"); +} + +iopipe(config)(run); diff --git a/types/iopipe__iopipe/tsconfig.json b/types/iopipe__iopipe/tsconfig.json new file mode 100644 index 0000000000..01d23ff29d --- /dev/null +++ b/types/iopipe__iopipe/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iopipe__iopipe-tests.ts" + ], + "paths": { + "@iopipe/iopipe": ["iopipe__iopipe"] + } +} diff --git a/types/iopipe__iopipe/tslint.json b/types/iopipe__iopipe/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iopipe__iopipe/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index acd380e7db..ca1d71a0aa 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -10,6 +10,7 @@ // Dmitry Motovilov // Oleg Repin // Ting-Wai To +// Alex Petty // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -971,8 +972,13 @@ declare namespace IORedis { count?: number; } + type DNSLookupFunction = (hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; + interface NatMap { + [key: string]: {host: string, port: number}; + } + interface ClusterOptions { - clusterRetryStrategy?(times: number): number; + clusterRetryStrategy?(times: number, reason?: Error): number | null; enableOfflineQueue?: boolean; enableReadyCheck?: boolean; scaleReads?: string; @@ -980,7 +986,12 @@ declare namespace IORedis { retryDelayOnFailover?: number; retryDelayOnClusterDown?: number; retryDelayOnTryAgain?: number; + slotsRefreshTimeout?: number; + slotsRefreshInterval?: number; redisOptions?: RedisOptions; + lazyConnect?: boolean; + dnsLookup?: DNSLookupFunction; + natMap?: NatMap; } interface MultiOptions { diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index df8e37aca8..14620b7476 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -192,3 +192,12 @@ redis.xread('STREAMS', 'streamName', '0-0'); redis.xreadgroup('GROUP', 'groupName', 'consumerName', 'STREAMS', 'streamName', '>'); redis.xrevrange('streamName', '+', '-', 'COUNT', 1); redis.xtrim('streamName', 'MAXLEN', '~', 1000); + +// ClusterRetryStrategy can return non-numbers to stop retrying +new Redis.Cluster([], { + clusterRetryStrategy: (times: number, reason?: Error) => null +}); + +new Redis.Cluster([], { + clusterRetryStrategy: (times: number, reason?: Error) => 1 +}); diff --git a/types/ioredis/v3/index.d.ts b/types/ioredis/v3/index.d.ts index ee2777c92c..03667cd071 100644 --- a/types/ioredis/v3/index.d.ts +++ b/types/ioredis/v3/index.d.ts @@ -7,6 +7,7 @@ // Shahar Mor // Whemoon Jang // Francis Gulotta +// Alex Petty // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -894,7 +895,7 @@ declare namespace IORedis { } interface ClusterOptions { - clusterRetryStrategy?(times: number): number; + clusterRetryStrategy?(times: number): number | null; enableOfflineQueue?: boolean; enableReadyCheck?: boolean; scaleReads?: string; diff --git a/types/ioredis/v3/ioredis-tests.ts b/types/ioredis/v3/ioredis-tests.ts index b77192e3b8..38cef49b73 100644 --- a/types/ioredis/v3/ioredis-tests.ts +++ b/types/ioredis/v3/ioredis-tests.ts @@ -153,3 +153,12 @@ new Redis.Cluster([{ host: 'localhost', port: 6379 }]); + +// ClusterRetryStrategy can return non-numbers to stop retrying +new Redis.Cluster([], { + clusterRetryStrategy: (times: number) => null +}); + +new Redis.Cluster([], { + clusterRetryStrategy: (times: number) => 1 +}); diff --git a/types/is-elevated/index.d.ts b/types/is-elevated/index.d.ts new file mode 100644 index 0000000000..c875437fde --- /dev/null +++ b/types/is-elevated/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-elevated 2.0 +// Project: https://github.com/sindresorhus/is-elevated#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isElevated; + +declare function isElevated(): Promise; diff --git a/types/is-elevated/is-elevated-tests.ts b/types/is-elevated/is-elevated-tests.ts new file mode 100644 index 0000000000..b2ba2f48fe --- /dev/null +++ b/types/is-elevated/is-elevated-tests.ts @@ -0,0 +1,3 @@ +import isElevated = require('is-elevated'); + +isElevated(); // $ExpectType Promise diff --git a/types/is-elevated/tsconfig.json b/types/is-elevated/tsconfig.json new file mode 100644 index 0000000000..ad48a57318 --- /dev/null +++ b/types/is-elevated/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", + "is-elevated-tests.ts" + ] +} diff --git a/types/is-elevated/tslint.json b/types/is-elevated/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-elevated/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-online/index.d.ts b/types/is-online/index.d.ts new file mode 100644 index 0000000000..04fa123c44 --- /dev/null +++ b/types/is-online/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for is-online 8.0 +// Project: https://github.com/sindresorhus/is-online#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isOnline; + +/** + * Check if the internet connection is up. + * + * The following checks are run in parallel: + * - Retrieve [icanhazip.com](https://github.com/major/icanhaz) via HTTPS + * - Query `myip.opendns.com` on OpenDNS (Node.js only) + * - Retrieve Apple's Captive Portal test page (Node.js only) + * + * When the first check succeeds, the returned Promise is resolved to `true`. + */ +declare function isOnline(options?: isOnline.Options): Promise; + +declare namespace isOnline { + interface Options { + /** + * Milliseconds to wait for a server to respond. + * @default 5000 + */ + timeout?: number; + /** + * Internet Protocol version to use. This is an advanced option that is usually not necessary to be set, + * but it can prove useful to specifically assert IPv6 connectivity. + * @default 'v4' + */ + version?: 'v4' | 'v6'; + } +} diff --git a/types/is-online/is-online-tests.ts b/types/is-online/is-online-tests.ts new file mode 100644 index 0000000000..74dbda5efa --- /dev/null +++ b/types/is-online/is-online-tests.ts @@ -0,0 +1,6 @@ +import isOnline = require('is-online'); + +isOnline(); // $ExpectType Promise +isOnline({ timeout: 10 }); // $ExpectType Promise +isOnline({ version: 'v4' }); // $ExpectType Promise +isOnline({ version: 'v6' }); // $ExpectType Promise diff --git a/types/is-online/tsconfig.json b/types/is-online/tsconfig.json new file mode 100644 index 0000000000..7009c26024 --- /dev/null +++ b/types/is-online/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", + "is-online-tests.ts" + ] +} diff --git a/types/is-online/tslint.json b/types/is-online/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-online/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-progressive/index.d.ts b/types/is-progressive/index.d.ts new file mode 100644 index 0000000000..3c05ab6fdc --- /dev/null +++ b/types/is-progressive/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for is-progressive 3.0 +// Project: https://github.com/sindresorhus/is-progressive#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Readable } from 'stream'; + +/** + * Returns whether the `buffer` is a progressive JPEG image. + * @param buffer Buffer of a JPEG image. + * Must be at least `65535` bytes when the file is larger than that. + */ +export function buffer(buffer: Buffer): boolean; + +/** + * Returns a Promise for a boolean indicating whether the file stream is a progressive JPEG image. + * @param stream Data stream. + */ +export function stream(stream: Readable): Promise; + +/** + * Returns a Promise for a boolean indicating whether the file is a progressive JPEG image. + * @param filepath Filepath to the image. + */ +export function file(filepath: string): Promise; + +/** + * Returns whether the buffer is a progressive JPEG. + * @param filepath Filepath to the image. + */ +export function fileSync(filepath: string): boolean; diff --git a/types/is-progressive/is-progressive-tests.ts b/types/is-progressive/is-progressive-tests.ts new file mode 100644 index 0000000000..b5525962ad --- /dev/null +++ b/types/is-progressive/is-progressive-tests.ts @@ -0,0 +1,12 @@ +import https = require('https'); +import isProgressive = require('is-progressive'); + +isProgressive.file('baseline.jpg'); // $ExpectType Promise + +isProgressive.fileSync('progressive.jpg'); // $ExpectType boolean + +https.get('/', res => { + isProgressive.stream(res); // $ExpectType Promise +}); + +isProgressive.buffer(new Buffer(1)); // $ExpectType boolean diff --git a/types/is-progressive/tsconfig.json b/types/is-progressive/tsconfig.json new file mode 100644 index 0000000000..edc521b158 --- /dev/null +++ b/types/is-progressive/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", + "is-progressive-tests.ts" + ] +} diff --git a/types/is-progressive/tslint.json b/types/is-progressive/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-progressive/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-reachable/index.d.ts b/types/is-reachable/index.d.ts new file mode 100644 index 0000000000..6e2ea2d62f --- /dev/null +++ b/types/is-reachable/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for is-reachable 3.0 +// Project: https://github.com/sindresorhus/is-reachable#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isReachable; + +/** + * Check if servers are reachable. + * + * The Node.js version will do a TCP handshake with the target's port. It attempts to detect cases where a router + * redirects the request to itself. + * + * The browser version is limited by the fact that browsers cannot connect to arbitrary ports. It only supports + * HTTP and HTTPS and the check relies on the `/favicon.ico` path being present. + * + * @param targets One or more targets to check. Can either be a full [URL](https://nodejs.org/api/url.html) + * like `https://hostname`, `hostname:port` or just `hostname`. When the protocol is missing from a target + * `http` is assumed. + * + * [Well-known protocols](http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml) + * are supported (e.g. `ftp://`, `mysql://`, `redis://` and more). + * + * @returns A `Promise` for a `boolean` which is `true` if any of the `targets` are reachable. + */ +declare function isReachable( + targets: string | string[], + options?: isReachable.Options +): Promise; + +declare namespace isReachable { + interface Options { + /** + * Timeout in milliseconds after which a request is considered failed. + * @default 5000 + */ + timeout?: number; + } +} diff --git a/types/is-reachable/is-reachable-tests.ts b/types/is-reachable/is-reachable-tests.ts new file mode 100644 index 0000000000..d497d004f2 --- /dev/null +++ b/types/is-reachable/is-reachable-tests.ts @@ -0,0 +1,4 @@ +import isReachable = require('is-reachable'); + +isReachable('sindresorhus.com'); // $ExpectType Promise +isReachable('google.com:80', { timeout: 10 }); // $ExpectType Promise diff --git a/types/is-reachable/tsconfig.json b/types/is-reachable/tsconfig.json new file mode 100644 index 0000000000..c30236ebd5 --- /dev/null +++ b/types/is-reachable/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", + "is-reachable-tests.ts" + ] +} diff --git a/types/is-reachable/tslint.json b/types/is-reachable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-reachable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 2109645eef..db5b00b633 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -21,7 +21,19 @@ * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs */ declare function describe(description: string, specDefinitions: () => void): void; + +/** + * A focused `describe`. If suites or specs are focused, only those that are focused will be executed. + * @param description Textual description of the group + * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs + */ declare function fdescribe(description: string, specDefinitions: () => void): void; + +/** + * A temporarily disabled `describe`. Specs within an xdescribe will be marked pending and not executed. + * @param description Textual description of the group + * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs + */ declare function xdescribe(description: string, specDefinitions: () => void): void; /** @@ -34,20 +46,25 @@ declare function xdescribe(description: string, specDefinitions: () => void): vo declare function it(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; /** - * A focused it - * If suites or specs are focused, only those that are focused will be executed. - * @param expectation - * @param assertion - * @param timeout + * A focused `it`. If suites or specs are focused, only those that are focused will be executed. + * @param expectation Textual description of what this spec is checking + * @param assertion Function that contains the code of your test. If not provided the test will be pending. + * @param timeout Custom timeout for an async spec. */ declare function fit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; + +/** + * A temporarily disabled `it`. The spec will report as pending and will not be executed. + * @param expectation Textual description of what this spec is checking + * @param assertion Function that contains the code of your test. If not provided the test will be pending. + * @param timeout Custom timeout for an async spec. + */ declare function xit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; /** * Mark a spec as pending, expectation results will be ignored. * If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. - * @param reason - * @returns {} + * @param reason Reason the spec is pending. */ declare function pending(reason?: string): void; @@ -119,11 +136,13 @@ declare function expectAsync(actual: Promise): jasmine.AsyncMatchers(object: T, method: keyof T): jasmine.Spy; /** - * Install a spy on a property onto an existing object. - * @param object The object upon which to install the Spy - * @param property The name of the property to replace with a Spy - * @param accessType The access type (get|set) of the property to Spy on. + * Install a spy on a property installed with `Object.defineProperty` onto an existing object. + * @param object The object upon which to install the `Spy`. + * @param property The name of the property to replace with a `Spy`. + * @param accessType The access type (get|set) of the property to `Spy` on. */ declare function spyOnProperty(object: T, property: keyof T, accessType?: 'get' | 'set'): jasmine.Spy; /** * Installs spies on all writable and configurable properties of an object. - * @param object The object upon which to install the Spies + * @param object The object upon which to install the `Spy`s. */ declare function spyOnAllFunctions(object: object): jasmine.Spy; @@ -158,9 +177,12 @@ declare function waits(timeout?: number): void; declare namespace jasmine { type Expected = T | ObjectContaining | Any | Spy; - type SpyObjMethodNames = T extends undefined ? (ReadonlyArray | {[methodName: string]: any}) : (ReadonlyArray | {[P in keyof T]?: ReturnType any ? T[P] : any>}); + type SpyObjMethodNames = + T extends undefined ? + (ReadonlyArray | {[methodName: string]: any}) : + (ReadonlyArray | {[P in keyof T]?: ReturnType any ? T[P] : any>}); - var clock: () => Clock; + function clock(): Clock; var matchersUtil: MatchersUtil; @@ -187,13 +209,12 @@ declare namespace jasmine { function addMatchers(matchers: CustomMatcherFactories): void; - function stringMatching(str: string): Any; - function stringMatching(str: RegExp): Any; + function stringMatching(str: string | RegExp): Any; function formatErrorMsg(domain: string, usage: string): (msg: string) => string; interface Any { - (...params: any[]):any; // jasmine.Any can also be a function + (...params: any[]): any; // jasmine.Any can also be a function new (expectedClass: any): any; jasmineMatches(other: any): boolean; @@ -221,7 +242,6 @@ declare namespace jasmine { } interface Block { - new (env: Env, func: SpecFunction, spec: Spec): any; execute(onComplete: () => void): void; @@ -271,12 +291,6 @@ declare namespace jasmine { } interface Env { - setTimeout: any; - clearTimeout: void; - setInterval: any; - clearInterval: void; - updateInterval: number; - currentSpec: Spec; matchersClass: Matchers; @@ -284,8 +298,7 @@ declare namespace jasmine { version(): any; versionString(): string; nextSpecId(): number; - addReporter(reporter: Reporter): void; - addReporter(reporter: CustomReporter): void; + addReporter(reporter: Reporter | CustomReporter): void; execute(): void; describe(description: string, specDefinitions: () => void): Suite; // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these @@ -316,7 +329,6 @@ declare namespace jasmine { } interface FakeTimer { - new (): any; reset(): void; @@ -395,7 +407,6 @@ declare namespace jasmine { } interface PrettyPrinter { - new (): any; format(value: any): void; @@ -411,7 +422,6 @@ declare namespace jasmine { } interface Queue { - new (env: any): any; env: Env; @@ -432,7 +442,6 @@ declare namespace jasmine { } interface Matchers { - new (env: Env, actual: T, spec: Env, isNot?: boolean): any; env: Env; @@ -445,7 +454,6 @@ declare namespace jasmine { * * @param expected the actual value to be === to the expected value. * @param expectationFailOutput - * @returns {} */ toBe(expected: Expected, expectationFailOutput?: any): boolean; @@ -453,7 +461,6 @@ declare namespace jasmine { * * @param expected the actual value to be equal to the expected, using deep equality comparison. * @param expectationFailOutput - * @returns {} */ toEqual(expected: Expected, expectationFailOutput?: any): boolean; toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean; @@ -504,7 +511,6 @@ declare namespace jasmine { } interface AsyncMatchers { - /** * Expect a promise to be resolved. * @param expectationFailOutput @@ -538,7 +544,7 @@ declare namespace jasmine { /** * Invert the matcher following this expect. */ - not: AsyncMatchers + not: AsyncMatchers; } interface Reporter { @@ -571,7 +577,6 @@ declare namespace jasmine { } interface PassedExpectation extends CustomReportExpectation { - } interface CustomReporterResult { @@ -586,7 +591,7 @@ declare namespace jasmine { interface RunDetails { failedExpectations: ExpectationResult[]; - order: jasmine.Order; + order: Order; } interface CustomReporter { @@ -599,7 +604,6 @@ declare namespace jasmine { } interface Runner { - new (env: Env): any; execute(): void; @@ -626,7 +630,6 @@ declare namespace jasmine { } interface Spec extends SuiteOrSpec { - new (env: Env, suite: Suite, description: string): any; suite: Suite; @@ -670,7 +673,6 @@ declare namespace jasmine { } interface Suite extends SuiteOrSpec { - new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; parentSuite: Suite; @@ -701,9 +703,9 @@ declare namespace jasmine { withArgs(...args: any[]): Spy; } - type SpyObj = { + type SpyObj = T & { [k in keyof T]: T[k] extends Function ? T[k] & Spy : T[k]; - } + }; interface SpyAnd { identity: string; @@ -723,21 +725,21 @@ declare namespace jasmine { } interface Calls { - /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ any(): boolean; - /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ count(): number; - /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ argsFor(index: number): any[]; - /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ allArgs(): any[]; - /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ all(): CallInfo[]; - /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ mostRecent(): CallInfo; - /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ first(): CallInfo; - /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ reset(): void; } @@ -759,7 +761,6 @@ declare namespace jasmine { } interface JsApiReporter extends Reporter { - started: boolean; finished: boolean; result: any; @@ -783,10 +784,32 @@ declare namespace jasmine { util: Util; } - export var HtmlReporter: HtmlReporter; - export var HtmlSpecFilter: HtmlSpecFilter; - export var DEFAULT_TIMEOUT_INTERVAL: number; - export var MAX_PRETTY_PRINT_DEPTH: number; + var HtmlReporter: HtmlReporter; + var HtmlSpecFilter: HtmlSpecFilter; + + /** + * Default number of milliseconds Jasmine will wait for an asynchronous spec to complete. + */ + var DEFAULT_TIMEOUT_INTERVAL: number; + + /** + * Maximum number of array elements to display when pretty printing objects. + * This will also limit the number of keys and values displayed for an object. + * Elements past this number will be ellipised. + */ + var MAX_PRETTY_PRINT_ARRAY_LENGTH: number; + + /** + * Maximum number of charasters to display when pretty printing objects. + * Characters past this number will be ellipised. + */ + var MAX_PRETTY_PRINT_CHARS: number; + + /** + * Maximum object depth the pretty printer will print to. + * Set this to a lower value to speed up pretty printing if you have large objects. + */ + var MAX_PRETTY_PRINT_DEPTH: number; } declare module "jasmine" { diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index bf3598fda9..47cc77895c 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -16,7 +16,6 @@ describe("A suite is just a function", () => { }); describe("The 'toBe' matcher compares with ===", () => { - it("and has a positive case", () => { expect(true).toBe(true); }); @@ -27,28 +26,26 @@ describe("The 'toBe' matcher compares with ===", () => { }); describe("Included matchers:", () => { - it("The 'toBe' matcher compares with ===", () => { - var a = 12; - var b = a; + const a = 12; + const b = a; expect(a).toBe(b); expect(a).not.toBe(24); }); describe("The 'toEqual' matcher", () => { - it("works for simple literals and variables", () => { - var a = 12; + const a = 12; expect(a).toEqual(12); }); it("should work for objects", () => { - var foo = { + const foo = { a: 12, b: 34 }; - var bar = { + const bar = { a: 12, b: 34 }; @@ -56,13 +53,13 @@ describe("Included matchers:", () => { }); it("should work for optional values", () => { - var opt: string | undefined = "s"; - expect(opt as (string | undefined)).toEqual(undefined); + const opt: string | undefined = Math.random() > .5 ? "s" : undefined; + expect(opt).toEqual(undefined); }); }); it("The 'toMatch' matcher is for regular expressions", () => { - var message = "foo bar baz"; + const message = "foo bar baz"; expect(message).toMatch(/bar/); expect(message).toMatch("bar"); @@ -70,7 +67,7 @@ describe("Included matchers:", () => { }); it("The 'toBeDefined' matcher compares against `undefined`", () => { - var a = { + const a = { foo: "foo" }; @@ -79,7 +76,7 @@ describe("Included matchers:", () => { }); it("The `toBeUndefined` matcher compares against `undefined`", () => { - var a = { + const a = { foo: "foo" }; @@ -88,8 +85,8 @@ describe("Included matchers:", () => { }); it("The 'toBeNull' matcher compares against null", () => { - var a: string | null = null; - var foo = "foo"; + const a: string | null = Math.random() > 0.5 ? "s" : null; + const foo = "foo"; expect(null).toBeNull(); expect(a).toBeNull(); @@ -97,72 +94,76 @@ describe("Included matchers:", () => { }); it("The 'toBeTruthy' matcher is for boolean casting testing", () => { - var a: string | undefined, foo = "foo"; + const a: string | undefined = Math.random() > 0.5 ? "s" : undefined; + const foo = "foo"; expect(foo).toBeTruthy(); expect(a).not.toBeTruthy(); }); it("The 'toBeFalsy' matcher is for boolean casting testing", () => { - var a: string | undefined, foo = "foo"; + const a: string | undefined = Math.random() > 0.5 ? "s" : undefined; + const foo = "foo"; expect(a).toBeFalsy(); expect(foo).not.toBeFalsy(); }); it("The 'toContain' matcher is for finding an item in an Array", () => { - var a = ["foo", "bar", "baz"]; + const a = ["foo", "bar", "baz"]; expect(a).toContain('foo'); expect(a).not.toContain("quux"); }); it("The 'toContain' matcher is also for finding an object containing distinct properties in an Array", () => { - var a = [{ a: "foo" }, { a: "bar" }, { b: "baz" }]; + const a = [{ a: "foo" }, { a: "bar" }, { b: "baz" }]; expect(a).toContain(jasmine.objectContaining({ a: "foo" })); expect(a).not.toContain({ a: "quux" }); }); it("The 'toBeLessThan' matcher is for mathematical comparisons", () => { - var pi = 3.1415926, - e = 2.78; + const pi = 3.1415926; + const e = 2.78; expect(e).toBeLessThan(pi); expect(pi).not.toBeLessThan(e); }); it("The 'toBeGreaterThan' is for mathematical comparisons", () => { - var pi = 3.1415926, - e = 2.78; + const pi = 3.1415926; + const e = 2.78; expect(pi).toBeGreaterThan(e); expect(e).not.toBeGreaterThan(pi); }); it("The 'toBeCloseTo' matcher is for precision math comparison", () => { - var pi = 3.1415926, - e = 2.78; + const pi = 3.1415926; + const e = 2.78; expect(pi).not.toBeCloseTo(e, 2); expect(pi).toBeCloseTo(e, 0); }); it("The 'toThrow' matcher is for testing if a function throws an exception", () => { - var foo = () => { + const foo = () => { return 1 + 2; }; - var bar = () => { - var a: any; - return a + 1; + const bar = () => { + throw new Error("message"); }; expect(foo).not.toThrow(); + expect(foo).toThrow(); + + expect(bar).not.toThrow(); expect(bar).toThrow(); }); it("The 'toThrowError' matcher is for testing a specific thrown exception", () => { - var foo = () => { + const foo = () => { throw new TypeError("foo bar baz"); }; @@ -173,7 +174,7 @@ describe("Included matchers:", () => { }); it("async matchers", async () => { - var badness = new Error("badness"); + const badness = new Error("badness"); await expectAsync(Promise.resolve()).toBeResolved(); await expectAsync(Promise.resolve()).toBeResolved("good job"); await expectAsync(Promise.resolve(true)).toBeResolvedTo(true); @@ -184,8 +185,8 @@ describe("Included matchers:", () => { }); it("async matchers - not", async () => { - var badness = new Error("badness"); - var malady = new Error("malady"); + const badness = new Error("badness"); + const malady = new Error("malady"); await expectAsync(Promise.reject(badness)).not.toBeResolved(); await expectAsync(Promise.resolve(true)).not.toBeResolvedTo(false); await expectAsync(Promise.resolve()).not.toBeRejected(); @@ -198,7 +199,7 @@ describe("Included matchers:", () => { describe("toThrowMatching", () => { expect(() => { ({} as any).doSomething(); - }).toThrowMatching(error => error != undefined); + }).toThrowMatching(error => error !== undefined); }); describe("toBeNegativeInfinity", () => { @@ -306,7 +307,6 @@ xdescribe("A spec", () => { }); describe("Pending specs", () => { - xit("can be declared 'xit'", () => { expect(true).toBe(false); }); @@ -358,7 +358,7 @@ describe("A spy", () => { expect(bar).toBeNull(); }); - it("tracks if it was called at all", function () { + it("tracks if it was called at all", function() { foo.setBar(); expect(foo.setBar.calls.any()).toEqual(true); @@ -723,19 +723,24 @@ describe("A spy, when created manually", () => { }); describe("Multiple spies, when created manually", () => { - interface Tape { - play(): void; - pause(): void; - rewind(pos: number): void; - stop(): void; + class Tape { + private rewindTo: number; + play(): void { }; + pause(): void { }; + rewind(pos: number): void { + this.rewindTo = pos; + }; + stop(): void { }; readonly isPlaying: boolean; // spy obj makes this writable } - var tape: jasmine.SpyObj; + var tape: Tape; + var tapeSpy: jasmine.SpyObj; var el: jasmine.SpyObj; beforeEach(() => { - tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tapeSpy = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tape = tapeSpy; (tape as { isPlaying: boolean }).isPlaying = false; el = jasmine.createSpyObj('Element', ['hasAttribute']); @@ -745,6 +750,10 @@ describe("Multiple spies, when created manually", () => { tape.play(); tape.pause(); tape.rewind(0); + + tapeSpy.play.and.callThrough(); + tapeSpy.pause.and.callThrough(); + tapeSpy.rewind.and.callThrough(); }); it("creates spies for each requested function", () => { @@ -767,17 +776,15 @@ describe("Multiple spies, when created manually", () => { it("read isPlaying property", () => { expect(tape.isPlaying).toBe(false); - }) + }); }); describe("multiple spies, when created with spyOnAllFunctions", () => { - it("spies on all functions", () => { - const obj = { x: (a: number) => a, y: (a: number) => a, - } + }; spyOnAllFunctions(obj); @@ -809,7 +816,7 @@ describe("jasmine.any", () => { const a: Test = { fn1: () => { }, - fn2: (param1: number) => { return param1; }, + fn2: (param1: number) => param1, }; const expected: Test = { @@ -822,7 +829,7 @@ describe("jasmine.any", () => { describe("when used with a spy", () => { it("is useful for comparing arguments", () => { - var foo = jasmine.createSpy('foo'); + const foo = jasmine.createSpy('foo'); foo(12, () => { return true; }); @@ -867,7 +874,7 @@ describe("jasmine.objectContaining", () => { describe("when used with a spy", () => { it("is useful for comparing arguments", () => { - var callback = jasmine.createSpy('callback'); + const callback = jasmine.createSpy('callback'); callback({ bar: "baz" @@ -884,7 +891,7 @@ describe("jasmine.objectContaining", () => { }); describe("jasmine.arrayContaining", () => { - var foo: Array; + var foo: number[]; beforeEach(() => { foo = [1, 2, 3, 4]; @@ -900,7 +907,7 @@ describe("jasmine.arrayContaining", () => { describe("when used with a spy", () => { it("is useful when comparing arguments", () => { - var callback = jasmine.createSpy('callback'); + const callback = jasmine.createSpy('callback'); callback([1, 2, 3, 4]); @@ -911,7 +918,7 @@ describe("jasmine.arrayContaining", () => { }); describe("jasmine.arrayWithExactContents", () => { - var foo: Array; + var foo: number[]; beforeEach(() => { foo = [1, 2, 3, 4]; @@ -927,7 +934,7 @@ describe("jasmine.arrayWithExactContents", () => { describe("when used with a spy", () => { it("is useful when comparing arguments", () => { - var callback = jasmine.createSpy('callback'); + const callback = jasmine.createSpy('callback'); callback([1, 2, 3, 4]); @@ -980,7 +987,7 @@ describe("Manually ticking the Jasmine Clock", () => { describe("Mocking the Date object", () => { it("mocks the Date object and sets it to a given time", () => { - var baseTime = new Date(2013, 9, 23); + const baseTime = new Date(2013, 9, 23); jasmine.clock().mockDate(baseTime); @@ -1020,11 +1027,9 @@ describe("Asynchronous specs", () => { done(); }, 1000); }); - }); describe("Fail", () => { - it("should fail test when called without arguments", () => { fail(); }); @@ -1036,12 +1041,11 @@ describe("Fail", () => { it("should fail test when called an error", () => { fail(new Error("The test failed with this error")); }); - }); // test based on http://jasmine.github.io/2.2/custom_equality.html describe("custom equality", () => { - var myCustomEquality: jasmine.CustomEqualityTester = function (first: any, second: any): boolean | void { + const myCustomEquality: jasmine.CustomEqualityTester = function(first: any, second: any): boolean | void { if (typeof first === "string" && typeof second === "string") { return first[0] === second[1]; } @@ -1051,7 +1055,6 @@ describe("custom equality", () => { jasmine.addCustomEqualityTester(myCustomEquality); }); - it("should be custom equal", () => { expect("abc").toEqual("aaa"); }); @@ -1069,15 +1072,13 @@ var customMatchers: jasmine.CustomMatcherFactories = { if (expected === undefined) { expected = ''; } - var result: jasmine.CustomMatcherResult = { pass: false }; + const result: jasmine.CustomMatcherResult = { pass: false }; result.pass = util.equals(actual.hyuk, "gawrsh" + expected, customEqualityTesters); - if (result.pass) { - result.message = "Expected " + actual + " not to be quite so goofy"; - } else { - result.message = "Expected " + actual + " to be goofy, but it was not very goofy"; - } + result.message = result.pass ? + `Expected ${actual} not to be quite so goofy` : + `Expected ${actual} to be goofy, but it was not very goofy`; return result; } @@ -1110,8 +1111,8 @@ var customMatchers: jasmine.CustomMatcherFactories = { // } declare namespace jasmine { interface Matchers { - toBeGoofy(expected?: jasmine.Expected): boolean; - toBeWithinRange(expected?: jasmine.Expected, floor?: number, ceiling?: number): boolean; + toBeGoofy(expected?: Expected): boolean; + toBeWithinRange(expected?: Expected, floor?: number, ceiling?: number): boolean; } } @@ -1157,7 +1158,7 @@ describe("Custom matcher: 'toBeGoofy'", () => { const result = matcher.compare(actual, null); expect(result.pass).toBe(false); - expect(result.message).toBe("Expected " + actual + " to be goofy, but it was not very goofy"); + expect(result.message).toBe(`Expected ${actual} to be goofy, but it was not very goofy`); }); }); @@ -1168,16 +1169,16 @@ var myReporter: jasmine.CustomReporter = { }, suiteStarted: (result: jasmine.CustomReporterResult) => { - console.log("Suite started: " + result.description + " whose full description is: " + result.fullName); + console.log(`Suite started: ${result.description} whose full description is: ${result.fullName}`); }, specStarted: (result: jasmine.CustomReporterResult) => { - console.log("Spec started: " + result.description + " whose full description is: " + result.fullName); + console.log(`Spec started: ${result.description} whose full description is: ${result.fullName}`); }, specDone: (result: jasmine.CustomReporterResult) => { - console.log("Spec: " + result.description + " was " + result.status); - //tslint:disable-next-line:prefer-for-of + console.log(`Spec: ${result.description} was ${result.status}`); + // tslint:disable-next-line:prefer-for-of for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i += 1) { console.log("Failure: " + result.failedExpectations[i].message); console.log("Actual: " + result.failedExpectations[i].actual); @@ -1188,8 +1189,8 @@ var myReporter: jasmine.CustomReporter = { }, suiteDone: (result: jasmine.CustomReporterResult) => { - console.log('Suite: ' + result.description + ' was ' + result.status); - //tslint:disable-next-line:prefer-for-of + console.log(`Suite: ${result.description} was ${result.status}`); + // tslint:disable-next-line:prefer-for-of for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i += 1) { console.log('AfterAll ' + result.failedExpectations[i].message); console.log(result.failedExpectations[i].stack); @@ -1207,24 +1208,24 @@ jasmine.getEnv().addReporter(myReporter); describe("Randomize Tests", () => { it("should allow randomization of the order of tests", () => { expect(() => { - var env = jasmine.getEnv(); - return env.randomizeTests(true); + const env = jasmine.getEnv(); + env.randomizeTests(true); }).not.toThrow(); }); it("should allow a seed to be passed in for randomization", () => { expect(() => { - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); env.randomizeTests(true); return env.seed(1234); }).not.toThrow(); }); }); -//dest spces copied from jasmine project (https://github.com/jasmine/jasmine/blob/master/spec/core/SpecSpec.js) -describe("createSpyObj", function () { - it("should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object", function () { - var spyObj = jasmine.createSpyObj('BaseName', { 'method1': 42, 'method2': 'special sauce' }); +// Dest spces copied from jasmine project (https://github.com/jasmine/jasmine/blob/master/spec/core/SpecSpec.js) +describe("createSpyObj", function() { + it("should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object", function() { + const spyObj = jasmine.createSpyObj('BaseName', {method1: 42, method2: 'special sauce'}); expect(spyObj.method1()).toEqual(42); expect(spyObj.method1.and.identity()).toEqual('BaseName.method1'); @@ -1233,17 +1234,16 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); }); - - it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function () { - var spyObj = jasmine.createSpyObj('BaseName', ['method1', 'method2']); + it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function() { + const spyObj = jasmine.createSpyObj('BaseName', ['method1', 'method2']); expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); expect(spyObj.method1.and.identity()).toEqual('BaseName.method1'); expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); }); - it("should allow you to omit the baseName and takes only an object", function () { - var spyObj = jasmine.createSpyObj({ 'method1': 42, 'method2': 'special sauce' }); + it("should allow you to omit the baseName and takes only an object", function() { + const spyObj = jasmine.createSpyObj({method1: 42, method2: 'special sauce'}); expect(spyObj.method1()).toEqual(42); expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); @@ -1252,22 +1252,22 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); }); - it("should allow you to omit the baseName and takes only a list of methods", function () { - var spyObj = jasmine.createSpyObj(['method1', 'method2']); + it("should allow you to omit the baseName and takes only a list of methods", function() { + const spyObj = jasmine.createSpyObj(['method1', 'method2']); expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); }); - it("should throw if you pass an empty array argument", function () { - expect(function () { + it("should throw if you pass an empty array argument", function() { + expect(function() { jasmine.createSpyObj('BaseName', []); }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); }); - it("should throw if you pass an empty object argument", function () { - expect(function () { + it("should throw if you pass an empty object argument", function() { + expect(function() { jasmine.createSpyObj('BaseName', {}); }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); }); @@ -1275,17 +1275,17 @@ describe("createSpyObj", function () { (() => { // from boot.js - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); - var htmlReporter = new jasmine.HtmlReporter(); + const htmlReporter = new jasmine.HtmlReporter(); env.addReporter(htmlReporter); - var specFilter = new jasmine.HtmlSpecFilter(); + const specFilter = new jasmine.HtmlSpecFilter(); env.specFilter = (spec) => { return specFilter.matches(spec.getFullName()); }; - var currentWindowOnload = window.onload; + const currentWindowOnload = window.onload; window.onload = () => { if (currentWindowOnload) { (currentWindowOnload as any)(null); @@ -1293,7 +1293,6 @@ describe("createSpyObj", function () { htmlReporter.initialize(); env.execute(); }; - })(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; diff --git a/types/jasmine/tslint.json b/types/jasmine/tslint.json index 2daeb51ad8..c540ba0129 100644 --- a/types/jasmine/tslint.json +++ b/types/jasmine/tslint.json @@ -1,80 +1,13 @@ { "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": true, - "eofline": false, - "export-just-namespace": false, - "file-name-casing": [true, "kebab-case"], - "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 + "only-arrow-functions": false } } diff --git a/types/jasmine/v2/index.d.ts b/types/jasmine/v2/index.d.ts index 4211cf2ca0..a248093082 100644 --- a/types/jasmine/v2/index.d.ts +++ b/types/jasmine/v2/index.d.ts @@ -629,7 +629,7 @@ declare namespace jasmine { calls: Calls; } - type SpyObj = { + type SpyObj = T & { [k in keyof T]: T[k] extends Function ? T[k] & Spy : T[k]; } diff --git a/types/jasmine/v2/jasmine-tests.ts b/types/jasmine/v2/jasmine-tests.ts index f79c3627eb..167aca1981 100644 --- a/types/jasmine/v2/jasmine-tests.ts +++ b/types/jasmine/v2/jasmine-tests.ts @@ -643,19 +643,24 @@ describe("A spy, when created manually", () => { }); describe("Multiple spies, when created manually", () => { - interface Tape { - play(): void; - pause(): void; - rewind(pos: number): void; - stop(): void; + abstract class Tape { + private rewindTo: number; + play(): void { }; + pause(): void { }; + rewind(pos: number): void { + this.rewindTo = pos; + }; + stop(): void { }; readonly isPlaying: boolean; // spy obj makes this writable } - var tape: jasmine.SpyObj; + var tape: Tape; + var tapeSpy: jasmine.SpyObj; var el: jasmine.SpyObj; beforeEach(() => { - tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tapeSpy = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tape = tapeSpy; (tape as { isPlaying: boolean }).isPlaying = false; el = jasmine.createSpyObj('Element', ['hasAttribute']); @@ -665,6 +670,10 @@ describe("Multiple spies, when created manually", () => { tape.play(); tape.pause(); tape.rewind(0); + + tapeSpy.play.and.callThrough(); + tapeSpy.pause.and.callThrough(); + tapeSpy.rewind.and.callThrough(); }); it("creates spies for each requested function", () => { diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 4073e21087..368ed83353 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -71,8 +71,8 @@ declare namespace jest { */ function clearAllMocks(): typeof jest; /** - * Clears the mock.calls and mock.instances properties of all mocks. - * Equivalent to calling .mockClear() on every mocked function. + * Resets the state of all mocks. + * Equivalent to calling .mockReset() on every mocked function. */ function resetAllMocks(): typeof jest; /** diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 404e0339ef..8f5e7b7a2a 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for joi 14.0 +// Type definitions for joi 14.3 // Project: https://github.com/hapijs/joi // Definitions by: Bart van der Schoor // Laurence Dougal Myers @@ -110,9 +110,10 @@ export interface EmailOptions { export interface HexOptions { /** - * hex decoded representation must be byte aligned + * hex decoded representation must be byte aligned. + * @default false */ - byteAligned: boolean; + byteAligned?: boolean; } export interface IpOptions { @@ -211,6 +212,16 @@ export interface JoiObject { isJoi: boolean; } +export interface ErrorOptions { + /** + * Boolean value indicating whether the error handler should be used for all errors or only for errors occurring + * on this property (`true` value). + * This concept only makes sense for `array` or `object` schemas as other values don't have children. + * @default false + */ + self?: boolean; +} + export interface ValidationError extends Error, JoiObject { details: ValidationErrorItem[]; annotate(): string; @@ -266,6 +277,14 @@ export interface AnySchema extends JoiObject { allow(...values: any[]): this; allow(values: any[]): this; + /** + * By default, some Joi methods to function properly need to rely on the Joi instance they are attached to because + * they use `this` internally. + * So `Joi.string()` works but if you extract the function from it and call `string()` it won't. + * `bind()` creates a new Joi instance where all the functions relying on `this` are bound to the Joi instance. + */ + bind(): this; + /** * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. */ @@ -412,7 +431,7 @@ export interface AnySchema extends JoiObject { * 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; + error(err: Error | ValidationErrorFunction, options?: ErrorOptions): this; /** * Returns a plain object representing the schema's rules and properties @@ -681,6 +700,12 @@ export interface SymbolSchema extends AnySchema { } export interface ArraySchema extends AnySchema { + /** + * Verifies that an assertion passes for at least one item in the array, where: + * `schema` - the validation rules required to satisfy the assertion. If the `schema` includes references, they are resolved against + * the array item being tested, not the value of the `ref` target. + */ + assertItem(schema: SchemaLike): this; /** * Allow this array to be sparse. * enabled can be used with a falsy value to go back to the default behavior. @@ -797,6 +822,13 @@ export interface ObjectSchema extends AnySchema { or(...peers: string[]): this; or(peers: string[]): this; + /** + * Defines an exclusive relationship between a set of keys where only one is allowed but none are required where: + * `peers` - the exclusive key names that must not appear together but where none are required. + */ + oxor(...peers: string[]): this; + oxor(peers: string[]): this; + /** * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: */ diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index e21310396b..af85cab0ac 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -19,28 +19,28 @@ declare const expArr: RegExp[]; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let schema: Joi.Schema = null; +let schema: Joi.Schema = Joi.any(); 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; +let anySchema: Joi.AnySchema = Joi.any(); +let numSchema: Joi.NumberSchema = Joi.number(); +let strSchema: Joi.StringSchema = Joi.string(); +let arrSchema: Joi.ArraySchema = Joi.array(); +let boolSchema: Joi.BooleanSchema = Joi.boolean(); +let binSchema: Joi.BinarySchema = Joi.binary(); +let dateSchema: Joi.DateSchema = Joi.date(); +let funcSchema: Joi.FunctionSchema = Joi.func(); +let objSchema: Joi.ObjectSchema = Joi.object(); +let altSchema: Joi.AlternativesSchema = Joi.alternatives(); declare const schemaArr: Joi.Schema[]; -let ref: Joi.Reference = null; -let description: Joi.Description = null; +let ref: Joi.Reference = Joi.ref('test'); +let description: Joi.Description = {}; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let validOpts: Joi.ValidationOptions = null; +let validOpts: Joi.ValidationOptions = {}; validOpts = { abortEarly: bool }; validOpts = { convert: bool }; @@ -72,7 +72,7 @@ validOpts = { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let renOpts: Joi.RenameOptions = null; +let renOpts: Joi.RenameOptions = {}; renOpts = { alias: bool }; renOpts = { multiple: bool }; @@ -81,7 +81,7 @@ renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let emailOpts: Joi.EmailOptions = null; +let emailOpts: Joi.EmailOptions = {}; emailOpts = { errorLevel: num }; emailOpts = { errorLevel: bool }; @@ -91,13 +91,13 @@ emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let hexOpts: Joi.HexOptions = null; +let hexOpts: Joi.HexOptions = {}; hexOpts = { byteAligned: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let ipOpts: Joi.IpOptions = null; +let ipOpts: Joi.IpOptions = {}; ipOpts = { version: str }; ipOpts = { version: strArr }; @@ -105,7 +105,7 @@ ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let uriOpts: Joi.UriOptions = null; +let uriOpts: Joi.UriOptions = {}; uriOpts = { scheme: str }; uriOpts = { scheme: exp }; @@ -114,19 +114,21 @@ uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let base64Opts: Joi.Base64Options = null; +let base64Opts: Joi.Base64Options = {}; base64Opts = { paddingRequired: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let dataUriOpts: Joi.DataUriOptions = null; +let dataUriOpts: Joi.DataUriOptions = {}; dataUriOpts = { paddingRequired: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let whenOpts: Joi.WhenOptions = null; +let whenOpts: Joi.WhenOptions = { + is: Joi.any(), +}; whenOpts = { is: x }; whenOpts = { is: schema, then: schema }; @@ -135,7 +137,7 @@ whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let whenSchemaOpts: Joi.WhenSchemaOptions = null; +let whenSchemaOpts: Joi.WhenSchemaOptions = {}; whenSchemaOpts = { then: schema }; whenSchemaOpts = { otherwise: schema }; @@ -143,14 +145,14 @@ whenSchemaOpts = { then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let refOpts: Joi.ReferenceOptions = null; +let refOpts: Joi.ReferenceOptions = {}; refOpts = { separator: str }; refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let stringRegexOpts: Joi.StringRegexOptions = null; +let stringRegexOpts: Joi.StringRegexOptions = {}; stringRegexOpts = { name: str }; stringRegexOpts = { invert: bool }; @@ -204,7 +206,7 @@ anySchema = objSchema; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let schemaMap: Joi.SchemaMap = null; +let schemaMap: Joi.SchemaMap = {}; schemaMap = { a: numSchema, @@ -246,6 +248,7 @@ anySchema = Joi.any(); anySchema = anySchema.allow(x); anySchema = anySchema.allow(x, x); anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.bind(); anySchema = anySchema.valid(x); anySchema = anySchema.valid(x, x); anySchema = anySchema.valid([x, x, x]); @@ -302,12 +305,14 @@ anySchema = Joi.any(); anySchema = anySchema.error(err); anySchema = anySchema.error(validErrFunc); + anySchema = anySchema.error(validErrFunc, { self: true }); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- arrSchema = Joi.array(); +arrSchema = arrSchema.assertItem(Joi.any()); arrSchema = arrSchema.sparse(); arrSchema = arrSchema.sparse(bool); arrSchema = arrSchema.single(); @@ -706,6 +711,11 @@ objSchema = objSchema.or(str, str); objSchema = objSchema.or(str, str, str); objSchema = objSchema.or(strArr); +objSchema = objSchema.oxor(str); +objSchema = objSchema.oxor(str, str); +objSchema = objSchema.oxor(str, str, str); +objSchema = objSchema.oxor(strArr); + objSchema = objSchema.xor(str); objSchema = objSchema.xor(str, str); objSchema = objSchema.xor(str, str, str); diff --git a/types/joi/tsconfig.json b/types/joi/tsconfig.json index 57e6c47881..09319363d5 100644 --- a/types/joi/tsconfig.json +++ b/types/joi/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/jquery/v2/index.d.ts b/types/jquery/v2/index.d.ts index 2643960e6d..068bbfc991 100644 --- a/types/jquery/v2/index.d.ts +++ b/types/jquery/v2/index.d.ts @@ -603,6 +603,14 @@ interface BaseJQueryEventObject extends Event { metaKey: boolean; } +interface JQueryCustomEventObject extends BaseJQueryEventObject { + /** + * @see {@link https://api.jquery.com/category/events/event-object/} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent} + */ + detail?: any; +} + interface JQueryInputEventObject extends BaseJQueryEventObject { altKey: boolean; ctrlKey: boolean; @@ -632,7 +640,7 @@ interface JQueryKeyEventObject extends JQueryInputEventObject { keyCode: number; } -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ +interface JQueryEventObject extends BaseJQueryEventObject, JQueryCustomEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { } /** diff --git a/types/js-levenshtein/index.d.ts b/types/js-levenshtein/index.d.ts new file mode 100644 index 0000000000..5b29d11026 --- /dev/null +++ b/types/js-levenshtein/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for js-levenshtein 1.1 +// Project: https://github.com/gustf/js-levenshtein +// Definitions by: Kallu609 +// Pyry Rouvila +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Calculates Levenshtein distance between two strings + */ +declare function levenshtein(compareFrom: string, compareTo: string): number; + +export = levenshtein; diff --git a/types/js-levenshtein/js-levenshtein-tests.ts b/types/js-levenshtein/js-levenshtein-tests.ts new file mode 100644 index 0000000000..539473ccf4 --- /dev/null +++ b/types/js-levenshtein/js-levenshtein-tests.ts @@ -0,0 +1,3 @@ +import levenshtein = require('js-levenshtein'); + +levenshtein('kittens', 'mittens'); // $ExpectType number diff --git a/types/js-levenshtein/tsconfig.json b/types/js-levenshtein/tsconfig.json new file mode 100644 index 0000000000..6df128481b --- /dev/null +++ b/types/js-levenshtein/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", "js-levenshtein-tests.ts"] +} diff --git a/types/js-levenshtein/tslint.json b/types/js-levenshtein/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/js-levenshtein/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/js-types/index.d.ts b/types/js-types/index.d.ts new file mode 100644 index 0000000000..756680fd04 --- /dev/null +++ b/types/js-types/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for js-types 2.0 +// Project: https://github.com/sindresorhus/js-types#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = jsTypes; + +declare const jsTypes: string[]; diff --git a/types/js-types/js-types-tests.ts b/types/js-types/js-types-tests.ts new file mode 100644 index 0000000000..b7e5a4fe8b --- /dev/null +++ b/types/js-types/js-types-tests.ts @@ -0,0 +1,5 @@ +import jsTypes = require('js-types'); +import jsTypesJson = require('js-types/js-types.json'); + +jsTypes; // $ExpectType string[] +jsTypesJson; // $ExpectType string[] diff --git a/types/js-types/js-types.json.d.ts b/types/js-types/js-types.json.d.ts new file mode 100644 index 0000000000..83565f43d1 --- /dev/null +++ b/types/js-types/js-types.json.d.ts @@ -0,0 +1,3 @@ +export = jsTypes; + +declare const jsTypes: string[]; diff --git a/types/js-types/tsconfig.json b/types/js-types/tsconfig.json new file mode 100644 index 0000000000..1b81a82e27 --- /dev/null +++ b/types/js-types/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", + "js-types.json.d.ts", + "js-types-tests.ts" + ] +} diff --git a/types/js-types/tslint.json b/types/js-types/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/js-types/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 49ba2807a7..b59741e74e 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-yaml 3.11 +// Type definitions for js-yaml 3.12 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -52,6 +52,8 @@ export interface LoadOptions { export interface DumpOptions { /** indentation width to use (in spaces). */ indent?: number; + /** when true, will not add an indentation level to array elements */ + noArrayIndent?: boolean; /** do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. */ skipInvalid?: boolean; /** specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere */ diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index d3d90131d1..304da7731d 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -72,6 +72,9 @@ loadOpts = { dumpOpts = { indent: num }; +dumpOpts = { + noArrayIndent: bool +}; dumpOpts = { skipInvalid: bool }; diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index 1420723b8d..0b8be95052 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -1,4 +1,4 @@ -import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow, ResourceLoader, FetchOptions } from 'jsdom'; +import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow, ResourceLoader, FetchOptions, ConstructorOptions } from 'jsdom'; import { CookieJar as ToughCookieJar, MemoryCookieStore } from 'tough-cookie'; import { Script } from 'vm'; @@ -56,8 +56,9 @@ function test_cookieJar() { const store = {} as MemoryCookieStore; const options = {} as ToughCookieJar.Options; - const cookieJar = new CookieJar(store, options); - const dom = new JSDOM(``, { cookieJar }); + const cookieJar: CookieJar = new CookieJar(store, options); + const constructorOptions: ConstructorOptions = { cookieJar }; + const dom = new JSDOM(``, constructorOptions); } function test_beforeParse() { diff --git a/types/jsonabc/index.d.ts b/types/jsonabc/index.d.ts new file mode 100644 index 0000000000..41a785d015 --- /dev/null +++ b/types/jsonabc/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for jsonabc 2.3 +// Project: http://novicelab.org/jsonabc +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Sort the JSON (clean, parse, sort, stringify). + * @param noArray Sort or don't sort arrays + */ +export function sort(inputStr: string, noArray?: boolean): string; + +/** + * Sort the JSON (clean, parse, sort, stringify). + * @param noArray Sort or don't sort arrays + */ +export function sortObj(input: object, noArray?: boolean): object; + +/** Remove trailing commas */ +export function cleanJSON(input: string): string; diff --git a/types/jsonabc/jsonabc-tests.ts b/types/jsonabc/jsonabc-tests.ts new file mode 100644 index 0000000000..8d51d94bac --- /dev/null +++ b/types/jsonabc/jsonabc-tests.ts @@ -0,0 +1,9 @@ +import * as myJsonAbc from 'jsonabc'; + +myJsonAbc.sortObj({ c: 0, b: 1, a: 0 }); +myJsonAbc.sortObj({ c: 0, b: 1, a: 0 }, false); + +myJsonAbc.sort('{ c: 0, b: 1, a: 0 }'); +myJsonAbc.sort('{ c: 0, b: 1, a: 0 }', true); + +myJsonAbc.cleanJSON('{ c: 0, b: 1, a: 0 }'); diff --git a/types/jsonabc/tsconfig.json b/types/jsonabc/tsconfig.json new file mode 100644 index 0000000000..072c667a18 --- /dev/null +++ b/types/jsonabc/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", + "jsonabc-tests.ts" + ] +} diff --git a/types/jsonabc/tslint.json b/types/jsonabc/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsonabc/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsonapi-serializer/index.d.ts b/types/jsonapi-serializer/index.d.ts new file mode 100644 index 0000000000..4d9344bc28 --- /dev/null +++ b/types/jsonapi-serializer/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for jsonapi-serializer 3.6 +// Project: https://github.com/SeyZ/jsonapi-serializer#readme +// Definitions by: Frank Chiang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.2 + +export type RefFunction = (current: any, item: any) => string; + +export interface Relation { + ref: string | RefFunction; + attributes?: string[]; + included?: boolean; +} + +export interface SerializerOptions { + ref?: (() => void) | boolean | string; + included?: boolean; + id?: string; + attributes?: string[]; + topLevelLinks?: string[] | Array<() => void>; + dataLinks?: string[] | Array<() => void>; + dataMeta?: (() => void) | object; + relationshipLinks?: object; + relationshipMeta?: object; + ignoreRelationshipData?: boolean; + keyForAttribute?: string | KeyForAttribute; + nullIfMissing?: boolean; + pluralizeType?: boolean; + typeForAttribute?: TypeForAttribute; + meta?: object; + transform?: (() => void); +} + +export interface KeyForAttribute { + (attribute: string): string; +} + +export interface TypeForAttribute { + (attribute: string, object?: any): any; +} + +export interface Transform { + (record: any): any; +} + +export interface DeserializerOptions { + id?: string; + keyForAttribute?: + | "dash-case" + | "lisp-case" + | "spinal-case" + | "kebab-case" + | "underscore_case" + | "snake_case" + | "camelCase" + | "CamelCase"; + pluralizeType?: boolean; + typeAsAttribute?: boolean; + transform?: Transform; +} + +export interface DeserializerConstructor { + new (opts: DeserializerOptions): Deserializer; +} + +export interface SerializerConstructor { + new (collectionName: string, opts: SerializerOptions): Serializer; +} + +export interface ErrorConstructor { + new (opts: JSONAPIErrorOptions | JSONAPIErrorOptions[]): JSONAPIError; +} + +export interface JSONAPIError { + errors: any[]; +} + +export interface JSONAPIErrorOptions { + id?: string; + status?: string; + code?: string; + title?: string; + detail?: string; + source?: { + pointer?: string; + parameter?: string; + }; + links?: { + about?: string; + }; + meta?: any; +} + +export interface Serializer { + serialize(data: any): any; +} + +export interface Deserializer { + deserialize(data: any, callback: Callback): void; + + deserialize(data: any): Promise; +} + +export interface Callback { + (error: Error, response: any): any; +} + +export let Serializer: SerializerConstructor; +export let Deserializer: DeserializerConstructor; +export let Error: ErrorConstructor; diff --git a/types/jsonapi-serializer/jsonapi-serializer-tests.ts b/types/jsonapi-serializer/jsonapi-serializer-tests.ts new file mode 100644 index 0000000000..cd560cca77 --- /dev/null +++ b/types/jsonapi-serializer/jsonapi-serializer-tests.ts @@ -0,0 +1,37 @@ +import { Serializer, Deserializer, Error } from "jsonapi-serializer"; + +declare let firstName: string; +declare let lastName: string; + +const UserSerializer = new Serializer("users", { + id: "id", + attributes: ["firstName", "lastName"], + keyForAttribute: "camelCase", + pluralizeType: false +}); + +const users = UserSerializer.serialize({ firstName, lastName }); + +const UserDeserializer = new Deserializer({ + id: "id", + keyForAttribute: "camelCase", + pluralizeType: false, + typeAsAttribute: true +}); + +UserDeserializer.deserialize(users); + +new Error({ + code: "_code", + detail: "_detail", + id: "_id", + links: { + about: "_about" + }, + source: { + parameter: "_parameter", + pointer: "_pointer" + }, + status: "_status", + title: "_title" +}); diff --git a/types/jsonapi-serializer/tsconfig.json b/types/jsonapi-serializer/tsconfig.json new file mode 100644 index 0000000000..eeea88010a --- /dev/null +++ b/types/jsonapi-serializer/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", "jsonapi-serializer-tests.ts"] +} diff --git a/types/jsonapi-serializer/tslint.json b/types/jsonapi-serializer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsonapi-serializer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/junk/index.d.ts b/types/junk/index.d.ts new file mode 100644 index 0000000000..390847e1c0 --- /dev/null +++ b/types/junk/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for junk 2.1 +// Project: https://github.com/sindresorhus/junk#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Returns `true` if `filename` matches a junk file. + */ +export function is(filename: string): boolean; +/** + * Returns `true` if `filename` doesn't match a junk file. + */ +export function not(filename: string): boolean; +/** + * Regex used for matching. + */ +export const regex: RegExp; diff --git a/types/junk/junk-tests.ts b/types/junk/junk-tests.ts new file mode 100644 index 0000000000..848eded660 --- /dev/null +++ b/types/junk/junk-tests.ts @@ -0,0 +1,12 @@ +/// + +import fs = require('fs'); +import * as junk from 'junk'; + +junk.is('foo'); // $ExpectType boolean +junk.not('foo'); // $ExpectType boolean +junk.regex; // $ExpectType RegExp + +fs.readdir('some/path', (err, files) => { + files.filter(junk.not); +}); diff --git a/types/junk/tsconfig.json b/types/junk/tsconfig.json new file mode 100644 index 0000000000..06710a9591 --- /dev/null +++ b/types/junk/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", + "junk-tests.ts" + ] +} diff --git a/types/junk/tslint.json b/types/junk/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/junk/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index 1d65bca261..05d9c50aa6 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -1,509 +1,373 @@ -// Type definitions for JW Player V8.2 -// Project: https://github.com/jwplayer/jwplayer/ +// Type definitions for JW Player 8.2 +// Project: https://github.com/jwplayer/jwplayer // Definitions by: Martin Duparc // Tomer Kruvi // Philipp Gürtler // Daniel McGraw // Benjamin Dobson -// Be Birchall +// Be Birchall +// Daniel Cassidy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 // JW Player is the leading HTML5 & Flash video player, optimized for mobile and the desktop. Easy enough for beginners, advanced enough for pros. -interface Version { - version: string; - major: number; - minor: number +declare namespace jwplayer { + interface Version { + version: string; + major: number; + minor: number; + } + + interface Browser { + chrome: boolean; + edge: boolean; + facebook: boolean; + firefox: boolean; + ie: boolean; + msie: boolean; + safari: boolean; + version: Version; + } + + interface OS { + android: boolean; + androidNative: boolean; // Android native browser + iOS: boolean; + mobile: boolean; + mac: boolean; + iPad: boolean; + iPhone: boolean; + windows: boolean; + version: Version; + } + + interface Features { + flash: boolean; + flashVersion: number; + iframe: boolean; + } + + interface Environment { + Browser: Browser; + OS: OS; + Features: Features; + } + + interface AdProgressParam { + client: 'vast' | 'googima'; + creativetype: string; + tag: string; + } + + interface AdCompanionsParam { + companions: any[]; + tag: string; + } + + interface AdErrorParam { + message: string; + tag: string; + } + + interface AdRequestParam { + adposition: 'pre' | 'mid' | 'post'; + client: 'vast' | 'googima'; + offset: 'pre' | 'mid' | 'post'; + tag: string; + } + + interface AdImpressionParam { + adposition: 'pre' | 'mid' | 'post'; + adsystem: string; + adtitle: string; + clickThroughUrl: string; + client: 'vast' | 'googima'; + creativetype: string; + linear: string; + mediafile: any; + tag: string; + vastversion: number; + wrapper: any[]; + } + + interface AdScheduleParam { + tag: string; + client: string; + adbreaks: object[]; + } + + interface AdStartedParam { + creativetype: string; + tag: string; + } + + interface AdPlayParam { + creativetype: string; + newstate: string; + oldstate: string; + tag: string; + } + + interface BufferParam { + newstate: string; + oldstate: string; + reason: 'loading' | 'complete' | 'stalled' | 'error'; + } + + interface BufferChangeParam { + duration: number; + bufferPercent: number; + position: number; + metadata: any; + } + + interface AdTimeParam { + client: 'vast' | 'googima'; + creativetype: string; + duration: number; + position: number; + sequence: number; + tag: string; + } + + interface AudioTracksParam { + levels: any[]; + } + + interface CaptionsChangedParam { + currentTrack: number; + } + + interface CaptionsListParam { + tracks: any[]; + } + + interface AudioTrackChangedParam { + currentTrack: number; + } + + interface MetadataParam { + metadata: any; + } + + interface ControlsParam { + controls: boolean; + } + + interface ErrorParam { + message: string; + } + + interface FullscreenParam { + fullscreen: boolean; + } + + interface IdleParam { + oldstate: 'buffering' | 'playing' | 'paused'; + } + + interface LevelsChangedParam { + currentQuality: number; + } + + interface MuteParam { + mute: boolean; + } + + interface VolumeParam { + volume: boolean; + } + + interface PlayParam { + oldstate: 'buffering' | 'playing'; + viewable: 0 | 1; + } + + interface PlaylistParam { + playlist: any[]; + } + + interface PlaylistItemParam { + index: number; + item: any; + } + + interface ReadyParam { + setupTime: number; + viewable: 0 | 1; + } + + interface ResizeParam { + width: number; + height: number; + } + + interface VisualQualityParam { + mode: string; + label: string; + reason: string; + } + + interface LevelsParam { + width: number; + levels: any[]; + } + + interface SeekParam { + position: number; + offset: number; + } + + interface TimeParam { + duration: number; + position: number; + viewable: 0 | 1; + } + + interface FirstFrameParam { + loadTime: number; + viewable: 0 | 1; + } + + type EventCallback = (param: T) => void; + + interface Region { + x: 0; // x and y will always be 0 according to https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayergetsaferegion + y: 0; + width: number; + height: number; + } + + interface CaptionOptions { + color: string; + fontSize: number; + fontFamily: string; + fontOpacity: number; + backgroundColor: string; + backgroundOpacity: number; + edgeStyle: string; + windowColor: string; + windowOpacity: number; + } + + interface Level { + bitrate: number; + height: number; + width: number; + label: string; + } + + interface QualityLevel { + mode: 'auto' | 'manual'; + level: Level; + reason: 'auto' | 'api' | 'initial choice'; + } + + interface EventParams { + adClick: AdProgressParam; + adCompanions: AdCompanionsParam; + adComplete: AdProgressParam; + adSkipped: AdProgressParam; + adError: AdErrorParam; + adRequest: AdRequestParam; + adSchedule: AdScheduleParam; + adStarted: AdStartedParam; + adImpression: AdImpressionParam; + adPlay: AdPlayParam; + adPause: AdPlayParam; + adTime: AdTimeParam; + meta: MetadataParam; + audioTracks: AudioTracksParam; + audioTrackChanged: AudioTrackChangedParam; + firstFrame: FirstFrameParam; + buffer: BufferParam; + bufferChange: BufferChangeParam; + captionsChanged: CaptionsChangedParam; + captionsList: CaptionsListParam; + controls: ControlsParam; + error: ErrorParam; + fullscreen: FullscreenParam; + idle: IdleParam; + levelsChanged: LevelsChangedParam; + mute: MuteParam; + volume: VolumeParam; + pause: PlayParam; + play: PlayParam; + playlist: PlaylistParam; + playlistItem: PlaylistItemParam; + ready: ReadyParam; + resize: ResizeParam; + visualQuality: VisualQualityParam; + levels: LevelsParam; + seek: SeekParam; + setupError: ErrorParam; + time: TimeParam; + } + + type NoParamEvent = 'adBlock' | 'beforeComplete' | 'complete' | 'beforePlay' | 'displayClick' | 'playlistComplete' + | 'seeked' | 'remove'; + + interface JWPlayer { + addButton(icon: string, label: string, handler: () => void, id: string): void; + getAudioTracks(): any[]; + getBuffer(): number; + getCaptionsList(): any[]; + getControls(): boolean; + getCurrentAudioTrack(): number; + getCurrentCaptions(): number; + getCurrentQuality(): number; + getDuration(): number; + getHeight(): number; + getFullscreen(): boolean; + getMute(): boolean; + getPlaylist(): any[]; + getPlaylistIndex(): number; + getPlaylistItem(index?: number): any; + getPosition(): number; + getQualityLevels(): any[]; + getRenderingMode(): string; + getSafeRegion(): Region; + getState(): string; + getVolume(): number; + getContainer(): HTMLElement; + getEnvironment(): Environment; + getWidth(): number; + getVisualQuality(): QualityLevel | undefined; + load(playlist: any[] | string): void; + on(event: TEvent, callback: EventCallback): void; + on(event: NoParamEvent, callback: () => void): void; + once(event: TEvent, callback: EventCallback): void; + once(event: NoParamEvent, callback: () => void): void; + off(event: keyof EventParams | NoParamEvent): void; + trigger(event: TEvent, args: EventParams[TEvent]): void; + trigger(event: NoParamEvent): void; + pause(state?: boolean): void; + play(state?: boolean): void; + playAd(tag: string): void; + playlistItem(index: number): void; + registerPlugin(id: string, target: string, jsPlugin: () => void, swfURL?: string): void; + remove(): void; + removeButton(id: string): void; + resize(width: number, height: number): void; + seek(position: number): void; + setControls(controls: boolean): void; + setCurrentAudioTrack(index: number): void; + setCurrentCaptions(index: number): void; + setCurrentQuality(index: number): void; + setFullscreen(state: boolean): void; + setMute(state?: boolean): void; + setup(options: any): JWPlayer; + setVolume(volume: number): void; + setCaptions(options: CaptionOptions): void; + stop(): void; + } + + interface JWPlayerStatic { + (query?: string | number | Element): JWPlayer; + key: string; + version: string; + } } -interface Browser { - chrome: boolean; - edge: boolean; - facebook: boolean; - firefox: boolean; - ie: boolean; - msie: boolean; - safari: boolean; - version: Version; -} - -interface OS { - android: boolean; - androidNative: boolean; // Android native browser - iOS: boolean; - mobile: boolean; - mac: boolean; - iPad: boolean; - iPhone: boolean; - windows: boolean; - version: Version; -} - -interface Features { - flash: boolean; - flashVersion: number; - iframe: boolean; -} - -interface Environment{ - Browser: Browser; - OS: OS; - Features: Features; -} - -interface CallbackParam { -} - -interface AdProgressParam extends CallbackParam { - client: 'vast' | 'googima'; - creativetype: string; - tag: string; -} - -interface AdCompanionsParam extends CallbackParam { - companions: any[]; - tag: string; -} - -interface AdErrorParam extends CallbackParam { - message: string; - tag: string; -} - -interface AdRequestParam extends CallbackParam { - adposition: 'pre' | 'mid' | 'post'; - client: 'vast' | 'googima'; - offset: 'pre' | 'mid' | 'post'; - tag: string; -} - -interface AdImpressionParam extends CallbackParam { - adposition: 'pre' | 'mid' | 'post'; - adsystem: string; - adtitle: string; - clickThroughUrl: string; - client: 'vast' | 'googima'; - creativetype: string; - linear: string; - mediafile: any; - tag: string; - vastversion: number; - wrapper: any[]; -} - -interface AdScheduleParam extends CallbackParam { - tag: string; - client: string; - adbreaks: object[]; -} - -interface AdStartedParam extends CallbackParam { - creativetype: string; - tag: string; -} - -interface AdPlayParam extends CallbackParam { - creativetype: string; - newstate: string; - oldstate: string; - tag: string; -} - -interface BufferParam extends CallbackParam { - newstate: string; - oldstate: string; - reason: 'loading' | 'complete' | 'stalled' | 'error'; -} - -interface BufferChangeParam extends CallbackParam { - duration: number; - bufferPercent: number; - position: number; - metadata: any; -} - -interface AdTimeParam extends CallbackParam { - client: 'vast' | 'googima'; - creativetype: string; - duration: number; - position: number; - sequence: number; - tag: string; -} - -interface AudioTracksParam extends CallbackParam { - levels: any[]; -} - -interface CaptionsChangedParam extends CallbackParam { - currentTrack: number; -} - -interface CaptionsListParam extends CallbackParam { - tracks: any[]; -} - -interface AudioTrackChangedParam extends CallbackParam { - currentTrack: number; -} - -interface MetadataParam extends CallbackParam { - metadata: any; -} - -interface ControlsParam extends CallbackParam { - controls: boolean; -} - -interface ErrorParam extends CallbackParam { - message: string; -} - -interface FullscreenParam extends CallbackParam { - fullscreen: boolean; -} - -interface IdleParam extends CallbackParam { - oldstate: 'buffering' | 'playing' | 'paused'; -} - -interface LevelsChangedParam extends CallbackParam { - currentQuality: number; -} - -interface MuteParam extends CallbackParam { - mute: boolean; -} - -interface VolumeParam extends CallbackParam { - volume: boolean; -} - -interface PlayParam extends CallbackParam { - oldstate: 'buffering' | 'playing'; - viewable: 0 | 1; -} - -interface PlaylistParam extends CallbackParam { - playlist: any[]; -} - -interface PlaylistItemParam extends CallbackParam { - index: number; - item: any; -} - -interface ReadyParam extends CallbackParam { - setupTime: number; - viewable: 0 | 1; -} - -interface ResizeParam extends CallbackParam { - width: number; - height: number; -} - -interface VisualQualityParam extends CallbackParam { - mode: string; - label: string; - reason: string; -} - -interface LevelsParam extends CallbackParam { - width: number; - levels: any[]; -} - -interface SeekParam extends CallbackParam { - position: number; - offset: number; -} - -interface TimeParam extends CallbackParam { - duration: number; - position: number; - viewable: 0 | 1; -} - -interface FirstFrameParam extends CallbackParam { - loadTime: number; - viewable: 0 | 1; -} - -interface EventCallback { - (param: T): void; -} - -interface Region { - x: 0; // x and y will always be 0 according to https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayergetsaferegion - y: 0; - width: number; - height: number; -} - -interface CaptionOptions { - color: string; - fontSize: number; - fontFamily: string; - fontOpacity: number; - backgroundColor: string; - backgroundOpacity: number; - edgeStyle: string; - windowColor: string; - windowOpacity: number; -} - -interface Level { - bitrate: number; - height: number; - width: number; - label: string; -} - -interface QualityLevel { - mode: 'auto' | 'manual'; - level: Level; - reason: 'auto' | 'api' | 'initial choice'; -} - -interface JWPlayer { - addButton(icon: string, label: string, handler: () => void, id: string): void; - getAudioTracks(): any[]; - getBuffer(): number; - getCaptionsList(): any[]; - getControls(): boolean; - getCurrentAudioTrack(): number; - getCurrentCaptions(): number; - getCurrentQuality(): number; - getDuration(): number; - getHeight(): number; - getFullscreen(): boolean; - getMute(): boolean; - getPlaylist(): any[]; - getPlaylistIndex(): number; - getPlaylistItem(index?: number): any; - getPosition(): number; - getQualityLevels(): any[]; - getRenderingMode(): string; - getSafeRegion(): Region; - getState(): string; - getVolume(): number; - getContainer(): HTMLElement; - getEnvironment(): Environment; - getWidth(): number; - getVisualQuality(): QualityLevel | undefined; - load(playlist: any[]): void; - load(playlist: string): void; - on(event: 'adClick', callback: EventCallback): void; - once(event: 'adClick', callback: EventCallback): void; - off(event: 'adClick'): void; - trigger(event: 'adClick', args: AdProgressParam): void; - on(event: 'adCompanions', callback: EventCallback): void; - once(event: 'adCompanions', callback: EventCallback): void; - off(event: 'adCompanions'): void; - trigger(event: 'adCompanions', args: AdCompanionsParam): void; - on(event: 'adComplete', callback: EventCallback): void; - once(event: 'adComplete', callback: EventCallback): void; - off(event: 'adComplete'): void; - trigger(event: 'adComplete', args: AdProgressParam): void; - on(event: 'adSkipped', callback: EventCallback): void; - once(event: 'adSkipped', callback: EventCallback): void; - off(event: 'adSkipped'): void; - trigger(event: 'adSkipped', args: AdProgressParam): void; - on(event: 'adError', callback: EventCallback): void; - once(event: 'adError', callback: EventCallback): void; - off(event: 'adError'): void; - trigger(event: 'adError', args: AdErrorParam): void; - on(event: 'adBlock', callback: () => void): void; - once(event: 'adBlock', callback: () => void): void; - off(event: 'adBlock'): void; - trigger(event: 'adBlock'): void; - on(event: 'adRequest', callback: EventCallback): void; - once(event: 'adRequest', callback: EventCallback): void; - off(event: 'adRequest'): void; - trigger(event: 'adRequest', args: AdRequestParam): void; - on(event: 'adSchedule', callback: EventCallback): void; - once(event: 'adSchedule', callback: EventCallback): void; - off(event: 'adSchedule'): void; - trigger(event: 'adSchedule', args: AdScheduleParam): void; - on(event: 'adStarted', callback: EventCallback): void; - once(event: 'adStarted', callback: EventCallback): void; - off(event: 'adStarted'): void; - trigger(event: 'adStarted', args: AdStartedParam): void; - on(event: 'adImpression', callback: EventCallback): void; - once(event: 'adImpression', callback: EventCallback): void; - off(event: 'adImpression'): void; - trigger(event: 'adImpression', args: AdImpressionParam): void; - on(event: 'adPlay', callback: EventCallback): void; - once(event: 'adPlay', callback: EventCallback): void; - off(event: 'adPlay'): void; - trigger(event: 'adPlay', args: AdPlayParam): void; - on(event: 'adPause', callback: EventCallback): void; - once(event: 'adPause', callback: EventCallback): void; - off(event: 'adPause'): void; - trigger(event: 'adPause', args: AdPlayParam): void; - on(event: 'adTime', callback: EventCallback): void; - once(event: 'adTime', callback: EventCallback): void; - off(event: 'adTime'): void; - trigger(event: 'adTime', args: AdTimeParam): void; - on(event: 'meta', callback: EventCallback): void; - once(event: 'meta', callback: EventCallback): void; - off(event: 'meta'): void; - trigger(event: 'meta', args: MetadataParam): void; - on(event: 'audioTracks', callback: EventCallback): void; - once(event: 'audioTracks', callback: EventCallback): void; - off(event: 'audioTracks'): void; - trigger(event: 'audioTracks', args: AudioTracksParam): void; - on(event: 'audioTrackChanged', callback: EventCallback): void; - once(event: 'audioTrackChanged', callback: EventCallback): void; - off(event: 'audioTrackChanged'): void; - trigger(event: 'audioTrackChanged', args: AudioTrackChangedParam): void; - on(event: 'beforeComplete', callback: () => void): void; - once(event: 'beforeComplete', callback: () => void): void; - off(event: 'beforeComplete'): void; - trigger(event: 'beforeComplete'): void; - on(event: 'complete', callback: () => void): void; - once(event: 'complete', callback: () => void): void; - off(event: 'complete'): void; - trigger(event: 'complete'): void; - on(event: 'firstFrame', callback: EventCallback): void; - once(event: 'firstFrame', callback: EventCallback): void; - off(event: 'firstFrame'): void; - trigger(event: 'firstFrame', args: FirstFrameParam): void; - on(event: 'beforePlay', callback: () => void): void; - once(event: 'beforePlay', callback: () => void): void; - off(event: 'beforePlay'): void; - trigger(event: 'beforePlay'): void; - on(event: 'buffer', callback: EventCallback): void; - once(event: 'buffer', callback: EventCallback): void; - off(event: 'buffer'): void; - trigger(event: 'buffer', args: BufferParam): void; - on(event: 'bufferChange', callback: EventCallback): void; - once(event: 'bufferChange', callback: EventCallback): void; - off(event: 'bufferChange'): void; - trigger(event: 'bufferChange', args: BufferChangeParam): void; - on(event: 'captionsChanged', callback: EventCallback): void; - once(event: 'captionsChanged', callback: EventCallback): void; - off(event: 'captionsChanged'): void; - trigger(event: 'captionsChanged', args: CaptionsChangedParam): void; - on(event: 'captionsList', callback: EventCallback): void; - once(event: 'captionsList', callback: EventCallback): void; - off(event: 'captionsList'): void; - trigger(event: 'captionsList', args: CaptionsListParam): void; - on(event: 'controls', callback: EventCallback): void; - once(event: 'controls', callback: EventCallback): void; - off(event: 'controls'): void; - trigger(event: 'controls', args: ControlsParam): void; - on(event: 'displayClick', callback: () => void): void; - once(event: 'displayClick', callback: () => void): void; - off(event: 'displayClick'): void; - trigger(event: 'displayClick'): void; - on(event: 'error', callback: EventCallback): void; - once(event: 'error', callback: EventCallback): void; - off(event: 'error'): void; - trigger(event: 'error', args: ErrorParam): void; - on(event: 'fullscreen', callback: EventCallback): void; - once(event: 'fullscreen', callback: EventCallback): void; - off(event: 'fullscreen'): void; - trigger(event: 'fullscreen', args: FullscreenParam): void; - on(event: 'idle', callback: EventCallback): void; - once(event: 'idle', callback: EventCallback): void; - off(event: 'idle'): void; - trigger(event: 'idle', args: IdleParam): void; - on(event: 'levelsChanged', callback: EventCallback): void; - once(event: 'levelsChanged', callback: EventCallback): void; - off(event: 'levelsChanged'): void; - trigger(event: 'levelsChanged', args: LevelsChangedParam): void; - on(event: 'mute', callback: EventCallback): void; - once(event: 'mute', callback: EventCallback): void; - off(event: 'mute'): void; - trigger(event: 'mute', args: MuteParam): void; - on(event: 'volume', callback: EventCallback): void; - once(event: 'volume', callback: EventCallback): void; - off(event: 'volume'): void; - trigger(event: 'volume', args: VolumeParam): void; - on(event: 'pause', callback: EventCallback): void; - once(event: 'pause', callback: EventCallback): void; - off(event: 'pause'): void; - trigger(event: 'pause', args: PlayParam): void; - on(event: 'play', callback: EventCallback): void; - once(event: 'play', callback: EventCallback): void; - off(event: 'play'): void; - trigger(event: 'play', args: PlayParam): void; - on(event: 'playlist', callback: EventCallback): void; - once(event: 'playlist', callback: EventCallback): void; - off(event: 'playlist'): void; - trigger(event: 'playlist', args: PlaylistParam): void; - on(event: 'playlistItem', callback: EventCallback): void; - once(event: 'playlistItem', callback: EventCallback): void; - off(event: 'playlistItem'): void; - trigger(event: 'playlistItem', args: PlaylistItemParam): void; - on(event: 'playlistComplete', callback: () => void): void; - once(event: 'playlistComplete', callback: () => void): void; - off(event: 'playlistComplete'): void; - trigger(event: 'playlistComplete'): void; - on(event: 'ready', callback: EventCallback): void; - once(event: 'ready', callback: EventCallback): void; - off(event: 'ready'): void; - trigger(event: 'ready'): void; - on(event: 'resize', callback: EventCallback): void; - once(event: 'resize', callback: EventCallback): void; - off(event: 'resize'): void; - trigger(event: 'resize', args: ResizeParam): void; - on(event: 'visualQuality', callback: EventCallback): void; - once(event: 'visualQuality', callback: EventCallback): void; - off(event: 'visualQuality'): void; - trigger(event: 'visualQuality', args: VisualQualityParam): void; - on(event: 'levels', callback: EventCallback): void; - once(event: 'levels', callback: EventCallback): void; - off(event: 'levels'): void; - trigger(event: 'levels', args: LevelsParam): void; - on(event: 'seek', callback: EventCallback): void; - once(event: 'seek', callback: EventCallback): void; - off(event: 'seek'): void; - trigger(event: 'seek', args: SeekParam): void; - on(event: 'seeked', callback: () => void): void; - once(event: 'seeked', callback: () => void): void; - off(event: 'seeked'): void; - trigger(event: 'seeked'): void - on(event: 'setupError', callback: EventCallback): void; - once(event: 'setupError', callback: EventCallback): void; - off(event: 'setupError'): void; - trigger(event: 'setupError', args: ErrorParam): void; - on(event: 'remove', callback: () => void): void; - once(event: 'remove', callback: () => void): void; - off(event: 'remove'): void; - trigger(event: 'remove'): void; - on(event: 'time', callback: EventCallback): void; - once(event: 'time', callback: EventCallback): void; - off(event: 'time'): void; - trigger(event: 'time', args: TimeParam): void; - pause(state?: boolean): void; - play(state?: boolean): void; - playAd(tag: string): void; - playlistItem(index: number): void; - registerPlugin(id: string, target: string, jsPlugin: () => void, swfURL?: string): void; - remove(): void; - removeButton(id: string): void; - resize(width: number, height: number): void; - seek(position: number): void; - setControls(controls: boolean): void; - setCurrentAudioTrack(index: number): void; - setCurrentCaptions(index: number): void; - setCurrentQuality(index: number): void; - setFullscreen(state: boolean): void; - setMute(state?: boolean): void; - setup(options: any): JWPlayer; - setVolume(volume: number): void; - setCaptions(options: CaptionOptions): void; - stop(): void; -} - -interface JWPlayerStatic { - (id: string): JWPlayer; - key: string; - version: string; -} - -declare const jwplayer:JWPlayerStatic; +declare const jwplayer: jwplayer.JWPlayerStatic; diff --git a/types/jwplayer/tslint.json b/types/jwplayer/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/jwplayer/tslint.json +++ b/types/jwplayer/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/kefir/index.d.ts b/types/kefir/index.d.ts index e892e1b291..05fd7a7aab 100644 --- a/types/kefir/index.d.ts +++ b/types/kefir/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for Kefir 3.7.3 +// Type definitions for Kefir 3.8.0 // Project: http://rpominov.github.io/kefir/ // Definitions by: Aya Morisawa // Piotr Hitori Bosak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.7 /// @@ -11,7 +11,7 @@ export type ValueOfAnObservable> = T['']; export interface Subscription { unsubscribe(): void; - closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 + readonly closed: boolean; } export interface Observer { @@ -20,21 +20,24 @@ export interface Observer { end?: () => void; } -export interface Subscription { - unsubscribe(): void; - closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 +interface ESObserver { + start?: Function, + next?: (value: T) => any, + error?: (error: S) => any, + complete?: () => any, } -export interface Observer { - value?: (value: T) => void; - error?: (error: S) => void; - end?: () => void; +interface ESObservable { + subscribe(callbacks: ESObserver): { unsubscribe(): void }; } -export interface Observable { +export class Observable { '': T; // TypeScript hack to enable value unwrapping for combine/flatMap - toProperty(getCurrent?: () => T): Property; + toProperty(): Property; + toProperty(getCurrent?: () => T2): Property; + changes(): Observable; + // Subscribe / add side effects onValue(callback: (value: T) => void): this; offValue(callback: (value: T) => void): this; @@ -42,8 +45,8 @@ export interface Observable { offError(callback: (error: S) => void): this; onEnd(callback: () => void): this; offEnd(callback: () => void): this; - onAny(callback: (event: Event) => void): this; - offAny(callback: (event: Event) => void): this; + onAny(callback: (event: Event) => void): this; + offAny(callback: (event: Event) => void): this; log(name?: string): this; spy(name?: string): this; offLog(name?: string): this; @@ -51,7 +54,7 @@ export interface Observable { flatten(transformer?: (value: T) => U[]): Stream; toPromise(): Promise; toPromise>(PromiseConstructor: () => W): W; - toESObservable(): any; + toESObservable(): ESObservable; // This method is designed to replace all other methods for subscribing observe(params: Observer): Subscription; observe( @@ -61,172 +64,174 @@ export interface Observable { ): Subscription; setName(source: Observable, selfName: string): this; setName(selfName: string): this; -} -export interface Stream extends Observable { + thru(cb: (obs: Observable) => Observable): Observable; // Modify an stream - map(fn: (value: T) => U): Stream; - filter(predicate?: (value: T) => boolean): Stream; - take(n: number): Stream; - takeWhile(predicate?: (value: T) => boolean): Stream; - last(): Stream; - skip(n: number): Stream; - skipWhile(predicate?: (value: T) => boolean): Stream; - skipDuplicates(comparator?: (a: T, b: T) => boolean): Stream; - diff(fn?: (prev: T, next: T) => T, seed?: T): Stream; - scan(fn: (prev: T | W, next: T) => W): Stream; - scan(fn: (prev: W, next: T) => W, seed: W): Stream; - delay(wait: number): Stream; - throttle(wait: number, options?: { leading?: boolean, trailing?: boolean }): Stream; - debounce(wait: number, options?: { immediate: boolean }): Stream; - valuesToErrors(): Stream; - valuesToErrors(handler: (value: T) => { convert: boolean, error: U }): Stream; - errorsToValues(handler?: (error: S) => { convert: boolean, value: U }): Stream; - mapErrors(fn: (error: S) => U): Stream; - filterErrors(predicate?: (error: S) => boolean): Stream; - endOnError(): Stream; - takeErrors(n: number): Stream; - ignoreValues(): Stream; - ignoreErrors(): Stream; - ignoreEnd(): Stream; - beforeEnd(fn: () => U): Stream; - slidingWindow(max: number, mix?: number): Stream; - bufferWhile(predicate: (value: T) => boolean): Stream; - bufferWithCount(count: number, options?: { flushOnEnd: boolean }): Stream; - bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Stream; - transduce(transducer: any): Stream; - withHandler(handler: (emitter: Emitter, event: Event) => void): Stream; + map(fn: (value: T) => U): Observable; + filter(fn: (value: T) => value is U): Observable + filter(predicate?: (value: T) => boolean): Observable; + take(n: number): Observable; + takeWhile(predicate?: (value: T) => boolean): Observable; + last(): Observable; + skip(n: number): Observable; + skipWhile(predicate?: (value: T) => boolean): Observable; + skipDuplicates(comparator?: (a: T, b: T) => boolean): Observable; + diff(fn?: (prev: T, next: T) => T, seed?: T): Observable; + scan(fn: (prev: T | W, next: T) => W): Observable; + scan(fn: (prev: W, next: T) => W, seed: W): Observable; + delay(wait: number): Observable; + throttle(wait: number, options?: { leading?: boolean, trailing?: boolean }): Observable; + debounce(wait: number, options?: { immediate: boolean }): Observable; + valuesToErrors(): Observable; + valuesToErrors(handler: (value: T) => { convert: boolean, error: U }): Observable; + errorsToValues(handler?: (error: S) => { convert: boolean, value: U }): Observable; + mapErrors(fn: (error: S) => U): Observable; + filterErrors(predicate?: (error: S) => boolean): Observable; + endOnError(): Observable; + takeErrors(n: number): Observable; + ignoreValues(): Observable; + ignoreErrors(): Observable; + ignoreEnd(): Observable; + beforeEnd(fn: () => U): Observable; + slidingWindow(max: number, mix?: number): Observable; + bufferWhile(predicate: (value: T) => boolean): Observable; + bufferWithCount(count: number, options?: { flushOnEnd: boolean }): Observable; + bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Observable; + transduce(transducer: any): Observable; + withHandler(handler: (emitter: Emitter, event: Event) => void): Observable; // Combine streams - combine(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; - zip(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; - merge(otherObs: Stream): Stream; - concat(otherObs: Stream): Stream; - flatMap(transform: (value: T) => Stream): Stream; - flatMap>(): Stream, any>; - flatMapLatest(fn: (value: T) => Stream): Stream; - flatMapLatest>(): Stream, any>; - flatMapFirst(fn: (value: T) => Stream): Stream; - flatMapFirst>(): Stream, any>; - flatMapConcat(fn: (value: T) => Stream): Stream; - flatMapConcat>(): Stream, any>; - flatMapConcurLimit(fn: (value: T) => Stream, limit: number): Stream; - flatMapErrors(transform: (error: S) => Stream): Stream; + combine(otherObs: Observable, combinator?: (value: T, ...values: U[]) => W): Observable; + zip(otherObs: Observable, combinator?: (value: T, ...values: U[]) => W): Observable; + merge(otherObs: Observable): Observable; + concat(otherObs: Observable): Observable; + flatMap(transform: (value: T) => Observable): Observable; + flatMap>(): Observable, any>; + flatMapLatest(fn: (value: T) => Observable): Observable; + flatMapLatest>(): Observable, any>; + flatMapFirst(fn: (value: T) => Observable): Observable; + flatMapFirst>(): Observable, any>; + flatMapConcat(fn: (value: T) => Observable): Observable; + flatMapConcat>(): Observable, any>; + flatMapConcurLimit(fn: (value: T) => Observable, limit: number): Observable; + flatMapErrors(transform: (error: S) => Observable): Observable; // Combine two streams - filterBy(otherObs: Observable): Stream; - sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Stream; - skipUntilBy(otherObs: Observable): Stream; - takeUntilBy(otherObs: Observable): Stream; - bufferBy(otherObs: Observable, options?: { flushOnEnd: boolean }): Stream; - bufferWhileBy(otherObs: Observable, options?: { flushOnEnd?: boolean, flushOnChange?: boolean }): Stream; - awaiting(otherObs: Observable): Stream; + filterBy(otherObs: Observable): Observable; + sampledBy(otherObs: Observable): Observable; + sampledBy(otherObs: Observable, combinator: (a: T, b: U) => W): Observable; + skipUntilBy(otherObs: Observable): Observable; + takeUntilBy(otherObs: Observable): Observable; + bufferBy(otherObs: Observable, options?: { flushOnEnd: boolean }): Observable; + bufferWhileBy(otherObs: Observable, options?: { flushOnEnd?: boolean, flushOnChange?: boolean }): Observable; + awaiting(otherObs: Observable): Observable; } -export interface Property extends Observable { - changes(): Stream; - // Modify an property - map(fn: (value: T) => U): Property; - filter(predicate?: (value: T) => boolean): Property; - take(n: number): Property; - takeWhile(predicate?: (value: T) => boolean): Property; - last(): Property; - skip(n: number): Property; - skipWhile(predicate?: (value: T) => boolean): Property; - skipDuplicates(comparator?: (a: T, b: T) => boolean): Property; - diff(fn?: (prev: T, next: T) => T, seed?: T): Property; - scan(fn: (prev: T, next: T) => T, seed?: T): Property; - delay(wait: number): Property; - throttle(wait: number, options?: { leading?: boolean, trailing?: boolean }): Property; - debounce(wait: number, options?: { immediate: boolean }): Property; - valuesToErrors(handler?: (value: T) => { convert: boolean, error: U }): Property; - errorsToValues(handler?: (error: S) => { convert: boolean, value: U }): Property; - mapErrors(fn: (error: S) => U): Property; - filterErrors(predicate?: (error: S) => boolean): Property; - endOnError(): Property; - takeErrors(n: number): Stream; - ignoreValues(): Property; - ignoreErrors(): Property; - ignoreEnd(): Property; - beforeEnd(fn: () => U): Property; - slidingWindow(max: number, mix?: number): Property; - bufferWhile(predicate: (value: T) => boolean): Property; - bufferWithCount(count: number, options?: { flushOnEnd: boolean }): Property; - bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Property; - transduce(transducer: any): Property; - withHandler(handler: (emitter: Emitter, event: Event) => void): Property; - // Combine properties - combine(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; - zip(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; - merge(otherObs: Property): Property; - concat(otherObs: Property): Property; - flatMap(transform: (value: T) => Property): Property; - flatMap>(): Property, any>; - flatMapLatest(fn: (value: T) => Property): Property; - flatMapLatest>(): Property, any>; - flatMapFirst(fn: (value: T) => Property): Property; - flatMapFirst>(): Property, any>; - flatMapConcat(fn: (value: T) => Property): Property; - flatMapConcurLimit(fn: (value: T) => Property, limit: number): Property; - flatMapErrors(transform: (error: S) => Property): Property; - // Combine two properties - filterBy(otherObs: Observable): Property; - sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Property; - skipUntilBy(otherObs: Observable): Property; - takeUntilBy(otherObs: Observable): Property; - bufferBy(otherObs: Observable, options?: { flushOnEnd: boolean }): Property; - bufferWhileBy(otherObs: Observable, options?: { flushOnEnd?: boolean, flushOnChange?: boolean }): Property; - awaiting(otherObs: Observable): Property; +export class Stream extends Observable { + } -export interface ObservablePool extends Observable { +export class Property extends Observable { + +} + +export class Pool extends Observable { plug(obs: Observable): this; - unPlug(obs: Observable): this; + unplug(obs: Observable): this; } -export interface Event { - type: string; - value: T; -} +export type Event = + { type: 'value', value: V } | + { type: 'error', value: E } | + { type: 'end', value: void }; -export interface Emitter { - emit(value: T): void; - error(error: S): void; +export interface Emitter { + value(value: V): boolean; + event(event: Event): boolean; + error(e: E): boolean; end(): void; - emitEvent(event: { type: string, value: T | S }): void; + + // Deprecated methods + emit(value: V): boolean; + emitEvent(event: Event): boolean; } // Create a stream -export declare function never(): Stream; -export declare function later(wait: number, value: T): Stream; -export declare function interval(interval: number, value: T): Stream; -export declare function sequentially(interval: number, values: T[]): Stream; -export declare function fromPoll(interval: number, fn: () => T): Stream; -export declare function withInterval(interval: number, handler: (emitter: Emitter) => void): Stream; -export declare function fromCallback(fn: (callback: (value: T) => void) => void): Stream; -export declare function fromNodeCallback(fn: (callback: (error: S, result: T) => void) => void): Stream; -export declare function fromEvents(target: EventTarget | NodeJS.EventEmitter | { on: Function, off: Function }, eventName: string, transform?: (value: T) => S): Stream; -export declare function stream(subscribe: (emitter: Emitter) => Function | void): Stream; -export declare function fromESObservable(observable: any): Stream +export function never(): Stream; +export function later(wait: number, value: T): Stream; +export function interval(interval: number, value: T): Stream; +export function sequentially(interval: number, values: T[]): Stream; +export function fromPoll(interval: number, fn: () => T): Stream; +export function withInterval(interval: number, handler: (emitter: Emitter) => void): Stream; +export function fromCallback(fn: (callback: (value: T) => void) => void): Stream; +export function fromNodeCallback(fn: (callback: (error: S, result: T) => void) => void): Stream; +export function fromEvents(target: EventTarget | NodeJS.EventEmitter | { on: Function, off: Function }, eventName: string, transform?: (value: T) => S): Stream; +export function stream(subscribe: (emitter: Emitter) => Function | void): Stream; +export function fromESObservable(observable: any): Stream // Create a property -export declare function constant(value: T): Property; -export declare function constantError(error: T): Property; -export declare function fromPromise(promise: Promise): Property; +export function constant(value: T): Property; +export function constantError(error: T): Property; +export function fromPromise(promise: Promise): Property; // Combine observables -export declare function combine(obss: Observable[], passiveObss: Observable[], combinator?: (...values: T[]) => U): Stream; -export declare function combine(obss: Observable[], combinator: (...values: T[]) => U): Stream; -export declare function combine }>(obss: T): Stream<{ [P in keyof T]: ValueOfAnObservable }, any>; -export declare function combine], P extends keyof T>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine]>(obss: T): Stream<[ValueOfAnObservable], any>; -export declare function combine(obss: T): Stream; -export declare function zip(obss: Observable[], passiveObss?: Observable[], combinator?: (...values: T[]) => U): Observable; -export declare function merge(obss: Observable[]): Observable; -export declare function concat(obss: Observable[]): Observable; -export declare function pool(): ObservablePool; -export declare function repeat(generator: (i: number) => Observable | boolean): Observable; +export function combine(obss: Observable[], passiveObss: Observable[], combinator?: (...values: T[]) => U): Stream; +export function combine(obss: Observable[], combinator: (...values: T[]) => U): Stream; +export function combine }>(obss: T): Stream<{ [P in keyof T]: ValueOfAnObservable }, any>; +export function combine], P extends keyof T>(obss: T): Stream<[ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine]>(obss: T): Stream<[ValueOfAnObservable], any>; +export function combine(obss: T): Stream; +export function combine], P extends [Observable], K>(obss: T, obssP: P, combinator: (a: T[0][''], b: P[0]['']) => K): Observable; +export function zip(obss: Observable[], passiveObss?: Observable[], combinator?: (...values: T[]) => U): Observable; +export function merge(obss: Observable[]): Observable; +export function concat(obss: Observable[]): Observable; +export function pool(): Pool; +export function repeat(generator: (i: number) => Observable | boolean): Observable; + +export var staticLand: { + Observable: { + ap(obsF: Observable<(x: A) => B, E1>, obsV: Observable): Observable; + bimap(fnE: (x: E1) => E2, fnV: (x: V1) => V2, obs: Observable): Observable; + chain(cb: (value: V) => Observable, s: Observable): Observable; + concat(obs1: Observable, obs2: Observable): Observable; + empty(): Observable; + map(cb: (value: V) => V2, s: Observable): Observable; + of(value: V): Observable; + } +} + +declare var kefir: { + Observable: typeof Observable; + Pool: typeof Pool; + Stream: typeof Stream; + Property: typeof Property; + + never: typeof never, + later: typeof later, + interval: typeof interval, + sequentially: typeof sequentially, + fromPoll: typeof fromPoll, + withInterval: typeof withInterval, + fromCallback: typeof fromCallback, + fromNodeCallback: typeof fromNodeCallback, + fromEvents: typeof fromEvents, + stream: typeof stream, + fromESObservable: typeof fromESObservable, + constant: typeof constant, + constantError: typeof constantError, + fromPromise: typeof fromPromise, + combine: typeof combine, + zip: typeof zip, + merge: typeof merge, + concat: typeof concat, + pool: typeof pool, + repeat: typeof repeat, + + staticLand: typeof staticLand +}; + +export default kefir; diff --git a/types/kefir/kefir-tests.ts b/types/kefir/kefir-tests.ts index d2dbd5835e..0fba9c5d21 100644 --- a/types/kefir/kefir-tests.ts +++ b/types/kefir/kefir-tests.ts @@ -1,6 +1,6 @@ import * as Kefir from 'kefir'; -import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'kefir'; +import { Observable, Pool, Stream, Property, Event, Emitter } from 'kefir'; //Create a stream { @@ -130,7 +130,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke var myTransducer: any; let observable28: Stream = Kefir.sequentially(100, [1, 2, 3, 4, 5, 6]).transduce(myTransducer); } - let observable28: Stream = Kefir.sequentially(100, [0, 1, 2, 3]).withHandler((emitter: Emitter, event: Event) => { + let observable28: Stream = Kefir.sequentially(100, [0, 1, 2, 3]).withHandler((emitter: Emitter, event: Event) => { if (event.type === 'end') { emitter.emit('bye'); emitter.end(); @@ -141,6 +141,9 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke } } }); + type First = 'first'; + type Second = 'second'; + let observable32: Stream = Kefir.sequentially(100, ['first', 'second']).filter((value): value is First => value === 'first'); } // Combine observables @@ -177,7 +180,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke let a: Stream = Kefir.sequentially(100, [0, 1, 2]); let b: Stream = Kefir.sequentially(100, [0, 1, 2]).delay(30); let c: Observable = Kefir.sequentially(100, [0, 1, 2]).delay(60); - let pool: ObservablePool = Kefir.pool(); + let pool: Pool = Kefir.pool(); pool.plug(a); pool.plug(b); pool.plug(c); @@ -207,7 +210,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke { let a: Property = Kefir.sequentially(200, [2, 3]).toProperty(() => 1); let b: Stream = Kefir.interval(100, 0).delay(40).take(5); - let observable02: Property = a.sampledBy(b) + let observable02: Property = a.sampledBy(b) } { let foo: Stream = Kefir.sequentially(100, [1, 2, 3, 4]); diff --git a/types/keyboardjs/index.d.ts b/types/keyboardjs/index.d.ts index 037bf7189b..c97cda0741 100644 --- a/types/keyboardjs/index.d.ts +++ b/types/keyboardjs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for KeyboardJS v2.4.1 +// Type definitions for KeyboardJS v2.4.2 // Project: https://github.com/RobertWHurst/KeyboardJS // Definitions by: Vincent Bortone , // David Asmuth , @@ -92,14 +92,16 @@ declare namespace keyboardjs { /** * Triggers a key press. Stays in pressed state until released. - * @param keyCombo String of keys to be pressed to execute 'pressed' callbacks. + * @param keyCombo String of keys or keyCode to be pressed to execute 'pressed' callbacks. + * @param event The KeyEvent, can be null. */ - export function pressKey(keyCombo: string): void + export function pressKey(keyCombo: string | number, event?: KeyEvent): void; /** * Triggers a key release. - * @param keyCombo String of keys to be released to execute 'released' callbacks. + * @param keyCombo String of keys or keyCode to be released to execute 'released' callbacks. + * @param event The KeyEvent, can be null. */ - export function releaseKey(keyCombo: string): void; + export function releaseKey(keyCombo: string | number, event?: KeyEvent): void; /** * Releases all keys. */ diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index b2163d09d1..4df53d0e8b 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -43,7 +43,7 @@ declare namespace Router { strict?: boolean; } - export interface IRouterContext extends Koa.Context { + export interface IRouterParamContext { /** * url params */ @@ -51,15 +51,26 @@ declare namespace Router { /** * the router instance */ - router: Router; + router: Router; + /** + * Matched route + */ + _matchedRoute: string | RegExp | undefined; + _matchedRouteName: string | undefined; } - export interface IMiddleware { - (ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; - } + export type RouterContext = + Koa.ParameterizedContext>; + + // For backward compatibility IRouterContext needs to be an interface + // But it's deprecated - please use `RouterContext` instead + export interface IRouterContext extends RouterContext {} + + export type IMiddleware = + Koa.Middleware> export interface IParamMiddleware { - (param: string, ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; + (param: string, ctx: RouterContext, next: () => Promise): any; } export interface IRouterAllowedMethodsOptions { @@ -148,7 +159,7 @@ declare namespace Router { } } -declare class Router { +declare class Router { params: Object; stack: Array; @@ -164,109 +175,195 @@ declare class Router { * sequentially, requests start at the first middleware and work their way * "down" the middleware stack. */ - use(...middleware: Array): Router; - use(path: string | string[] | RegExp, ...middleware: Array): Router; + use(...middleware: Array>): Router; + use( + path: string | string[] | RegExp, + ...middleware: Array> + ): Router; /** * HTTP get method */ - get(name: string, path: string | RegExp, ...middleware: Array): Router; - get(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + get( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + get( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP post method */ - post(name: string, path: string | RegExp, ...middleware: Array): Router; - post(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + post( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + post( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP put method */ - put(name: string, path: string | RegExp, ...middleware: Array): Router; - put(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + put( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + put( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP link method */ - link(name: string, path: string | RegExp, ...middleware: Array): Router; - link(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + link( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + link( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP unlink method */ - unlink(name: string, path: string | RegExp, ...middleware: Array): Router; - unlink(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + unlink( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + unlink( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP delete method */ - delete(name: string, path: string | RegExp, ...middleware: Array): Router; - delete(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + delete( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + delete( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * Alias for `router.delete()` because delete is a reserved word */ - del(name: string, path: string | RegExp, ...middleware: Array): Router; - del(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + del( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + del( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP head method */ - head(name: string, path: string | RegExp, ...middleware: Array): Router; - head(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + head( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + head( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP options method */ - options(name: string, path: string | RegExp, ...middleware: Array): Router; - options(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + options( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + options( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP path method */ - patch(name: string, path: string | RegExp, ...middleware: Array): Router; - patch(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + patch( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + patch( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * Register route with all methods. */ - all(name: string, path: string | RegExp, ...middleware: Array): Router; - all(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + all( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + all( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * Set the path prefix for a Router instance that was already initialized. */ - prefix(prefix: string): Router; + prefix(prefix: string): Router; /** * Returns router middleware which dispatches a route matching the request. */ - routes(): Koa.Middleware; + routes(): Router.IMiddleware; /** * Returns router middleware which dispatches a route matching the request. */ - middleware(): Koa.Middleware; + middleware(): Router.IMiddleware; /** * Returns separate middleware for responding to `OPTIONS` requests with * an `Allow` header containing the allowed methods, as well as responding * with `405 Method Not Allowed` and `501 Not Implemented` as appropriate. */ - allowedMethods(options?: Router.IRouterAllowedMethodsOptions): Koa.Middleware; + allowedMethods( + options?: Router.IRouterAllowedMethodsOptions + ): Router.IMiddleware; /** * Redirect `source` to `destination` URL with optional 30x status `code`. * * Both `source` and `destination` can be route names. */ - redirect(source: string, destination: string, code?: number): Router; + redirect(source: string, destination: string, code?: number): Router; /** * Create and register a route. */ - register(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Object): Router.Layer; + register( + path: string | RegExp, + methods: string[], + middleware: Router.IMiddleware, + opts?: Object + ): Router.Layer; /** * Lookup route with given `name`. @@ -304,7 +401,7 @@ declare class Router { /** * Run middleware for named route parameters. Useful for auto-loading or validation. */ - param(param: string, middleware: Router.IParamMiddleware): Router; + param(param: string, middleware: Router.IParamMiddleware): Router; /** * Generate URL from url pattern and given `params`. diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index 50e66509ea..96fa0d1751 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -1,9 +1,15 @@ import Koa = require("koa"); +import { Context } from "koa"; +import compose = require("koa-compose"); +import etag = require("koa-etag"); import Router = require("koa-router"); +type MyState = {foo: string} +type MyContext = {bar: string} + const app = new Koa<{}, {}>(); -const router = new Router({ +const router = new Router({ prefix: "/users" }); @@ -31,9 +37,10 @@ router } }) .post('/users', function (ctx, next) { - // ... + ctx.state.foo = 'foo'; }) .put('/users/:id', function (ctx, next) { + ctx.bar = 'bar'; ctx.body = ctx.params.id; }) .del('/users/:id', function () { @@ -49,11 +56,72 @@ const match = router.match('/users/:id', 'GET'); let layer: Router.Layer let layerOptions: Router.ILayerOptions -const mw: Router.IMiddleware = (ctx: Router.IRouterContext, next: () => Promise) => { +const mw: Router.IMiddleware = (ctx: Koa.ParameterizedContext, next: () => Promise) => { ctx.body = "Ok"; }; -app.use(router.routes()); -app.use(router.allowedMethods()); +const mw2: Router.IMiddleware = (ctx: Router.IRouterContext, next: () => Promise) => { + ctx.body = "Ok"; +}; -app.listen(3000); +app.use(async (ctx: Koa.ParameterizedContext, next) => { + ctx.state.foo = 'foo'; + await next(); + }) + .use(router.routes()) + .use(router.allowedMethods()) + .use(async (ctx, next) => { + ctx.state.foo = '3'; + await next(); + }) + .listen(3000); + +const router3 = new Router(); +router3.get('/', (ctx) => { + ctx.foo = "bar"; + console.log(ctx.router.params); + ctx.body = "Hello World!"; +}); +router3.get('/foo', (ctx: Router.IRouterContext) => { + ctx.body = "Yup"; +}) +new Koa() + .use(async (ctx, next) => next()) + .use(router3.routes()) + .use(router.allowedMethods()) + .listen(3001); + +// It's from https://github.com/DefinitelyTyped/DefinitelyTyped/pull/31704#issuecomment-451075919, +// to make sure we don't break it again + +declare module "koa" { + interface Context { + name: string; + } +} + +const app2 = new Koa(); + +const conditional = async (ctx: Context, next: any) => { + await next(); + if (ctx.fresh) { + ctx.status = 304; + ctx.body = null; + } +}; + +const router2 = compose([conditional, etag()]); + +app2.use(router2); + +app2.use(async (ctx: Context, next: any) => { + ctx.name = "hello world"; + await next(); +}); + +app2.use((ctx: Context, next: any) => { + console.log(ctx.name); + ctx.body = ctx.name; +}); + +app2.listen(8000); diff --git a/types/latest-semver/index.d.ts b/types/latest-semver/index.d.ts new file mode 100644 index 0000000000..761a487b88 --- /dev/null +++ b/types/latest-semver/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for latest-semver 1.0 +// Project: https://github.com/sindresorhus/latest-semver#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = latestSemver; + +declare function latestSemver(versions: string[]): string | undefined; diff --git a/types/latest-semver/latest-semver-tests.ts b/types/latest-semver/latest-semver-tests.ts new file mode 100644 index 0000000000..ec8312e467 --- /dev/null +++ b/types/latest-semver/latest-semver-tests.ts @@ -0,0 +1,4 @@ +import latestSemver = require('latest-semver'); + +// $ExpectType string | undefined +latestSemver(['v1.8.0-alpha.1', 'v1.3.16', 'v1.7.0', 'v1.6.9']); diff --git a/types/latest-semver/tsconfig.json b/types/latest-semver/tsconfig.json new file mode 100644 index 0000000000..54f1df51e2 --- /dev/null +++ b/types/latest-semver/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", + "latest-semver-tests.ts" + ] +} diff --git a/types/latest-semver/tslint.json b/types/latest-semver/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/latest-semver/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/latest-version/index.d.ts b/types/latest-version/index.d.ts new file mode 100644 index 0000000000..5127714c15 --- /dev/null +++ b/types/latest-version/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for latest-version 4.0 +// Project: https://github.com/sindresorhus/latest-version#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = latestVersion; + +declare function latestVersion(name: string, options?: latestVersion.Options): Promise; + +declare namespace latestVersion { + interface Options { + version?: string; + } +} diff --git a/types/latest-version/latest-version-tests.ts b/types/latest-version/latest-version-tests.ts new file mode 100644 index 0000000000..2cbd29b61f --- /dev/null +++ b/types/latest-version/latest-version-tests.ts @@ -0,0 +1,4 @@ +import latestVersion = require('latest-version'); + +latestVersion('ava'); // $ExpectType Promise +latestVersion('npm', { version: 'latest-5' }); // $ExpectType Promise diff --git a/types/latest-version/tsconfig.json b/types/latest-version/tsconfig.json new file mode 100644 index 0000000000..a62d14b69d --- /dev/null +++ b/types/latest-version/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", + "latest-version-tests.ts" + ] +} diff --git a/types/latest-version/tslint.json b/types/latest-version/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/latest-version/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 8177ba1aa6..96bcb3277a 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Leaflet.js 1.2 +// Type definitions for Leaflet.js 1.4 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Alejandro Sánchez // Arne Schubert @@ -323,7 +323,7 @@ export abstract class Evented extends Class { * Note that if you passed a custom context to on, you must pass the same context * to off in order to remove the listener. */ - removeEventListener(type: string, fn: LeafletEventHandlerFn, context?: any): this; + removeEventListener(type: string, fn?: LeafletEventHandlerFn, context?: any): this; /** * Alias for off(...) @@ -1181,6 +1181,12 @@ export interface FitBoundsOptions extends ZoomOptions, PanOptions { maxZoom?: number; } +export interface PanInsideOptions { + paddingTopLeft?: PointExpression; + paddingBottomRight?: PointExpression; + padding?: PointExpression; +} + export interface LocateOptions { watch?: boolean; setView?: boolean; @@ -1355,6 +1361,7 @@ export class Map extends Evented { setMaxBounds(bounds: LatLngBoundsExpression): this; setMinZoom(zoom: number): this; setMaxZoom(zoom: number): this; + panInside(latLng: LatLngExpression, options?: PanInsideOptions): this; panInsideBounds(bounds: LatLngBoundsExpression, options?: PanOptions): this; /** * Boolean for animate or advanced ZoomPanOptions diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index 6debf6b0d6..a6c9b6ccc3 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -40,8 +40,8 @@ point = new L.Point(12, 13); point = new L.Point(12, 13, true); let distance: number; -point.distanceTo(point); -point.distanceTo(pointTuple); +distance = point.distanceTo(point); +distance = point.distanceTo(pointTuple); const transformation = new L.Transformation(1, 2, 3, 4); point = transformation.transform(point); @@ -163,6 +163,16 @@ map = new L.Map(htmlElement, mapOptions); let doesItHaveLayer: boolean; doesItHaveLayer = map.hasLayer(L.tileLayer('')); +map.off('moveend'); +map.off('moveend', () => {}); +map.off('moveend', () => {}, {}); + +map.removeEventListener('moveend'); +map.removeEventListener('moveend', () => {}); +map.removeEventListener('moveend', () => {}, {}); + +map.panInside(latLng, {padding: [50, 50], paddingBottomRight: point, paddingTopLeft: [100, 100]}); + // map.getRenderer let html: HTMLElement; diff --git a/types/libsodium-wrappers-sumo/index.d.ts b/types/libsodium-wrappers-sumo/index.d.ts index ceeadd5980..5341cca299 100644 --- a/types/libsodium-wrappers-sumo/index.d.ts +++ b/types/libsodium-wrappers-sumo/index.d.ts @@ -7,10 +7,12 @@ export * from 'libsodium-wrappers'; import { - Uint8ArrayOutputFormat, - StringOutputFormat, + KeyPair, onetimeauth_state_address, state_address, + StringKeyPair, + StringOutputFormat, + Uint8ArrayOutputFormat, } from 'libsodium-wrappers'; export const crypto_auth_hmacsha256_BYTES: number; @@ -77,6 +79,12 @@ export const crypto_stream_xchacha20_KEYBYTES: number; export const crypto_stream_xchacha20_NONCEBYTES: number; +export const crypto_box_curve25519xchacha20poly1305_NONCEBYTES: number; + +export const crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES: number; + +export const crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES: number; + export function crypto_auth_hmacsha256( message: string | Uint8Array, key: Uint8Array, @@ -113,6 +121,18 @@ export function crypto_auth_hmacsha512_keygen(outputFormat?: StringOutputFormat export function crypto_auth_hmacsha512_verify(tag: Uint8Array, message: string | Uint8Array, key: Uint8Array): boolean; +export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): KeyPair; + +export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: StringOutputFormat | null): StringKeyPair; + +export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; + +export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat?: StringOutputFormat | null): string; + +export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; + +export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: StringOutputFormat | null): string; + export function crypto_hash_sha256( message: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null, @@ -240,6 +260,10 @@ export function crypto_sign_ed25519_sk_to_seed( outputFormat?: StringOutputFormat | null, ): string; +export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat?: StringOutputFormat | null): string; + +export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; + export function crypto_stream_chacha20_ietf_xor( input_message: string | Uint8Array, nonce: Uint8Array, diff --git a/types/libsodium-wrappers/index.d.ts b/types/libsodium-wrappers/index.d.ts index e9213da782..155448bcc2 100644 --- a/types/libsodium-wrappers/index.d.ts +++ b/types/libsodium-wrappers/index.d.ts @@ -886,30 +886,30 @@ export function crypto_secretstream_xchacha20poly1305_keygen(outputFormat?: Uint export function crypto_secretstream_xchacha20poly1305_keygen(outputFormat?: StringOutputFormat | null): string; export function crypto_secretstream_xchacha20poly1305_pull( - state_address?: secretstream_xchacha20poly1305_state_address, - cipher?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + cipher: string | Uint8Array, ad?: string | Uint8Array | null, outputFormat?: Uint8ArrayOutputFormat | null, -): { message: Uint8Array; tag: Uint8Array }; +): { message: Uint8Array; tag: number }; export function crypto_secretstream_xchacha20poly1305_pull( - state_address?: secretstream_xchacha20poly1305_state_address, - cipher?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + cipher: string | Uint8Array, ad?: string | Uint8Array | null, outputFormat?: StringOutputFormat | null, -): { message: string; tag: Uint8Array }; +): { message: string; tag: number }; export function crypto_secretstream_xchacha20poly1305_push( - state_address?: secretstream_xchacha20poly1305_state_address, - message_chunk?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + message_chunk: string | Uint8Array, ad?: string | Uint8Array | null, tag?: number, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_secretstream_xchacha20poly1305_push( - state_address?: secretstream_xchacha20poly1305_state_address, - message_chunk?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + message_chunk: string | Uint8Array, ad?: string | Uint8Array | null, tag?: number, outputFormat?: StringOutputFormat | null, @@ -1031,7 +1031,7 @@ export function crypto_stream_keygen(outputFormat?: Uint8ArrayOutputFormat | nul export function crypto_stream_keygen(outputFormat?: StringOutputFormat | null): string; -export function from_base64(input: string, variant: base64_variants): Uint8Array; +export function from_base64(input: string, variant?: base64_variants): Uint8Array; export function from_hex(input: string): Uint8Array; @@ -1077,7 +1077,7 @@ export function sodium_version_string(): string; export function symbols(): string[]; -export function to_base64(input: string | Uint8Array, variant: base64_variants): string; +export function to_base64(input: string | Uint8Array, variant?: base64_variants): string; export function to_hex(input: string | Uint8Array): string; diff --git a/types/load-google-maps-api/index.d.ts b/types/load-google-maps-api/index.d.ts new file mode 100644 index 0000000000..818957ff5f --- /dev/null +++ b/types/load-google-maps-api/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for load-google-maps-api 1.3 +// Project: https://github.com/yuanqing/load-google-maps-api#readme +// Definitions by: Oscar Busk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface Options { + /** + * Client usage reporting channel + * + * https://developers.google.com/maps/premium/reports/usage-reports#channels + */ + channel?: string; + /** + * Client ID + * + * https://developers.google.com/maps/documentation/javascript/get-api-key#specifying-a-client-id-when-loading-the-api + */ + client?: string; + /** + * Your API key + * + * https://developers.google.com/maps/documentation/javascript/get-api-key#step-2-add-the-api-key-to-your-application + */ + key?: string; + /** + * https://developers.google.com/maps/documentation/javascript/localization#Language + */ + language?: string; + /** + * Supplemental libraries to load + * + * Default Value `[]` + * + * https://developers.google.com/maps/documentation/javascript/libraries + */ + libraries?: string[]; + /** + * https://developers.google.com/maps/documentation/javascript/localization#Region + */ + region?: string; + /** + * Time in milliseconds before rejecting the Promise + * + * Default Value `10000` + */ + timeout?: number; + /** + * API Version + * + * https://developers.google.com/maps/documentation/javascript/versions + */ + v?: string; +} + +declare function loadGoogleMapsApi(options?: Options): Promise; + +export = loadGoogleMapsApi; diff --git a/types/load-google-maps-api/load-google-maps-api-tests.ts b/types/load-google-maps-api/load-google-maps-api-tests.ts new file mode 100644 index 0000000000..0d2495de64 --- /dev/null +++ b/types/load-google-maps-api/load-google-maps-api-tests.ts @@ -0,0 +1,38 @@ +import loadGoogleMapsApi = require('load-google-maps-api'); + +// Example from README.md https://github.com/yuanqing/load-google-maps-api#usage +loadGoogleMapsApi().then((googleMaps) => { + new googleMaps.Map(document.querySelector('.map'), { + center: { + lat: 40.7484405, + lng: -73.9944191 + }, + zoom: 12 + }); +}).catch((error) => { + console.error(error); +}); + +loadGoogleMapsApi({ libraries: 'drawing' }); // $ExpectError +loadGoogleMapsApi({ v: 3 }); // $ExpectError +loadGoogleMapsApi({ timeout: '1000' }); // $ExpectError + +loadGoogleMapsApi({ + channel: 'customer', + client: '12345', + key: 'abcde', + language: 'se', + libraries: [ + 'drawing', + 'geometry', + 'places', + 'visualization', + ], + region: 'SE', + timeout: 500, + v: '3.33', +}).then(gm => { + gm; // $ExpectType typeof maps + const map = new gm.Map(document.querySelector('.map')); // $ExpectType Map + const polygon = new gm.Polygon(); // $ExpectType Polygon +}); diff --git a/types/load-google-maps-api/tsconfig.json b/types/load-google-maps-api/tsconfig.json new file mode 100644 index 0000000000..7d3af9db08 --- /dev/null +++ b/types/load-google-maps-api/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", + "load-google-maps-api-tests.ts" + ] +} diff --git a/types/load-google-maps-api/tslint.json b/types/load-google-maps-api/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/load-google-maps-api/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lodash/fp.d.ts b/types/lodash/fp.d.ts index 9b6cf52ccb..68084f1c8d 100644 --- a/types/lodash/fp.d.ts +++ b/types/lodash/fp.d.ts @@ -616,20 +616,15 @@ declare namespace _ { (iteratee: (value: T) => any): LodashForEach1x1; (iteratee: lodash.__, collection: ReadonlyArray): LodashForEach1x2; (iteratee: (value: T) => any, collection: ReadonlyArray): T[]; - (iteratee: (value: string) => any): LodashForEach2x1; - (iteratee: lodash.__, collection: string): LodashForEach2x2; - (iteratee: (value: string) => any, collection: string): string; - (iteratee: lodash.__, collection: lodash.List): LodashForEach3x2; + (iteratee: lodash.__, collection: lodash.List): LodashForEach2x2; (iteratee: (value: T) => any, collection: lodash.List): lodash.List; - (iteratee: lodash.__, collection: T): LodashForEach4x2; + (iteratee: lodash.__, collection: T): LodashForEach3x2; (iteratee: (value: T[keyof T]) => any, collection: T): T; - (iteratee: lodash.__, collection: TArray & (T[] | null | undefined)): LodashForEach5x2; + (iteratee: lodash.__, collection: TArray & (T[] | null | undefined)): LodashForEach4x2; (iteratee: (value: T) => any, collection: TArray & (T[] | null | undefined)): TArray; - (iteratee: lodash.__, collection: TString): LodashForEach6x2; - (iteratee: (value: string) => any, collection: TString): TString; - | null | undefined>(iteratee: lodash.__, collection: TList & (lodash.List | null | undefined)): LodashForEach7x2; + | null | undefined>(iteratee: lodash.__, collection: TList & (lodash.List | null | undefined)): LodashForEach5x2; | null | undefined>(iteratee: (value: T) => any, collection: TList & (lodash.List | null | undefined)): TList; - (iteratee: lodash.__, collection: T | null | undefined): LodashForEach8x2; + (iteratee: lodash.__, collection: T | null | undefined): LodashForEach6x2; (iteratee: (value: T[keyof T]) => any, collection: T | null | undefined): T | null | undefined; } interface LodashForEach1x1 { @@ -641,35 +636,24 @@ declare namespace _ { (collection: T1 | null | undefined): T1 | null | undefined; } type LodashForEach1x2 = (iteratee: (value: T) => any) => T[]; - interface LodashForEach2x1 { - (collection: string): string; - (collection: TString): TString; - } - type LodashForEach2x2 = (iteratee: (value: string) => any) => string; - type LodashForEach3x2 = (iteratee: (value: T) => any) => lodash.List; - type LodashForEach4x2 = (iteratee: (value: T[keyof T]) => any) => T; - type LodashForEach5x2 = (iteratee: (value: T) => any) => TArray; - type LodashForEach6x2 = (iteratee: (value: string) => any) => TString; - type LodashForEach7x2 = (iteratee: (value: T) => any) => TList; - type LodashForEach8x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + type LodashForEach2x2 = (iteratee: (value: T) => any) => lodash.List; + type LodashForEach3x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForEach4x2 = (iteratee: (value: T) => any) => TArray; + type LodashForEach5x2 = (iteratee: (value: T) => any) => TList; + type LodashForEach6x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; interface LodashForEachRight { (iteratee: (value: T) => any): LodashForEachRight1x1; (iteratee: lodash.__, collection: ReadonlyArray): LodashForEachRight1x2; (iteratee: (value: T) => any, collection: ReadonlyArray): T[]; - (iteratee: (value: string) => any): LodashForEachRight2x1; - (iteratee: lodash.__, collection: string): LodashForEachRight2x2; - (iteratee: (value: string) => any, collection: string): string; - (iteratee: lodash.__, collection: lodash.List): LodashForEachRight3x2; + (iteratee: lodash.__, collection: lodash.List): LodashForEachRight2x2; (iteratee: (value: T) => any, collection: lodash.List): lodash.List; - (iteratee: lodash.__, collection: T): LodashForEachRight4x2; + (iteratee: lodash.__, collection: T): LodashForEachRight3x2; (iteratee: (value: T[keyof T]) => any, collection: T): T; - (iteratee: lodash.__, collection: TArray & (T[] | null | undefined)): LodashForEachRight5x2; + (iteratee: lodash.__, collection: TArray & (T[] | null | undefined)): LodashForEachRight4x2; (iteratee: (value: T) => any, collection: TArray & (T[] | null | undefined)): TArray; - (iteratee: lodash.__, collection: TString): LodashForEachRight6x2; - (iteratee: (value: string) => any, collection: TString): TString; - | null | undefined>(iteratee: lodash.__, collection: TList & (lodash.List | null | undefined)): LodashForEachRight7x2; + | null | undefined>(iteratee: lodash.__, collection: TList & (lodash.List | null | undefined)): LodashForEachRight5x2; | null | undefined>(iteratee: (value: T) => any, collection: TList & (lodash.List | null | undefined)): TList; - (iteratee: lodash.__, collection: T | null | undefined): LodashForEachRight8x2; + (iteratee: lodash.__, collection: T | null | undefined): LodashForEachRight6x2; (iteratee: (value: T[keyof T]) => any, collection: T | null | undefined): T | null | undefined; } interface LodashForEachRight1x1 { @@ -681,17 +665,11 @@ declare namespace _ { (collection: T1 | null | undefined): T1 | null | undefined; } type LodashForEachRight1x2 = (iteratee: (value: T) => any) => T[]; - interface LodashForEachRight2x1 { - (collection: string): string; - (collection: TString): TString; - } - type LodashForEachRight2x2 = (iteratee: (value: string) => any) => string; - type LodashForEachRight3x2 = (iteratee: (value: T) => any) => lodash.List; - type LodashForEachRight4x2 = (iteratee: (value: T[keyof T]) => any) => T; - type LodashForEachRight5x2 = (iteratee: (value: T) => any) => TArray; - type LodashForEachRight6x2 = (iteratee: (value: string) => any) => TString; - type LodashForEachRight7x2 = (iteratee: (value: T) => any) => TList; - type LodashForEachRight8x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; + type LodashForEachRight2x2 = (iteratee: (value: T) => any) => lodash.List; + type LodashForEachRight3x2 = (iteratee: (value: T[keyof T]) => any) => T; + type LodashForEachRight4x2 = (iteratee: (value: T) => any) => TArray; + type LodashForEachRight5x2 = (iteratee: (value: T) => any) => TList; + type LodashForEachRight6x2 = (iteratee: (value: T[keyof T]) => any) => T | null | undefined; interface LodashEndsWith { (target: string): LodashEndsWith1x1; (target: lodash.__, string: string): LodashEndsWith1x2; @@ -917,29 +895,24 @@ declare namespace _ { type LodashFill2x13 = (end: number) => lodash.List; type LodashFill2x14 = (start: number) => lodash.List; interface LodashFilter { - (predicate: (value: string) => boolean): LodashFilter1x1; - (predicate: lodash.__, collection: string | null | undefined): LodashFilter1x2; - (predicate: (value: string) => boolean, collection: string | null | undefined): string[]; - (predicate: lodash.ValueIteratorTypeGuard): LodashFilter2x1; - (predicate: lodash.__, collection: lodash.List | null | undefined): LodashFilter2x2; + (predicate: lodash.ValueIteratorTypeGuard): LodashFilter1x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashFilter1x2; (predicate: lodash.ValueIteratorTypeGuard, collection: lodash.List | null | undefined): S[]; - (predicate: lodash.ValueIterateeCustom): LodashFilter3x1; + (predicate: lodash.ValueIterateeCustom): LodashFilter2x1; (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T[]; - (predicate: lodash.ValueIteratorTypeGuard): LodashFilter4x1; - (predicate: lodash.__, collection: T | null | undefined): LodashFilter4x2; + (predicate: lodash.ValueIteratorTypeGuard): LodashFilter3x1; + (predicate: lodash.__, collection: T | null | undefined): LodashFilter3x2; (predicate: lodash.ValueIteratorTypeGuard, collection: T | null | undefined): S[]; (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): Array; } - type LodashFilter1x1 = (collection: string | null | undefined) => string[]; - type LodashFilter1x2 = (predicate: (value: string) => boolean) => string[]; - type LodashFilter2x1 = (collection: lodash.List | null | undefined) => S[]; - interface LodashFilter2x2 { + type LodashFilter1x1 = (collection: lodash.List | null | undefined) => S[]; + interface LodashFilter1x2 { (predicate: lodash.ValueIteratorTypeGuard): S[]; (predicate: lodash.ValueIterateeCustom): T[]; } - type LodashFilter3x1 = (collection: lodash.List | object | null | undefined) => T[]; - type LodashFilter4x1 = (collection: T | null | undefined) => S[]; - interface LodashFilter4x2 { + type LodashFilter2x1 = (collection: lodash.List | object | null | undefined) => T[]; + type LodashFilter3x1 = (collection: T | null | undefined) => S[]; + interface LodashFilter3x2 { (predicate: lodash.ValueIteratorTypeGuard): S[]; (predicate: lodash.ValueIterateeCustom): Array; } @@ -2131,45 +2104,40 @@ declare namespace _ { type LodashMapKeys2x1 = (object: T | null | undefined) => lodash.Dictionary; type LodashMapKeys2x2 = (iteratee: lodash.ValueIteratee) => lodash.Dictionary; interface LodashMapValues { - (callback: (value: string) => TResult): LodashMapValues1x1; - (callback: lodash.__, obj: string | null | undefined): LodashMapValues1x2; - (callback: (value: string) => TResult, obj: string | null | undefined): lodash.NumericDictionary; - (callback: (value: T) => TResult): LodashMapValues2x1; - (callbackOrIterateeOrIterateeOrIteratee: lodash.__, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashMapValues2x2; + (callback: (value: T) => TResult): LodashMapValues1x1; + (callbackOrIterateeOrIterateeOrIteratee: lodash.__, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): LodashMapValues1x2; (callback: (value: T) => TResult, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; - (callback: (value: T[keyof T]) => TResult): LodashMapValues3x1; - (callbackOrIterateeOrIteratee: lodash.__, obj: T | null | undefined): LodashMapValues3x2; + (callback: (value: T[keyof T]) => TResult): LodashMapValues2x1; + (callbackOrIterateeOrIteratee: lodash.__, obj: T | null | undefined): LodashMapValues2x2; (callback: (value: T[keyof T]) => TResult, obj: T | null | undefined): { [P in keyof T]: TResult }; - (iteratee: object): LodashMapValues4x1; + (iteratee: object): LodashMapValues3x1; (iteratee: object, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; (iteratee: object, obj: T | null | undefined): { [P in keyof T]: boolean }; - (iteratee: TKey): LodashMapValues6x1; + (iteratee: TKey): LodashMapValues5x1; (iteratee: TKey, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; - (iteratee: string): LodashMapValues7x1; + (iteratee: string): LodashMapValues6x1; (iteratee: string, obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; (iteratee: string, obj: T | null | undefined): { [P in keyof T]: any }; } - type LodashMapValues1x1 = (obj: string | null | undefined) => lodash.NumericDictionary; - type LodashMapValues1x2 = (callback: (value: string) => TResult) => lodash.NumericDictionary; - type LodashMapValues2x1 = (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined) => lodash.Dictionary; - interface LodashMapValues2x2 { + type LodashMapValues1x1 = (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined) => lodash.Dictionary; + interface LodashMapValues1x2 { (callback: (value: T) => TResult): lodash.Dictionary; (iteratee: object): lodash.Dictionary; (iteratee: TKey): lodash.Dictionary; (iteratee: string): lodash.Dictionary; } - type LodashMapValues3x1 = (obj: T | null | undefined) => { [P in keyof T]: TResult }; - interface LodashMapValues3x2 { + type LodashMapValues2x1 = (obj: T | null | undefined) => { [P in keyof T]: TResult }; + interface LodashMapValues2x2 { (callback: (value: T[keyof T]) => TResult): { [P in keyof T]: TResult }; (iteratee: object): { [P in keyof T]: boolean }; (iteratee: string): { [P in keyof T]: any }; } - interface LodashMapValues4x1 { + interface LodashMapValues3x1 { (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; (obj: T | null | undefined): { [P in keyof T]: boolean }; } - type LodashMapValues6x1 = (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined) => lodash.Dictionary; - interface LodashMapValues7x1 { + type LodashMapValues5x1 = (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined) => lodash.Dictionary; + interface LodashMapValues6x1 { (obj: lodash.Dictionary | lodash.NumericDictionary | null | undefined): lodash.Dictionary; (obj: T | null | undefined): { [P in keyof T]: any }; } @@ -3536,20 +3504,15 @@ declare namespace _ { type LodashReduceRight3x5 = (accumulator: TResult) => TResult; type LodashReduceRight3x6 = (callback: lodash.MemoIteratorCappedRight) => TResult; interface LodashReject { - (predicate: (value: string) => boolean): LodashReject1x1; - (predicate: lodash.__, collection: string | null | undefined): LodashReject1x2; - (predicate: (value: string) => boolean, collection: string | null | undefined): string[]; - (predicate: lodash.ValueIterateeCustom): LodashReject2x1; - (predicate: lodash.__, collection: lodash.List | null | undefined): LodashReject2x2; + (predicate: lodash.ValueIterateeCustom): LodashReject1x1; + (predicate: lodash.__, collection: lodash.List | null | undefined): LodashReject1x2; (predicate: lodash.ValueIterateeCustom, collection: lodash.List | null | undefined): T[]; - (predicate: lodash.__, collection: T | null | undefined): LodashReject3x2; + (predicate: lodash.__, collection: T | null | undefined): LodashReject2x2; (predicate: lodash.ValueIterateeCustom, collection: T | null | undefined): Array; } - type LodashReject1x1 = (collection: string | null | undefined) => string[]; - type LodashReject1x2 = (predicate: (value: string) => boolean) => string[]; - type LodashReject2x1 = (collection: lodash.List | object | null | undefined) => T[]; - type LodashReject2x2 = (predicate: lodash.ValueIterateeCustom) => T[]; - type LodashReject3x2 = (predicate: lodash.ValueIterateeCustom) => Array; + type LodashReject1x1 = (collection: lodash.List | object | null | undefined) => T[]; + type LodashReject1x2 = (predicate: lodash.ValueIterateeCustom) => T[]; + type LodashReject2x2 = (predicate: lodash.ValueIterateeCustom) => Array; interface LodashRemove { (predicate: lodash.ValueIteratee): LodashRemove1x1; (predicate: lodash.__, array: lodash.List): LodashRemove1x2; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 9d2547dcf4..64d445c65a 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -1766,6 +1766,8 @@ _.chain([1, 2, 3, 4]).unshift(5, 6); // $ExpectType LoDashExplicitWrapper s === "a")(["a", "b"]); // $ExpectType string[] + fp.filter((s: string) => s === "a")("ab"); // $ExpectType string[] // Test filtering with type guard const a2: Array | null | undefined = anything; @@ -2337,7 +2339,7 @@ _.chain([1, 2, 3, 4]).unshift(5, 6); // $ExpectType LoDashExplicitWrapper }); - fp.forEach(stringIterator, ""); // $ExpectType string + fp.forEach(stringIterator, ""); // $ExpectType ArrayLike fp.forEach(valueIterator, array); // $ExpectType AbcObject[] fp.forEach(valueIterator)(array); // $ExpectType AbcObject[] fp.forEach(valueIterator, list); // $ExpectType ArrayLike diff --git a/types/lodash/scripts/generate-fp.ts b/types/lodash/scripts/generate-fp.ts index 817b485cf2..8dc4b7d3eb 100644 --- a/types/lodash/scripts/generate-fp.ts +++ b/types/lodash/scripts/generate-fp.ts @@ -153,6 +153,7 @@ async function processDefinitions(filePaths: string[], commonTypes: string[]): P for (const filePath of filePaths) { const definitions = await parseFile(filePath, commonTypes); for (const definition of definitions) { + definition.overloads = definition.overloads.filter(o => !o.params.some(p => p.includes('StringIterator'))); if (definition.overloads.every(o => o.params.length <= 1 && (o.returnType === "typeof _" || o.returnType === "LoDashStatic"))) { // Our convert technique doesn't work well on "typeof _" functions (or at least runInContext) // Plus, if there are 0-1 parameters, there's nothing to curry anyways. diff --git a/types/loopbench/index.d.ts b/types/loopbench/index.d.ts new file mode 100644 index 0000000000..bd5e61d3e2 --- /dev/null +++ b/types/loopbench/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for loopbench 1.2 +// Project: https://github.com/mcollina/loopbench#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { EventEmitter } from 'events'; + +export = loopbench; + +/** + * Creates a new instance of loopbench. + */ +declare function loopbench(options?: loopbench.Options): loopbench.LoopBench; + +declare namespace loopbench { + interface Options { + /** + * The interval at which the eventLoop should be sampled, defaults to `5`. + */ + sampleInterval?: number; + /** + * The maximum amount of delay that is tolerated before `overLimit` becomes true, + * and the `load` event is emitted, defaults to `42`. + */ + limit?: number; + } + + /** + * Events: + * - `load`, emitted when `instance.delay > instance.limit` + * - `unload`, emitted when `overLimit` goes from `true` and `false` + */ + interface LoopBench extends EventEmitter { + /** + * The delay in milliseconds (and fractions) from the expected run. It might be negative (in older nodes). + */ + readonly delay: number; + + /** + * The maximum amount of delay that is tolerated before `overLimit` becomes true, + * and the `load` event is emitted. + */ + readonly limit: number; + + /** + * Is `true` if the `instance.delay > instance.limit`. + */ + readonly overLimit: boolean; + + /** + * Stops the sampling. + */ + stop(): void; + + addListener(event: 'load' | 'unload', listener: () => void): this; + on(event: 'load' | 'unload', listener: () => void): this; + once(event: 'load' | 'unload', listener: () => void): this; + removeListener(event: 'load' | 'unload', listener: () => void): this; + off(event: 'load' | 'unload', listener: () => void): this; + removeAllListeners(event?: 'load' | 'unload'): this; + listeners(event: 'load' | 'unload'): Array<() => void>; + rawListeners(event: 'load' | 'unload'): Array<() => void>; + emit(event: 'load' | 'unload'): boolean; + listenerCount(type: 'load' | 'unload'): number; + prependListener(event: 'load' | 'unload', listener: () => void): this; + prependOnceListener(event: 'load' | 'unload', listener: () => void): this; + eventNames(): Array<'load' | 'unload'>; + } +} diff --git a/types/loopbench/loopbench-tests.ts b/types/loopbench/loopbench-tests.ts new file mode 100644 index 0000000000..e78a22e08a --- /dev/null +++ b/types/loopbench/loopbench-tests.ts @@ -0,0 +1,11 @@ +import loopbench = require('loopbench'); + +const inst = loopbench(); +inst; // $ExpectType LoopBench +loopbench({ sampleInterval: 1 }); // $ExpectType LoopBench +loopbench({ limit: 1 }); // $ExpectType LoopBench + +inst.delay; // $ExpectType number +inst.limit; // $ExpectType number +inst.overLimit; // $ExpectType boolean +inst.stop(); diff --git a/types/loopbench/tsconfig.json b/types/loopbench/tsconfig.json new file mode 100644 index 0000000000..05e37ab0fa --- /dev/null +++ b/types/loopbench/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", + "loopbench-tests.ts" + ] +} diff --git a/types/loopbench/tslint.json b/types/loopbench/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/loopbench/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lozad/index.d.ts b/types/lozad/index.d.ts index 6257c47043..8c24d888e6 100644 --- a/types/lozad/index.d.ts +++ b/types/lozad/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for lozad 1.1 +// Type definitions for lozad 1.2 // Project: https://github.com/ApoorvSaxena/lozad.js // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,18 +7,22 @@ declare namespace lozad { interface Option { rootMargin?: string; threshold?: number; - load?(element: HTMLElement | HTMLCanvasElement): void; + load?(element: Element): void; + loaded?(element: Element): void; } interface Observer { observe(): void; + triggerLoad(element: Element): void; } + type Selector = string | Element | HTMLCollectionOf | NodeListOf; + const prototype: { }; } -declare function lozad(selector?: string, options?: lozad.Option): lozad.Observer; +declare function lozad(selector?: lozad.Selector, options?: lozad.Option): lozad.Observer; export as namespace lozad; diff --git a/types/lozad/lozad-tests.ts b/types/lozad/lozad-tests.ts index ad3ff13eea..a7b74a2fb0 100644 --- a/types/lozad/lozad-tests.ts +++ b/types/lozad/lozad-tests.ts @@ -8,6 +8,21 @@ const observer = lozad('.lozad', { // Custom implementation to load an element // e.g. el.src = el.dataset.src; + }, + loaded(el) { + console.log('loaded element'); } }); observer.observe(); + +const singleElement = document.getElementById('hello'); +if (singleElement) { + const observer2 = lozad(singleElement); + observer2.triggerLoad(singleElement); +} + +const elementsCollection = document.getElementsByClassName('lozad'); +if (elementsCollection) lozad(elementsCollection); + +const nodeList = document.querySelectorAll('.images'); +if (nodeList) lozad(nodeList); diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index 415c7c1d8f..ab59d556f6 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -535,6 +535,24 @@ declare namespace lunr { } namespace Query { + /** + * Constants for indicating what kind of presence a term must have in matching documents. + */ + enum presence { + /** + * Term's presence in a document is optional, this is the default value. + */ + OPTIONAL = 1, + /** + * Term's presence in a document is required, documents that do not contain this term will not be returned. + */ + REQUIRED = 2, + /** + * Term's presence in a document is prohibited, documents that do contain this term will not be returned. + */ + PROHIBITED = 3 + } + enum wildcard { NONE = 0, LEADING = 1 << 0, @@ -598,6 +616,12 @@ declare namespace lunr { * Adds a term to the current query, under the covers this will create a {@link lunr.Query~Clause} * to the list of clauses that make up this query. * + * The term is used as is, i.e. no tokenization will be performed by this method. Instead conversion + * to a token or token-like string should be done before calling this method. + * + * The term will be converted to a string by calling `toString`. Multiple terms can be passed as an + * array, each term in the array will share the same options. + * * @param term - The term to add to the query. * @param [options] - Any additional properties to add to the query clause. * @see lunr.Query#clause @@ -611,7 +635,7 @@ declare namespace lunr { * wildcard: lunr.Query.wildcard.TRAILING * }) */ - term(term: string, options: object): Query; + term(term: string | string[] | Token | Token[], options: object): Query; } class QueryParseError extends Error { diff --git a/types/lunr/lunr-tests.ts b/types/lunr/lunr-tests.ts index a14fd1947f..4d3fa57461 100644 --- a/types/lunr/lunr-tests.ts +++ b/types/lunr/lunr-tests.ts @@ -25,6 +25,16 @@ function basic_test() { }); index.search("foo"); + + index.query(q => { + q.term( + lunr.tokenizer('search terms'), + { + wildcard: lunr.Query.wildcard.TRAILING, + presence: lunr.Query.presence.REQUIRED + } + ); + }); } function pipeline_test() { diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 8d5b17d697..d2a4e474b8 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for luxon 1.4 +// Type definitions for luxon 1.10 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart // Hyeonseok Yang // Jonathan Siebern // Matt R. Wilson +// Pietro Vismara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,6 +24,35 @@ declare module 'luxon' { round?: boolean; }; + type ToRelativeOptions = { + /** The DateTime to use as the basis to which this time is compared. Defaults to now. */ + base?: DateTime; + locale?: string; + style?: 'long' | 'short' | 'narrow'; + /** If omitted, the method will pick the unit. */ + unit?: 'year' | 'quarter' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second'; + /** Defaults to `true`. */ + round?: boolean; + /** + * Padding in milliseconds. This allows you to round up the result if it fits inside the threshold. + * Don't use in combination with {round: false} because the decimal output will include the padding. + * Defaults to 0. + */ + padding?: number; + /** The Intl system may choose not to honor this */ + numberingSystem?: string; + }; + + type ToRelativeCalendarOptions = { + /** The DateTime to use as the basis to which this time is compared. Defaults to now. */ + base?: DateTime; + locale?: string; + /** If omitted, the method will pick the unit. */ + unit?: 'year' | 'quarter' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second'; + /** The Intl system may choose not to honor this. */ + numberingSystem?: string; + }; + type ToSQLOptions = { includeOffset?: boolean; includeZone?: boolean; @@ -115,6 +145,7 @@ declare module 'luxon' { text: string, options?: DateTimeOptions ): DateTime; + static fromSeconds(seconds: number, options?: DateTimeOptions): DateTime; static fromSQL(text: string, options?: DateTimeOptions): DateTime; static fromFormat( text: string, @@ -196,6 +227,7 @@ declare module 'luxon' { weeksInWeekYear: number; year: number; zoneName: string; + zone: Zone; diff( other: DateTime, unit?: DurationUnit | DurationUnit[], @@ -229,7 +261,10 @@ declare module 'luxon' { toMillis(): number; toMillis(): number; toObject(options?: { includeConfig?: boolean }): DateObject; + toRelative(options?: ToRelativeOptions): string | null; + toRelativeCalendar(options?: ToRelativeCalendarOptions): string | null; toRFC2822(): string; + toSeconds(): number; toSQL(options?: ToSQLOptions): string; toSQLDate(): string; toSQLTime(options?: ToSQLOptions): string; @@ -393,6 +428,7 @@ declare module 'luxon' { toISO(options?: ISOTimeOptions): string; toString(): string; union(other: Interval): Interval; + mapEndpoints(cb: (d: DateTime) => DateTime): Interval; } namespace Settings { diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index 587210815c..7387497c2e 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -39,16 +39,41 @@ dt.toLocaleString(); dt.toLocaleString(DateTime.DATE_MED); dt.toISO(); dt.toISO({includeOffset: true}); +dt.toSeconds(); dt.toSQL(); dt.toSQL({includeOffset: false, includeZone: true}); dt.toSQLDate(); dt.toSQLTime(); dt.toSQLTime({includeOffset: false, includeZone: true}); +dt.toRelative(); +dt.toRelativeCalendar(); + +// $ExpectType string | null +dt.toRelative({ + base: DateTime.local(), + locale: 'fr', + style: 'long', + unit: 'day', + round: true, + padding: 10, + numberingSystem: 'bali', +}); + +// $ExpectType string | null +dt.toRelativeCalendar({ + base: DateTime.local(), + locale: 'fr', + unit: 'day', + numberingSystem: 'bali', +}); + dt.plus({ hours: 3, minutes: 2 }); dt.minus({ days: 7 }); dt.startOf('day'); dt.endOf('hour'); +dt.zone; +dt.zoneName; dt.set({ hour: 3 }).hour; @@ -67,7 +92,7 @@ DateTime.utc().toLocal(); DateTime.fromMillis(1527780819458).toMillis(); -const {input, result, zone} = DateTime.fromFormatExplain("Aug 6 1982", "MMMM d yyyy"); +const {input, result, zone} = DateTime.fromFormatExplain('Aug 6 1982', 'MMMM d yyyy'); /* Duration */ const dur = Duration.fromObject({ hours: 2, minutes: 7 }); @@ -87,6 +112,7 @@ i.length(); i.length('years'); i.contains(DateTime.local(2019)); i.set({end: DateTime.local(2020)}); +i.mapEndpoints((d) => d); i.toISO(); i.toString(); diff --git a/types/mangopay2-nodejs-sdk/index.d.ts b/types/mangopay2-nodejs-sdk/index.d.ts new file mode 100644 index 0000000000..e27565df18 --- /dev/null +++ b/types/mangopay2-nodejs-sdk/index.d.ts @@ -0,0 +1,4387 @@ +// Type definitions for mangopay2-nodejs-sdk 1.9 +// Project: https://github.com/MangoPay/mangopay2-nodejs-sdk +// Definitions by: Ifiok Jr. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +import { + ApiMethod, + CountryISO, + CurrencyISO, + MakeKeysRequired, + Omit, + OmitType, + PickPartialRequired, + ValueOf, + PickPartial, + DeepPartial +} from "./types"; + +export = MangoPay; + +declare class MangoPay { + constructor(config: MangoPay.Config); + config: MangoPay.Config; + requestOptions: MangoPay.RequestOptions; + Users: MangoPay.Users; + BankAccounts: MangoPay.BankAccounts; + BankingAliases: MangoPay.BankingAliases; + DisputeDocuments: MangoPay.DisputeDocuments; + Wallets: MangoPay.Wallets; + KycDocuments: MangoPay.KycDocuments; + UboDeclarations: MangoPay.UboDeclarations; + Cards: MangoPay.Cards; + CardRegistrations: MangoPay.CardRegistrations; + CardPreAuthorizations: MangoPay.CardPreAuthorizations; + PayIns: MangoPay.PayIns; + Transfers: MangoPay.Transfers; + PayOuts: MangoPay.PayOuts; + Refunds: MangoPay.Refunds; + Clients: MangoPay.Clients; + Disputes: MangoPay.Disputes; + Repudiations: MangoPay.Repudiations; + Events: MangoPay.Events; + Responses: MangoPay.Responses; + Mandates: MangoPay.Mandates; + Hooks: MangoPay.Hooks; + Reports: MangoPay.Reports; + + models: typeof MangoPay.models; + + Log(...args: any[]): void; + authorize(callback: (data: MangoPay.AuthorizationData) => void): void; + authorize(): Promise; + buildRequestData(entity: any): any; + canReadSubRequestData(entity: any, propertyName: any): boolean; + isExpired(): boolean; + method( + method: ApiMethod, + callback: (...args: any[]) => void, + options: MangoPay.RequestOptions + ): any; +} + +declare namespace MangoPay { + interface AuthorizationData { + access_token: string; + token_type: string; + expires_in: number; + } + + interface Headers { + "Content-Type": string; + "User-Agent": string; + "Idempotency-Key": string; + Authorization: string; + [header: string]: string | undefined; + } + + /** A UTC timestamp in seconds */ + type Timestamp = number; + type ColumnAndDirection = "ASC" | "DESC"; + type AVSResult = + | "NO_CHECK" + | "NO_MATCH" + | "ADDRESS_MATCH_ONLY" + | "POSTAL_CODE_MATCH_ONLY" + | "FULL_MATCH"; + type SecureMode = "DEFAULT" | "FORCE"; + type PreAuthorizationExecutionType = "DIRECT"; + type PaymentStatus = "WAITING" | "CANCELED" | "EXPIRED" | "VALIDATED"; + type PreAuthorizationStatus = "CREATED" | "SUCCEEDED" | "FAILED"; + interface BillingData { + Address: models.Address | address.AddressData | string; + } + + interface SecurityInfoData { + AVSResult: AVSResult; + } + + interface MoneyData { + /** + * The currency - should be ISO_4217 format + */ + Currency: CurrencyISO; + + /** + * An amount of money in the smallest sub-division of the currency, e.g. 12.60 EUR would be represented as 1260 whereas 12 JPY would be represented as just 12) + */ + Amount: number; + } + + interface WithResponse { + statusCode: number; + body: T; + headers: Headers; + } + + interface NoArgMethodOverload { + (options: MethodOptionWithResponse): Promise>; + (options?: MethodOptionWithoutResponse): Promise; + ( + callback: (data: WithResponse) => void, + options?: MethodOptionWithResponse + ): void; + (callback: (data: R) => void, options?: MethodOptionWithoutResponse): void; + } + + interface MethodOverload { + (data: T, options: MethodOptionWithResponse): Promise>; + (data: T, options?: MethodOptionWithoutResponse): Promise; + ( + data: T, + callback: (data: WithResponse) => void, + options: MethodOptionWithResponse + ): void; + ( + data: T, + callback: (data: R) => void, + options?: MethodOptionWithoutResponse + ): void; + } + + interface TwoArgsMethodOverload { + (data: T, extra: U, options: MethodOptionWithResponse): Promise< + WithResponse + >; + (data: T, extra: U, options?: MethodOptionWithoutResponse): Promise; + ( + data: T, + extra: U, + callback: (data: WithResponse) => void, + options?: MethodOptionWithResponse + ): void; + ( + data: T, + extra: U, + callback: (data: R) => void, + options?: MethodOptionWithoutResponse + ): void; + } + + interface ThreeArgsMethodOverload { + (data: T, extra: U, lastArg: V, options: MethodOptionWithResponse): Promise< + WithResponse + >; + ( + data: T, + extra: U, + lastArg: V, + options?: MethodOptionWithoutResponse + ): Promise; + ( + data: T, + extra: U, + lastArg: V, + callback: (data: WithResponse) => void, + options?: MethodOptionWithResponse + ): void; + ( + data: T, + extra: U, + lastArg: V, + callback: (data: R) => void, + options?: MethodOptionWithoutResponse + ): void; + } + + interface Config { + /** + * API Client Id + */ + clientId: string; + + /** + * API Client Api Key + */ + clientApiKey: string; + + /** + * API Base URL.The fault base value points to sandbox. + * Production is 'https://api.mangopay.com' + * + * @default "https://api.sandbox.mangopay.com" + */ + baseUrl?: string; + + /** + * Active debugging + * @default false + */ + debugMode?: boolean; + + /** + * Log function to be used for debug + * @default `console.log` + */ + logClass?(...args: any[]): void; + + /** + * Set the connection timeout limit(in milliseconds) + * @default 30000 + */ + connectionTimeout?: number; + + /** + * Set the response timeout limit(in milliseconds) + * @default 80000 + */ + responseTimeout?: number; + + /** + * API Version + * @default 'v2.01' + */ + apiVersion?: string; + + /** + * Set a custom error handler + * @default `console.error` + */ + errorHandler?(options: any, err: any): void; + } + + interface RequestOptions { + requestConfig: { + timeout: number; + }; + responseConfig: { + timeout: number; + }; + + /** + * Path options are replacing the ${placeholders} from apiMethods + */ + path: { + clientId: string; + apiVersion: string; + readonly id: string; + }; + headers: Partial; + } + + type WithToJson = T & { toJSON(): any }; + + // Determines the shape of the response + interface ReadResponseHeaders { + readResponseHeaders: true; + } + + interface PaginationOptions { + /** + * The page number of results you wish to return + * @default 1 + */ + Page?: number; + + /** + * The number of results to return per page: Max 100; + * @default 10 + */ + Per_Page?: number; + } + + interface FilterOptions extends Record { + /** + * The column to sort against and direction - only CreationDate (or Date for the events) is available and ASC or DESC for the direction + */ + Sort?: ColumnAndDirection; + + /** + * To return only resources that have CreationDate BEFORE this date + */ + BeforeDate?: Timestamp; + + /** + * To return only resources that have CreationDate AFTER this date + */ + AfterDate?: Timestamp; + } + + interface MethodOptions extends DeepPartial { + data?: WithToJson | string; + parameters?: FilterOptions & PaginationOptions; + } + + interface MethodOptionWithResponse extends MethodOptions { + readResponseHeaders: true; + } + + interface MethodOptionWithoutResponse extends MethodOptions { + readResponseHeaders?: false; + } + + interface DependsObject { + dependsPropertyName: string; + propertyName: string; + propertyValueMapping: Record; + } + + interface ModelMethods { + initialize(): void; + + /** + * Returns object property value + * @param attribute + */ + getData(attribute: K): T[K]; + + /** + * @param attribute - attribute's value to be set or hash of properties with values + * @param value - value to be set + */ + setData(attribute: K, value: T[K]): this; + setData(attribute: Partial): this; + + getReadOnlyProperties(): Array; + getDependsObjects(): DependsObject[]; + parse(): void; + } + + namespace models { + const PayInExecutionType: IPayInExecutionType; + const PayInPaymentType: IPayInPaymentType; + const MandateStatus: IMandateStatus; + const LegalPersonType: ILegalPersonType; + const PersonType: IPersonType; + const BankAccountType: IBankAccountType; + const DeclaredUboStatus: IDeclaredUboStatus; + const KycDocumentStatus: IKycDocumentStatus; + const KycDocumentType: IKycDocumentType; + const PayOutPaymentType: IPayOutPaymentType; + const PlatformType: IPlatformType; + const UboDeclarationRefusedReasonType: IUboDeclarationRefusedReasonType; + const UboDeclarationStatus: IUboDeclarationStatus; + const UboRefusedReasonType: IUboRefusedReasonType; + const UserNaturalCapacity: IUserNaturalCapacity; + class DeclaredUbo extends Model { + constructor(data: Partial); + } + + class Model implements ModelMethods { + initialize(): void; + getData(attribute: K): T[K]; + setData(attribute: K, value: T[K]): this; + setData(attribute: Partial): this; + setData(attribute: any, value?: any): this; + getReadOnlyProperties(): Array; + getDependsObjects(): DependsObject[]; + parse(): void; + constructor(data: T); + } + + class EntityBase extends Model { + initialize(): void; + + /** + * Returns object property value + */ + getData(attribute: K): T[K]; + + /** + * @param attribute - attribute's value to be set or hash of properties with values + * @param value - value to be set + */ + setData(attribute: K, value: T[K]): this; + setData(attribute: Partial): this; + + getReadOnlyProperties(): Array; + getDependsObjects(): DependsObject[]; + parse(): void; + toJSON(): any; + } + + class Money extends EntityBase { + constructor(data: MoneyData); + } + + class Billing extends EntityBase { + constructor(data: BillingData); + } + + class Address extends EntityBase { + constructor(data: Partial); + } + + interface Address extends address.AddressData {} + + class BankingAlias extends EntityBase { + constructor(data: Partial); + } + + class BankingAliasIBAN extends BankingAlias {} + + interface BankingAlias extends bankingAlias.IBANBankingAliasData {} + + class BankAccount extends EntityBase { + constructor(data: bankAccount.CreationDetails); + } + interface BankAccount extends bankAccount.DataIntersection {} + + class BankAccountDetails { + constructor(data: any); + } + + class BankAccountDetailsCA extends BankAccountDetails { + constructor(data: any); + } + + interface BankAccountDetailsCA extends bankAccount.CADetails {} + + class BankAccountDetailsOther extends BankAccountDetails { + constructor(data: any); + } + + interface BankAccountDetailsOther extends bankAccount.OtherDetails {} + + class BankAccountDetailsGB extends BankAccountDetails { + constructor(data: any); + } + + interface BankAccountDetailsGB extends bankAccount.GBDetails {} + + class BankAccountDetailsIBAN extends BankAccountDetails { + constructor(data: any); + } + + interface BankAccountDetailsIBAN extends bankAccount.IBANDetails {} + + class BankAccountDetailsUS extends BankAccountDetails { + constructor(data: any); + } + + interface BankAccountDetailsUS extends bankAccount.USDetails {} + + class Transaction extends EntityBase { + constructor(data: transaction.TransactionData); + } + + interface Transaction extends transaction.TransactionData {} + + class ClientWallet extends EntityBase {} + + class Wallet extends EntityBase { + constructor(data: wallet.CreateWallet | wallet.UpdateWallet); + } + + class DocumentPageConsult extends Model { + constructor(data: Partial); + } + + interface DocumentPageConsult extends disputeDocument.DocumentPageConsult {} + + class Document extends EntityBase { + constructor(data: any); + } + + class DisputeDocument extends Document {} + + interface DisputeDocument extends disputeDocument.DisputeDocumentData {} + + class DisputeDocumentPage extends EntityBase { + constructor(data: disputeDocument.CreateDisputeDocumentPage); + } + + interface DisputeDocumentPage + extends disputeDocument.CreateDisputeDocumentPage {} + + class KycDocument extends EntityBase { + constructor(data: Partial); + } + + interface KycDocument extends kycDocument.KycDocumentData {} + + class KycPage { + constructor(data: kycDocument.CreateKycPage); + } + + interface KycPage extends kycDocument.CreateKycPage {} + + class EMoney { + constructor(data: eMoney.EMoneyData); + } + + interface EMoney extends eMoney.EMoneyData {} + + class UboDeclaration extends EntityBase { + constructor( + data: + | uboDeclaration.CreateUboDeclaration + | uboDeclaration.UpdateUboDeclaration + ); + } + + interface UboDeclaration extends uboDeclaration.UboDeclarationData {} + + class CardRegistration extends EntityBase< + cardRegistration.CardRegistrationData + > { + constructor( + data: + | cardRegistration.CreateCardRegistration + | cardRegistration.UpdateCardRegistration + ); + } + + interface CardRegistration extends cardRegistration.CardRegistrationData {} + + class Card extends EntityBase { + constructor(data: card.CardData); + } + + interface Card extends card.CardData {} + + class CardPreAuthorization { + constructor( + data: + | cardPreAuthorization.CardPreAuthorizationData + | cardPreAuthorization.UpdateCardPreAuthorization + ); + } + + interface CardPreAuthorization + extends cardPreAuthorization.CardPreAuthorizationData {} + + class SecurityInfo extends EntityBase< + SecurityInfo & entityBase.EntityBaseData + > { + constructor(data: SecurityInfo); + } + + class UserLegal extends EntityBase { + PersonType: "LEGAL"; + constructor( + data: MakeKeysRequired< + Partial, + user.RequiredUserLegalData + > + ); + + /** + * Sets the person type for the model + * @param personType + */ + setPersonType(type: user.PersonType): void; + } + + interface UserLegal extends user.UserLegalData {} + + class UserNatural extends EntityBase { + PersonType: "NATURAL"; + constructor( + data: MakeKeysRequired< + Partial, + user.RequiredUserNaturalData + > + ); + + /** + * Sets the person type for the model + * @param personType + */ + setPersonType(type: user.PersonType): void; + } + + interface UserNatural extends user.UserNaturalData {} + + class User extends EntityBase { + constructor(data: user.UserData); + + /** + * Sets the person type for the model + * @param personType + */ + setPersonType(type: user.PersonType): void; + } + + interface User extends user.UserData {} + + class PayIn extends EntityBase { + constructor(data: any); + } + + interface PayIn extends payIn.BasePayInData {} + + class PayInPaymentDetails extends EntityBase { + constructor(data: any); + } + + class PayInExecutionDetails extends EntityBase { + constructor(data: any); + } + + class PayInExecutionDetailsDirect extends PayInExecutionDetails { + constructor(data: any); + } + + class PayInExecutionDetailsWeb extends PayInExecutionDetails { + constructor(data: any); + } + + class PayInPaymentDetailsBankWire extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsBankingAlias extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsCard extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsCardDirect extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsCardWeb extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsDirectDebitDirect extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsDirectDebitWeb extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsPayPal extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInPaymentDetailsPreAuthorized extends PayInPaymentDetails { + constructor(data: any); + } + + class PayInTemplateURLOptions extends EntityBase { + constructor(data: any); + } + + class Refund extends EntityBase { + constructor(data: refund.CreatePayInRefund | refund.CreateTransferRefund); + } + + class RefundReasonDetails extends EntityBase { + constructor(data: any); + } + + class Repudiation extends EntityBase { + constructor(data: Partial); + } + + interface Repudiation extends repudiation.RepudiationData {} + + class Client extends EntityBase { + constructor(data?: Partial); + } + + interface Client extends client.ClientData {} + + class PlatformCategorization extends EntityBase< + client.PlatformCategorization + > { + constructor(data: client.PlatformCategorization); + } + + class Dispute extends EntityBase { + constructor(data: Partial); + } + + interface Dispute extends dispute.DisputeData {} + + class DisputeReason extends Model { + constructor(data: any); + } + + class SettlementTransfer extends EntityBase< + settlementTransfer.SettlementTransferData + > { + constructor(data: Partial); + } + + interface SettlementTransfer + extends settlementTransfer.SettlementTransferData {} + + class Transfer extends EntityBase { + constructor(data: Partial); + } + + interface Transfer extends transfer.TransferData {} + + class PayOut extends EntityBase { + constructor(data: Partial); + } + // interface PayOut extends PayOut.PayoutData {} + + class PayOutPaymentDetails extends EntityBase { + constructor(data?: any); + } + + class PayOutPaymentDetailsBankWire extends PayOutPaymentDetails { + constructor(data?: any); + } + + class Mandate extends EntityBase { + constructor(data?: Partial); + } + + interface Mandate extends mandate.MandateData {} + + class Hook extends EntityBase { + constructor(data?: Partial); + } + + interface Hook extends hook.HookData {} + + class Report extends EntityBase { + constructor(data?: Partial); + } + + interface Report extends report.ReportData {} + + class ReportFilter extends Model { + constructor(data?: Partial); + } + + interface Report extends report.Filters {} + } + + interface IPayInExecutionType { + Direct: "DIRECT"; + Web: "WEB"; + } + + interface IPayInPaymentType { + BankWire: "BANK_WIRE"; + Card: "CARD"; + DirectDebit: "DIRECT_DEBIT"; + Preauthorized: "PREAUTHORIZED"; + PayPal: "PAYPAL"; + } + + interface IMandateStatus { + Created: "CREATED"; + Submitted: "SUBMITTED"; + Active: "ACTIVE"; + Failed: "FAILED"; + } + + interface ILegalPersonType { + NotSpecified: "NotSpecified"; + Business: "BUSINESS"; + Organization: "ORGANIZATION"; + Soletrader: "SOLETRADER"; + } + + interface IPersonType { + NotSpecified: "NotSpecified"; + Natural: "NATURAL"; + Legal: "LEGAL"; + } + + interface IBankAccountType { + NotSpecified: "NotSpecified"; + IBAN: "IBAN"; + GB: "GB"; + US: "US"; + CA: "CA"; + OTHER: "OTHER"; + } + + interface IDeclaredUboStatus { + Created: "CREATED"; + Validated: "VALIDATED"; + Refused: "REFUSED"; + } + + interface IKycDocumentStatus { + Created: "CREATED"; + ValidationAsked: "VALIDATION_ASKED"; + Validated: "VALIDATED"; + Refused: "REFUSED"; + } + + interface IKycDocumentType { + IdentityProof: "IDENTITY_PROOF"; + RegistrationProof: "REGISTRATION_PROOF"; + ArticlesOfAssociation: "ARTICLES_OF_ASSOCIATION"; + ShareholderDeclaration: "SHAREHOLDER_DECLARATION"; + AddressProof: "ADDRESS_PROOF"; + } + + interface IPayOutPaymentType { + BankWire: "BANK_WIRE"; + } + + interface IPlatformType { + NotSpecified: "NotSpecified"; + MARKETPLACE: "MARKETPLACE"; + P2P_PAYMENT: "P2P_PAYMENT"; + CROWDFUNDING_DONATION: "CROWDFUNDING_DONATION"; + CROWDFUNDING_REWARD: "CROWDFUNDING_REWARD"; + CROWDFUNDING_EQUITY: "CROWDFUNDING_EQUITY"; + CROWDFUNDING_LOAN: "CROWDFUNDING_LOAN"; + OTHER: "OTHER"; + } + + interface IUboDeclarationRefusedReasonType { + /** + * When at least one natural user is missing on the declaration + */ + MissingUbo: "MISSING_UBO"; + + /** + * When at least one natural user should not be declared as UBO + */ + InvalidDeclaredUbo: "INVALID_DECLARED_UBO"; + + /** + * When at least one natural user declared as UBO has been created + * with wrong details (i.e. date of birth, country of residence) + */ + InvalidUboDetails: "INVALID_UBO_DETAILS"; + } + + interface IUboDeclarationStatus { + /** + * When the UBO declaration was created + */ + Created: "CREATED"; + + /** + * When validation has been requested for the UBO declaration + */ + ValidationAsked: "VALIDATION_ASKED"; + + /** + * When the UBO declaration was validated + */ + Validated: "VALIDATED"; + + /** + * When the UBO declaration was refused + */ + Refused: "REFUSED"; + } + + interface IUboRefusedReasonType { + /** + * When user should not be declared as UBO + */ + InvalidDeclaredUbo: "INVALID_DECLARED_UBO"; + + /** + * When user declared as UBO was created with wrong + * details (i.e. date of birth, country of residence) + */ + InvalidUboDetails: "INVALID_UBO_DETAILS"; + } + + interface IUserNaturalCapacity { + /** + * Real customer + */ + Normal: "NORMAL"; + + /** + * User used only for declaration purpose + */ + Declarative: "DECLARATIVE"; + } + + namespace entityBase { + interface EntityBaseData { + Id: string; + Tag: string; + CreationDate: number; + } + } + + namespace address { + interface AddressData { + AddressLine1: string; + AddressLine2: string; + City: string; + Region: string; + PostalCode: string; + Country: string; + } + type AddressType = string | AddressData | models.Address; + } + + namespace bankingAlias { + type BankingAliasType = "IBAN"; + interface BankingAliasData extends entityBase.EntityBaseData { + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId: string; + + /** + * The ID of a wallet + */ + WalletId: string; + + /** + * The Country of the Address + */ + Country: CountryISO; + + /** + * The type of banking alias (note that only IBAN is available at present) + */ + Type: BankingAliasType; + + /** + * The owner of the wallet/banking alias + */ + OwnerName: string; + + /** + * Whether the banking alias is active or not + */ + Active: boolean; + } + + interface IBANBankingAliasData extends BankingAliasData { + /** + * The type of banking alias (note that only IBAN is available at present) + */ + Type: "IBAN"; + + /** + * The IBAN of the banking alias + */ + IBAN: string; + + /** + * The BIC of the banking alias + */ + BIC: string; + } + + interface CreateIBANBankingAlias + extends PickPartialRequired< + IBANBankingAliasData, + "Tag" | "CreditedUserId", + "OwnerName" | "Country" + > {} + } + + namespace bankAccount { + type BankAccountType = "IBAN" | "GB" | "US" | "CA" | "OTHER"; + type DepositAccountType = "CHECKING" | "SAVINGS"; + + interface BaseData extends entityBase.EntityBaseData { + /** + * The object owner's UserId + */ + UserId: string; + + /** + * The type of bank account + */ + Type: BankAccountType; + + /** + * The name of the owner of the bank account + */ + OwnerName: string; + + /** + * The address of the owner of the bank account + */ + OwnerAddress: address.AddressType; + + /** + * @deprecated + */ + Details?: models.BankAccountDetails; + + /** + * Whether the bank account is active or not + */ + Active: boolean; + } + + interface IBANDetails { + Type: "IBAN"; + + /** + * The address of the owner of the bank account + */ + OwnerAddress: address.AddressType; + + /** + * The name of the owner of the bank account + */ + OwnerName: string; + + /** + * The IBAN of the bank account + */ + IBAN: string; + + /** + * The BIC of the bank account + */ + BIC?: string; + } + + type IBANData = BaseData & IBANDetails; + + interface USDetails { + Type: "US"; + + /** + * The address of the owner of the bank account + */ + OwnerAddress: address.AddressType; + + /** + * The name of the owner of the bank account + */ + OwnerName: string; + + /** + * The account number of the bank account. US account numbers must be digits only. + */ + AccountNumber: string; + + /** + * The ABA of the bank account. Must be numbers only, and 9 digits long + */ + ABA: string; + + /** + * The type of account + */ + DepositAccountType?: DepositAccountType; + } + + type USData = BaseData & USDetails; + + interface CADetails { + Type: "CA"; + + /** + * The address of the owner of the bank account + */ + OwnerAddress: address.AddressType; + + /** + * The name of the owner of the bank account + */ + OwnerName: string; + + /** + * The branch code of the bank where the bank account. Must be numbers only, and 5 digits long + */ + BranchCode: string; + + /** + * The institution number of the bank account. Must be numbers only, and 3 or 4 digits long + */ + InstitutionNumber: string; + + /** + * The account number of the bank account. Must be numbers only. Canadian account numbers must be a maximum of 20 digits. + */ + AccountNumber: string; + + /** + * The name of the bank where the account is held. Must be letters or numbers only and maximum 50 characters long. + */ + BankName: string; + } + + type CAData = BaseData & CADetails; + + interface GBDetails { + Type: "GB"; + + /** + * The address of the owner of the bank account + */ + OwnerAddress: address.AddressType; + + /** + * The name of the owner of the bank account + */ + OwnerName: string; + + /** + * The sort code of the bank account. Must be numbers only, and 6 digits long + */ + SortCode: string; + + /** + * The account number of the bank account. Must be numbers only. GB account numbers must be 8 digits long. + */ + AccountNumber: string; + } + + type GBData = BaseData & GBDetails; + + interface OtherDetails { + Type: "OTHER"; + + /** + * The address of the owner of the bank account + */ + OwnerAddress: address.AddressType; + + /** + * The name of the owner of the bank account + */ + OwnerName: string; + + /** + * The Country of the Address + */ + Country: string; + + /** + * The BIC of the bank account + */ + BIC: string; + + /** + * The account number of the bank account. Must be numbers only. Canadian account numbers must be a maximum of 20 digits. + */ + AccountNumber: string; + } + + type OtherData = BaseData & OtherDetails; + + type Data = OtherData | CAData | GBData | IBANData | USData; + type DataIntersection = OtherData & CAData & GBData & IBANData & USData; + type CreationDetails = + | OtherDetails + | CADetails + | GBDetails + | IBANDetails + | USDetails; + } + + namespace transaction { + type TransactionNature = + | "REGULAR" + | "REPUDIATION" + | "REFUND" + | "SETTLEMENT"; + type TransactionType = "PAYIN" | "TRANSFER" | "PAYOUT"; + type TransactionStatus = "CREATED" | "SUCCEEDED" | "FAILED"; + + interface TransactionData extends entityBase.EntityBaseData { + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Details about the funds that are being credited (DebitedFunds – Fees = CreditedFunds) + */ + CreditedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * The ID of the wallet that was debited + */ + DebitedWalletId: string; + + /** + * The ID of the wallet where money will be credited + */ + CreditedWalletId: string; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId: string; + + /** + * The nature of the transaction + */ + Nature: TransactionNature; + + /** + * The status of the transaction + */ + Status: TransactionStatus; + + /** + * When the transaction happened + */ + ExecutionDate: Timestamp; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + + /** + * The type of the transaction + */ + Type: TransactionType; + } + } + + namespace wallet { + type ClientFundsType = "FEES" | "CREDIT"; + type FundsType = "DEFAULT" | ClientFundsType; + + interface WalletData extends entityBase.EntityBaseData { + /** + * An array of userIDs of who own's the wallet. For now, you only can set up a unique owner. + */ + Owners: [string]; + + /** + * The current balance of the wallet + */ + Balance: MoneyData; + + /** + * The type of funds in the wallet + */ + FundsType: FundsType; + + /** + * A desciption of the wallet + */ + Description: string; + + /** + * The currency - should be ISO_4217 format + */ + Currency: CurrencyISO; + } + + interface ClientWalletData + extends Omit { + FundsType: ClientFundsType; + } + + type CreateWallet = UpdateWallet & + Pick; + type UpdateWallet = PickPartial; + } + + namespace disputeDocument { + type DisputeDocumentType = + | "DELIVERY_PROOF" + | "INVOICE" + | "REFUND_PROOF" + | "USER_CORRESPONDANCE" + | "USER_ACCEPTANCE_PROOF" + | "PRODUCT_REPLACEMENT_PROOF" + | "OTHER"; + + type DocumentStatus = + | "CREATED" + | "VALIDATION_ASKED" + | "VALIDATED" + | "REFUSED"; + + type RefusedReasonType = + | "DOCUMENT_UNREADABLE" + | "DOCUMENT_NOT_ACCEPTED" + | "DOCUMENT_HAS_EXPIRED" + | "DOCUMENT_INCOMPLETE" + | "DOCUMENT_MISSING" + | "SPECIFIC_CASE" + | "DOCUMENT_FALSIFIED" + | "OTHER"; + + interface DisputeDocumentData extends entityBase.EntityBaseData { + /** + * Gives the type of the KYC document + */ + Type: DisputeDocumentType; + + /** + * The object owner's UserId + */ + UserId: string; + + /** + * The Id of a Dispute + */ + DisputeId: string; + + /** + * The status of this KYC/Dispute document + */ + Status: DocumentStatus; + + /** + * The message accompanying a refusal + */ + RefusedReasonMessage: string; + + /** + * The type of reason for refusal + */ + RefusedReasonType: RefusedReasonType; + + /** + * The date when the document was processed by MANGOPAY + */ + ProcessedDate: Timestamp; + } + + interface CreateDisputeDocument { + /** + * Gives the type of the KYC document + */ + Type: DisputeDocumentType; + Tag?: string; + } + + interface SubmitDisputeDocument { + /** + * The status of this KYC/Dispute document + */ + Status: "VALIDATION_ASKED"; + Tag?: string; + } + + /** + * - Documents have to be in "CREATED" Status + * - You can create as many pages as needed + * + * Remember to change Status to "VALIDATION_ASKED" to submit KYC documents + * The maximum size per page is about 7Mb (or 10Mb when base64encoded). The following formats are accepted for the documents : .pdf, .jpeg, .jpg, .gif and .png. The minimum size is 1Kb. + */ + interface CreateDisputeDocumentPage { + /** + * The base64 encoded file which needs to be uploaded + * + * You need to fill in only the binary code. Do not send the first part that some converters add into the binary code which is + * `` + * + * e.g. + * ```json + * { + * "File": "/9j/4AAQSkZJRgABAQEBLAEsAAD/.../wgARCAAyADIDAREAAhEBAxEB/8QAGwAAAgMBAQEA" + * } + * ``` + */ + File: string; + } + + interface DocumentPageConsult { + /** + * URL where this document page can be viewed. + */ + Url: string; + + /** + * Time in millis when the page consult will expire. + */ + ExpirationDate: Timestamp; + } + } + + namespace kycDocument { + type KycDocumentType = + | "IDENTITY_PROOF" + | "REGISTRATION_PROOF" + | "ARTICLES_OF_ASSOCIATION" + | "SHAREHOLDER_DECLARATION" + | "ADDRESS_PROOF"; + type DocumentStatus = + | "CREATED" + | "VALIDATION_ASKED" + | "VALIDATED" + | "REFUSED"; + + type KYCDocumentRefusedReasonType = + | "DOCUMENT_UNREADABLE" + | "DOCUMENT_NOT_ACCEPTED" + | "DOCUMENT_HAS_EXPIRED" + | "DOCUMENT_INCOMPLETE" + | "DOCUMENT_MISSING" + | "DOCUMENT_DO_NOT_MATCH_USER_DATA" + | "DOCUMENT_DO_NOT_MATCH_ACCOUNT_DATA" + | "SPECIFIC_CASE" + | "DOCUMENT_FALSIFIED" + | "UNDERAGE_PERSON" + | "SPECIFIC_CASE"; + + interface KycDocumentData extends entityBase.EntityBaseData { + /** + * Gives the type of the KYC document + */ + Type: KycDocumentType; + + /** + * The object owner's UserId + */ + UserId: string; + + /** + * The status of this KYC/Dispute document + */ + Status: DocumentStatus; + + /** + * The message accompanying a refusal + */ + RefusedReasonMessage: string; + + /** + * The type of reason for refusal + */ + RefusedReasonType: KYCDocumentRefusedReasonType; + + /** + * The date when the document was processed by MANGOPAY + */ + ProcessedDate: Timestamp; + } + + interface CreateKycDocument { + /** + * Gives the type of the KYC document + */ + Type: KycDocumentType; + Tag?: string; + } + + interface CreateKycDocument { + /** + * Gives the type of the KYC document + */ + Type: KycDocumentType; + Tag?: string; + } + + interface SubmitKycDocument { + /** + * The status of this KYC/Dispute document + */ + Status: "VALIDATION_ASKED"; + Tag?: string; + } + + /** + * - Documents have to be in "CREATED" Status + * - You can create as many pages as needed + * + * Remember to change Status to "VALIDATION_ASKED" to submit KYC documents + * The maximum size per page is about 7Mb (or 10Mb when base64encoded). The following formats are accepted for the documents : .pdf, .jpeg, .jpg, .gif and .png. The minimum size is 1Kb. + */ + interface CreateKycPage { + /** + * The base64 encoded file which needs to be uploaded + * + * You need to fill in only the binary code. Do not send the first part that some converters add into the binary code which is + * `` + * + * e.g. + * ```json + * { + * "File": "/9j/4AAQSkZJRgABAQEBLAEsAAD/.../wgARCAAyADIDAREAAhEBAxEB/8QAGwAAAgMBAQEA" + * } + * ``` + */ + File: string; + } + } + + namespace eMoney { + interface EMoneyData extends entityBase.EntityBaseData { + /** + * The object owner's UserId + */ + UserId: string; + + /** + * The amount of money that has been credited to this user + */ + CreditedEMoney: MoneyData; + + /** + * The amount of money that has been debited from this user + */ + DebitedEMoney: MoneyData; + } + } + + namespace uboDeclaration { + interface UboDeclarationData extends entityBase.EntityBaseData { + /** + * The object owner's UserId + */ + UserId: string; + + /** + * Status of a UBO Declaration + */ + Status: kycDocument.DocumentStatus; + + /** + * Reason types for a UBO Declaration + */ + RefusedReasonTypes: string[]; + + /** + * Refused Reason Message for a UBO Declaration + */ + RefusedReasonMessage: string; + + /** + * An array of UserIDs declared as Ultimate Beneficial Owners of a BUSINESS Legal User. + */ + DeclaredUBOs: string[]; + } + + interface CreateUboDeclaration { + DeclaredUBOs?: string[]; + } + + interface UpdateUboDeclaration { + Id: string; + Tag?: string; + Status?: "VALIDATION_ASKED"; + + /** + * An array of UserIDs declared as Ultimate Beneficial Owners of a BUSINESS Legal User. + */ + DeclaredUBOs?: string[]; + } + } + + namespace cardRegistration { + interface CardRegistrationData extends entityBase.EntityBaseData { + /** + * The object owner's UserId + */ + UserId: string; + /** + * The currency - should be ISO_4217 format + */ + Currency: CurrencyISO; + + /** + * A special key to use when registering a card + */ + AccessKey: string; + + /** + * A specific value to pass to the CardRegistrationURL + */ + PreregistrationData: string; + + /** + * The URL to submit the card details form to + */ + CardRegistrationURL: string; + + /** + * Having registered a card, this confirmation hash needs to be updated to the card item + */ + RegistrationData: string; + + /** + * The type of card + */ + CardType: card.CardType; + + /** + * The ID of a card + */ + CardId: string; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + + /** + * Status of the card registration + */ + Status: card.CardStatus; + } + + interface CreateCardRegistration + extends PickPartialRequired< + CardRegistrationData, + "CardType" | "Tag", + "UserId" | "Currency" + > {} + type UpdateCardRegistration = PickPartial< + CardRegistrationData, + "Tag" | "RegistrationData" + >; + } + + namespace card { + type CardType = + | "CB_VISA_MASTERCARD" + | "DINERS" + | "MASTERPASS" + | "MAESTRO" + | "P24" + | "IDEAL" + | "BCMC" + | "PAYLIB"; + type CardStatus = "CREATED" | "VALIDATED" | "ERROR"; + type CardValidity = "UNKNOWN" | "VALID" | "INVALID"; + + interface CardData extends entityBase.EntityBaseData { + /** + * The expiry date of the card - must be in format MMYY + */ + ExpirationDate: string; + + /** + * A partially obfuscated version of the credit card number + */ + Alias: string; + + /** + * The provider of the card + */ + CardProvider: string; + + /** + * The type of card + */ + CardType: CardType; + + /** + * The Country of the Address + */ + Country: string; + + /** + * The card product type - more info + */ + Product: string; + + /** + * The bank code + */ + BankCode: string; + + /** + * Whether the card is active or not + */ + Active: boolean; + + /** + * The currency - should be ISO_4217 format + */ + Currency: CurrencyISO; + + /** + * Whether the card is valid or not. Once they process (or attempt to process) a payment with the card we are able to indicate if it is "valid" or "invalid". + * If they didn’t process a payment yet the "Validity" stay at "unknown". + */ + Validity: CardValidity; + + /** + * A unique representation of a 16-digits card number + */ + Fingerprint: string; + } + + interface UpdateCard { + Id: string; + Active?: false; + } + } + + namespace cardPreAuthorization { + interface CardPreAuthorizationData extends entityBase.EntityBaseData { + /** + * A user's ID + */ + AuthorId: string; + + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Status of the PreAuthorization + */ + Status: PreAuthorizationStatus; + + /** + * The status of the payment after the PreAuthorization. You can pass the PaymentStatus from "WAITING" to "CANCELED" should you need/want to + */ + PaymentStatus: PaymentStatus; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + + /** + * How the PreAuthorization has been executed + */ + ExecutionType: PreAuthorizationExecutionType; + + /** + * The SecureMode corresponds to '3D secure' for CB Visa and MasterCard. This field lets you activate it manually. + * The field lets you activate it automatically with "DEFAULT" (Secured Mode will be activated from €50 or when MANGOPAY detects there is a higher risk ), + * "FORCE" (if you wish to specifically force the secured mode). + */ + SecureMode: SecureMode; + + /** + * The ID of a card + */ + CardId: string; + + /** + * The value is 'true' if the SecureMode was used + */ + SecureModeNeeded: boolean; + + /** + * This is the URL where to redirect users to proceed to 3D secure validation + */ + SecureModeRedirectUrl: string; + + /** + * This is the URL where users are automatically redirected after 3D secure validation (if activated) + */ + SecureModeReturnURL: string; + + /** + * The date when the payment is to be processed by + */ + ExpirationDate: Timestamp; + + /** + * The Id of the associated PayIn + */ + PayInId: string; + + /** + * Contains useful information related to the user billing + */ + Billing: BillingData; + + /** + * Contains useful information related to security and fraud + */ + SecurityInfo: SecurityInfoData; + } + + type CreateCardPreAuthorization = PickPartialRequired< + CardPreAuthorizationData, + "Tag" | "Billing" | "SecureMode", + "AuthorId" | "DebitedFunds" | "CardId" | "SecureModeReturnURL" + >; + type UpdateCardPreAuthorization = PickPartialRequired< + CardPreAuthorizationData, + "Tag", + "PaymentStatus" | "Id" + >; + } + + namespace hook { + type HookValidity = "UNKNOWN" | "VALID" | "INVALID"; + type HookStatus = "DISABLED" | "ENABLED"; + + interface HookData extends entityBase.EntityBaseData { + /** + * This is the URL where your receive notification for each EventType + */ + Url: string; + + /** + * Whether the hook is enabled or not + */ + Status: HookStatus; + + /** + * Whether the hook is valid or not + */ + Validity: HookValidity; + + /** + * The event type + */ + EventType: event.EventType; + } + + interface CreateHook + extends PickPartialRequired {} + + interface UpdateHook + extends PickPartialRequired< + HookData, + "EventType" | "Url" | "Tag", + "Id" + > {} + } + + namespace report { + interface Filters { + /** + * To return only resources that have CreationDate BEFORE this date + */ + BeforeDate: Timestamp; + + /** + * To return only resources that have CreationDate AFTER this date + */ + AfterDate: Timestamp; + + /** + * The type of the transaction + */ + Type: transaction.TransactionType[]; + + /** + * The status of the transaction + */ + Status: transaction.TransactionStatus[]; + + /** + * The nature of the transaction + */ + Nature: transaction.TransactionNature[]; + + /** + * The minimum amount of DebitedFunds + */ + MinDebitedFundsAmount: number; + + /** + * The currency for the minimum amount of DebitedFunds + */ + MinDebitedFundsCurrency: CurrencyISO; + + /** + * The maximum amount of DebitedFunds + */ + MaxDebitedFundsAmount: number; + + /** + * The currency for the maximum amount of DebitedFunds + */ + MaxDebitedFundsCurrency: CurrencyISO; + + /** + * The minimum amount of Fees + */ + MinFeesAmount: number; + + /** + * The currency for the minimum amount of Fees + */ + MinFeesCurrency: CurrencyISO; + + /** + * The maximum amount of Fees + */ + MaxFeesAmount: number; + + /** + * The currency for the maximum amount of Fees + */ + MaxFeesCurrency: CurrencyISO; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The ID of a wallet + */ + WalletId: string; + } + + type Column = + | "Alias" + | "AuthorId" + | "BankAccountId" + | "BankWireRef" + | "CardId" + | "CardType" + | "Country" + | "CreationDate" + | "CreditedFundsAmount" + | "CreditedFundsCurrency" + | "CreditedUserId" + | "CreditedWalletId" + | "Culture" + | "DebitedFundsAmount" + | "DebitedFundsCurrency" + | "DebitedWalletId" + | "DeclaredDebitedFundsAmount" + | "DeclaredDebitedFundsCurrency" + | "DeclaredFeesAmount" + | "DeclaredFeesCurrency" + | "ExecutionDate" + | "ExecutionType" + | "ExpirationDate" + | "FeesAmount" + | "FeesCurrency" + | "Id" + | "Nature" + | "PaymentType" + | "PreauthorizationId" + | "ResultCode" + | "ResultMessage" + | "Status" + | "Tag" + | "Type" + | "WireReference"; + + interface ReportData extends entityBase.EntityBaseData { + /** + * The date when the report was executed + */ + ReportDate: Timestamp; + + /** + * The URL to download the report + */ + DownloadURL: string; + + /** + * A URL that we will ping when the report is ready to download(works in a similar way to the hooks) + */ + CallbackURL: string; + + /** + * The format of the report download + */ + DownloadFormat: "CSV"; + + /** + * The type of report + */ + ReportType: "TRANSACTIONS"; + + /** + * The column to sort against and direction seperate by a `:` + */ + Sort: string; + + /** + * Whether the report should be limited to the first 10 lines(and therefore quicker to execute) + */ + Preview: boolean; + + /** + * An object of various filters for the report + */ + Filters: Filters; + + /** + * A list of columns / infos to show in the report + */ + Columns: Column[]; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + } + + interface CreateReport + extends PickPartial< + ReportData, + | "Tag" + | "CallbackURL" + | "DownloadFormat" + | "Sort" + | "Preview" + | "Filters" + | "Columns" + > {} + } + + namespace mandate { + /** + * - "CREATED" - the mandate has been created + * - "SUBMITTED" - the mandate has been submitted to the banks and you can now do payments with this mandate + * - "ACTIVE" - the mandate is active and has been accepted by the banks and/or successfully used in a payment + * - "FAILED" - the mandate has failed for a variety of reasons and is no longer available for payments + */ + type MandateStatus = ValueOf; + type MandateScheme = "SEPA" | "BACS"; + type MandateCultureCode = "EN" | "FR" | "NL" | "DE" | "ES" | "IT" | "PL"; + type MandateExecutionType = "WEB"; + type MandateType = "DIRECT_DEBIT"; + interface MandateData extends entityBase.EntityBaseData { + /** + * An ID of a Bank Account + */ + BankAccountId: string; + + /** + * The object owner's UserId + */ + UserId: string; + + /** + * The URL to redirect to after payment (whether successful or not) + */ + ReturnURL: string; + + /** + * The URL to redirect to user to for them to proceed with the payment + */ + RedirectURL: string; + + /** + * The URL to download the mandate + */ + DocumentURL: string; + + /** + * The language to use for the mandate confirmation page - needs to be the ISO code of the language + */ + Culture: MandateCultureCode; + + /** + * The type of mandate, but will only be completed once the mandate has been submitted + */ + Scheme: MandateScheme; + + /** + * The status of the mandate: + */ + Status: MandateStatus; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + + /** + * The execution type for creating the mandate + */ + ExecutionType: MandateExecutionType; + + /** + * The type of Mandate + */ + MandateType: MandateType; + + /** + * The banking reference for this mandate + */ + BankReference: string; + } + + interface CreateMandate + extends PickPartialRequired< + MandateData, + "Tag", + "BankAccountId" | "Culture" | "ReturnURL" + > {} + } + + namespace user { + /** + * Should be only one of these values: + * 1 - for incomes <18K€), + * 2 - for incomes between 18 and 30K€, + * 3 - for incomes between 30 and 50K€, + * 4 - for incomes between 50 and 80K€, + * 5 - for incomes between 80 and 120K€, + * 6 - for incomes >120K€ + */ + type IncomeRange = 1 | 2 | 3 | 4 | 5 | 6; + type PersonType = "NATURAL" | "LEGAL"; + type KYCLevel = "LIGHT" | "REGULAR"; + type LegalPersonType = "BUSINESS" | "ORGANIZATION" | "SOLETRADER"; + type StaticKeys = + | "KYCLevel" + | "PersonType" + | "Id" + | "CreationDate" + | "ProofOfIdentity" + | "ProofOfAddress" + | "ProofOfRegistration" + | "LegalRepresentativeProofOfIdentity" + | "ShareholderDeclaration" + | "Statute"; + interface UserData extends entityBase.EntityBaseData { + /** + * Type of user + */ + PersonType: PersonType; + + /** + * The person's email address (not more than 12 consecutive numbers) - must be a valid email + */ + Email: string; + + /** + * KYC Level (LIGHT or REGULAR) + */ + KYCLevel: KYCLevel; + } + + interface UserLegalData extends UserData { + PersonType: "LEGAL"; + + /** + * The name of the legal user + */ + Name: string; + + /** + * Type for legal user. + */ + LegalPersonType: LegalPersonType; + + /** + * The address of the company’s headquarters + */ + HeadquartersAddress: address.AddressType; + + /** + * The first name of the company’s Legal representative person + */ + LegalRepresentativeFirstName: string; + + /** + * The last name of the company’s Legal representative person + */ + LegalRepresentativeLastName: string; + + /** + * The address of the company’s Legal representative person + */ + LegalRepresentativeAddress: address.AddressType; + + /** + * The email of the company’s Legal representative person - must be valid + */ + LegalRepresentativeEmail: string; + + /** + * The date of birth of the company’s Legal representative person - be careful to set the right timezone (should be UTC) to avoid 00h becoming 23h (and hence interpreted as the day before) + */ + LegalRepresentativeBirthday: Timestamp; + + /** + * The nationality of the company’s Legal representative person + */ + LegalRepresentativeNationality: CountryISO; + + /** + * The country of residence of the company’s Legal representative person + */ + LegalRepresentativeCountryOfResidence: CountryISO; + ProofOfIdentity: string | null; + + /** + * The business statute of the company + */ + Statute: string | null; + + /** + * A MANGOPAY reference to the validated document of the proof of registration of the company + */ + ProofOfRegistration: string | null; + + /** + * The shareholder declaration of the company + */ + ShareholderDeclaration: string | null; + + /** + * The official registered number of the business + */ + CompanyNumber: string; + } + + interface UserNaturalData extends UserData { + PersonType: "NATURAL"; + + /** + * The name of the user + */ + FirstName: string; + + /** + * The last name of the user + */ + LastName: string; + + /** + * The user address + */ + Address: string | address.AddressData; + + /** + * The date of birth of the user - be careful to set the right timezone (should be UTC) to avoid 00h becoming 23h (and hence interpreted as the day before) + */ + Birthday: Timestamp; + + /** + * The user’s nationality. ISO 3166-1 alpha-2 format is expected + */ + Nationality: CountryISO; + + /** + * The user’s country of residence. ISO 3166-1 alpha-2 format is expected + */ + CountryOfResidence: CountryISO; + + /** + * User’s occupation, ie. Work + */ + Occupation: string; + IncomeRange: IncomeRange; + + /** + * Maximum length is 255 characters + */ + ProofOfIdentity: string | null; + + /** + * Maximum length is 255 characters + */ + ProofOfAddress: string | null; + + /** + * The capacity of this user - for use with UBO declarations + */ + Capacity: "NORMAL" | "DECLARATIVE"; + } + + type RequiredUserLegalData = + | "LegalPersonType" + | "Name" + | "LegalRepresentativeBirthday" + | "LegalRepresentativeCountryOfResidence" + | "LegalRepresentativeNationality" + | "LegalRepresentativeFirstName" + | "LegalRepresentativeLastName" + | "Email"; + + type RequiredUserNaturalData = + | "FirstName" + | "LastName" + | "Birthday" + | "Nationality" + | "CountryOfResidence" + | "Email"; + + interface BaseUserLegalData + extends PickPartial< + UserLegalData, + | RequiredUserLegalData + | "CompanyNumber" + | "LegalRepresentativeEmail" + | "LegalRepresentativeAddress" + | "HeadquartersAddress" + | "Tag" + > { + PersonType: "LEGAL"; + } + + interface UpdateUserLegalData extends BaseUserLegalData { + Id: string; + } + + interface CreateUserLegalData + extends MakeKeysRequired< + BaseUserLegalData, + RequiredUserLegalData | "PersonType" + > {} + + interface BaseUserNaturalData + extends PickPartial< + UserNaturalData, + | RequiredUserNaturalData + | "Address" + | "Occupation" + | "IncomeRange" + | "Tag" + > { + PersonType: "NATURAL"; + } + + interface UpdateUserNaturalData extends BaseUserNaturalData { + Id: string; + } + + interface CreateUserNaturalData + extends MakeKeysRequired< + BaseUserNaturalData, + RequiredUserNaturalData | "PersonType" + > {} + } + + namespace payIn { + type PayInPaymentType = ValueOf; + type PayInExecutionType = + | ValueOf + | "EXTERNAL_INSTRUCTION"; + + interface TemplateURLOptions { + Payline: string; + } + + interface BasePayInData extends entityBase.EntityBaseData { + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Details about the funds that are being credited (DebitedFunds – Fees = CreditedFunds) + */ + CreditedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * The ID of the wallet that was debited + */ + DebitedWalletId: string; + + /** + * The ID of the wallet where money will be credited + */ + CreditedWalletId: string; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId: string; + + /** + * The nature of the transaction + */ + Nature: transaction.TransactionNature; + + /** + * The status of the transaction + */ + Status: transaction.TransactionStatus; + + /** + * When the transaction happened + */ + ExecutionDate: Timestamp; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + + /** + * The type of the transaction + */ + Type: transaction.TransactionType; + + /** + * The type of payin + */ + PaymentType: PayInPaymentType; + + /** + * The type of execution for the payin + */ + ExecutionType: PayInExecutionType; + } + + interface CardWebPayInData extends BasePayInData { + ExecutionType: "WEB"; + PaymentType: "CARD"; + + /** + * The URL to redirect to after payment (whether successful or not) + */ + ReturnURL: string; + + /** + * The type of card + */ + CardType: card.CardType; + + /** + * The SecureMode corresponds to '3D secure' for CB Visa and MasterCard. This field lets you activate it manually. The field lets you activate it + * automatically with "DEFAULT" (Secured Mode will be activated from €50 or when MANGOPAY detects there is a higher risk ), "FORCE" (if you wish to specifically force the secured mode). + */ + SecureMode: SecureMode; + + /** + * The language to use for the payment page - needs to be the ISO code of the language + */ + Culture: CountryISO; + + /** + * The URL to use for the payment page template + */ + TemplateURL: string; + + /** + * A custom description to appear on the user's bank statement. It can be up to 10 characters long, and can only include alphanumeric characters or spaces. + * See here for important info. Note that each bank handles this information differently, some show less or no information. + */ + StatementDescriptor: string; + + /** + * The URL to redirect to user to for them to proceed with the payment + */ + RedirectURL: string; + } + + interface CreateCardWebPayIn { + ExecutionType: "WEB"; + PaymentType: "CARD"; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId?: string; + + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * The URL to redirect to after payment (whether successful or not) + */ + ReturnURL: string; + + /** + * The ID of the wallet where money will be credited + */ + CreditedWalletId: string; + + /** + * The type of card + */ + CardType: card.CardType; + + /** + * The SecureMode corresponds to '3D secure' for CB Visa and MasterCard. This field lets you activate it manually. + * The field lets you activate it automatically with "DEFAULT" (Secured Mode will be activated from €50 or when MANGOPAY detects + * there is a higher risk ), "FORCE" (if you wish to specifically force the secured mode). + */ + SecureMode?: SecureMode; + + /** + * The language to use for the payment page - needs to be the ISO code of the language + */ + Culture: CountryISO; + + /** + * A URL to an SSL page to allow you to customise the payment page. Must be in the format: array("PAYLINE"=>"https://...") and meet all the + * specifications listed here. Note that only a template for Payline is currently available + */ + TemplateURLOptions?: TemplateURLOptions; + + /** + * A custom description to appear on the user's bank statement. It can be up to 10 characters long, and + * can only include alphanumeric characters or spaces. See here for important info. Note that each bank handles this information differently, some show less or no information. + */ + StatementDescriptor?: string; + } + + interface CardDirectPayInData extends BasePayInData { + ExecutionType: "DIRECT"; + PaymentType: "CARD"; + + /** + * This is the URL where users are automatically redirected after 3D secure validation (if activated) + */ + SecureModeReturnURL: string; + + /** + * The ID of a card + */ + CardId: string; + + /** + * The SecureMode corresponds to '3D secure' for CB Visa and MasterCard. This field lets you activate it manually. The field lets you activate it + * automatically with "DEFAULT" (Secured Mode will be activated from €50 or when MANGOPAY detects there is a higher risk ), "FORCE" (if you wish to specifically force the secured mode). + */ + SecureMode: SecureMode; + + /** + * A custom description to appear on the user's bank statement. It can be up to 10 characters long, and can only include alphanumeric + * characters or spaces. See here for important info. Note that each bank handles this information differently, some show less or no information. + */ + StatementDescriptor: string; + + /** + * Contains useful information related to the user billing + */ + Billing: BillingData; + + /** + * Contains information related to security and fraud + */ + SecurityInfo: SecurityInfoData; + + /** + * The value is 'true' if the SecureMode was used + */ + SecureModeNeeded: boolean; + + /** + * This is the URL where to redirect users to proceed to 3D secure validation + */ + SecureModeRedirectUrl: string; + } + + interface CreateCardDirectPayIn { + ExecutionType: "DIRECT"; + PaymentType: "CARD"; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId?: string; + + /** + * The ID of the wallet where money will be credited + */ + CreditedWalletId: string; + + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * This is the URL where users are automatically redirected after 3D secure validation (if activated) + */ + SecureModeReturnURL: string; + + /** + * The ID of a card + */ + CardId: string; + + /** + * The SecureMode corresponds to '3D secure' for CB Visa and MasterCard. This field lets you activate it manually. The field lets you activate it automatically + * with "DEFAULT" (Secured Mode will be activated from €50 or when MANGOPAY detects there is a higher risk ), "FORCE" (if you wish to specifically force the secured mode). + */ + SecureMode?: SecureMode; + + /** + * Contains useful information related to the user billing + */ + Billing?: BillingData; + + /** + * A custom description to appear on the user's bank statement. It can be up to 10 characters long, and can only include alphanumeric characters or spaces. + * See here for important info. Note that each bank handles this information differently, some show less or no information. + */ + StatementDescriptor?: string; + } + + interface CardPreAuthorizedPayInData extends BasePayInData { + PreauthorizationId: string; + ExecutionType: "DIRECT"; + PaymentType: "PREAUTHORIZED"; + } + + interface CreateCardPreAuthorizedPayIn { + ExecutionType: "DIRECT"; + PaymentType: "PREAUTHORIZED"; + + /** + * Custom data that you can add to this item + */ + Tag?: string; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId?: string; + + /** + * The ID of the wallet where money will be credited + */ + CreditedWalletId: string; + + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * The ID of the Preauthorization object + */ + PreauthorizationId: string; + } + + interface BankAccountData { + /** + * The BIC of the bank account + */ + BIC: string; + + /** + * The IBAN of the bank account + */ + IBAN: string; + + /** + * The name of the owner of the bank account + */ + OwnerName: string; + + /** + * The address of the owner of the bank account + */ + OwnerAddress: string; + + /** + * The type of bank account + */ + Type: ValueOf; + } + + interface BankWireDirectPayInData extends BasePayInData { + ExecutionType: "DIRECT"; + PaymentType: "BANK_WIRE"; + + /** + * The declared debited funds + */ + DeclaredDebitedFunds: MoneyData; + + /** + * The declared fees + */ + DeclaredFees: MoneyData; + + /** + * Wire reference + */ + WireReference: string; + + /** + * Bank account details + */ + BankAccount: BankAccountData; + } + + interface CreateBankWireDirectPayIn + extends PickPartialRequired< + BankWireDirectPayInData, + "Tag", + | "AuthorId" + | "CreditedUserId" + | "CreditedWalletId" + | "DeclaredDebitedFunds" + | "DeclaredFees" + > { + ExecutionType: "DIRECT"; + PaymentType: "BANK_WIRE"; + } + + type PayInData = + | CardDirectPayInData + | CardPreAuthorizedPayInData + | CardWebPayInData + | BankWireDirectPayInData; + } + + namespace refund { + type RefundReasonType = + | "INITIALIZED_BY_CLIENT" + | "BANKACCOUNT_INCORRECT" + | "OWNER_DO_NOT_MATCH_BANKACCOUNT" + | "BANKACCOUNT_HAS_BEEN_CLOSED" + | "WITHDRAWAL_IMPOSSIBLE_ON_SAVINGS_ACCOUNTS" + | "OTHER"; + interface RefundReason { + RefundReasonType: RefundReasonType; + } + + interface RefundData extends transaction.TransactionData { + /** + * The nature of the transaction + */ + Nature: "REFUND"; + + /** + * The initial transaction ID + */ + InitialTransactionId: string; + + /** + * The initial transaction type + */ + InitialTransactionType: transaction.TransactionType; + + /** + * Contains info about the reason for refund + */ + RefundReason: RefundReason; + } + + interface CreatePayInRefund { + AuthorId: string; + Tag?: string; + DebitedFunds?: MoneyData; + Fees?: MoneyData; + } + + interface CreateTransferRefund { + AuthorId: string; + Tag?: string; + } + } + + namespace repudiation { + interface RepudiationData extends transaction.TransactionData { + /** + * The nature of the transaction + */ + Nature: "REPUDIATION"; + + /** + * The initial transaction ID + */ + InitialTransactionId: string; + + /** + * The initial transaction type + */ + InitialTransactionType: transaction.TransactionType; + + /** + * Contains info about the reason for refund + */ + RefundReason: refund.RefundReason; + } + } + + namespace client { + type BusinessType = "MARKETPLACE" | "CROWDFUNDING" | "FRANCHISE" | "OTHER"; + type Sector = + | "RENTALS" + | "STORES_FASHION_ACCESSORIES_OBJECTS" + | "BEAUTY_COSMETICS_HEALTH" + | "FOOD_WINE_RESTAURANTS" + | "HOSPITALITY_TRAVEL_CORIDING" + | "ART_MUSIC_ENTERTAINMENT" + | "FURNITURE_GARDEN" + | "SERVICES_JOBBING_EDUCATION" + | "SPORT_RECREATION_ACTIVITIES" + | "TICKETING"; + type PlatformType = ValueOf; + + interface PlatformCategorization { + Sector: Sector; + BusinessType: BusinessType; + } + + interface ClientData extends entityBase.EntityBaseData { + /** + * The pretty name for the client + */ + Name: string; + + /** + * The registered name of your company + */ + RegisteredName: string; + + /** + * An ID for the client (i.e. url friendly, lowercase etc - sort of namespace identifier) + */ + ClientId: string; + + /** + * The primary branding colour to use for your merchant + */ + PrimaryThemeColour: string; + + /** + * The primary branding colour to use for buttons for your merchant + */ + PrimaryButtonColour: string; + + /** + * The URL of the logo of your client + */ + Logo: string; + + /** + * A list of email addresses to use when contacting you for technical issues/communications + */ + TechEmails: string[]; + + /** + * A list of email addresses to use when contacting you for admin/commercial issues/communications + */ + AdminEmails: string[]; + + /** + * A list of email addresses to use when contacting you for fraud/compliance issues/communications + */ + FraudEmails: string[]; + + /** + * A list of email addresses to use when contacting you for billing issues/communications + */ + BillingEmails: string[]; + + /** + * The Categorization of your platform, in terms of Business Type and Sector + */ + PlatformCategorization: PlatformCategorization; + + /** + * A description of what your platform does + */ + PlatformDescription: string; + + /** + * The URL for your website + */ + PlatformURL: string; + + /** + * The address of the company’s headquarters + */ + HeadquartersAddress: address.AddressType; + + /** + * The tax (or VAT) number for your company + */ + TaxNumber: string; + + /** + * Your unique MANGOPAY reference which you should use when contacting us + */ + CompanyReference: string; + } + + interface UpdateClient { + /** + * The primary branding colour to use for buttons for your merchant + */ + PrimaryButtonColour?: string; + + /** + * The primary branding colour to use for your merchant + */ + PrimaryThemeColour?: string; + + /** + * A list of email addresses to use when contacting you for admin/commercial issues/communications + */ + AdminEmails?: string[]; + + /** + * A list of email addresses to use when contacting you for technical issues/communications + */ + TechEmails?: string[]; + + /** + * A list of email addresses to use when contacting you for billing issues/communications + */ + BillingEmails?: string[]; + + /** + * A list of email addresses to use when contacting you for fraud/compliance issues/communications + */ + FraudEmails?: string[]; + + /** + * The address of the company’s headquarters + */ + HeadquartersAddress?: address.AddressType; + + /** + * The tax (or VAT) number for your company + */ + TaxNumber?: string; + + /** + * The type of platform + */ + PlatformType?: PlatformType; + + /** + * A description of what your platform does + */ + PlatformDescription?: string; + + /** + * The URL for your website + */ + PlatformURL?: string; + } + + interface UpdateClientLogo { + /** + * The base64 encoded file which needs to be uploaded + */ + File: string; + } + } + + namespace event { + type EventType = + | "PAYIN_NORMAL_CREATED" + | "PAYIN_NORMAL_SUCCEEDED" + | "PAYIN_NORMAL_FAILED" + | "PAYOUT_NORMAL_CREATED" + | "PAYOUT_NORMAL_SUCCEEDED" + | "PAYOUT_NORMAL_FAILED" + | "TRANSFER_NORMAL_CREATED" + | "TRANSFER_NORMAL_SUCCEEDED" + | "TRANSFER_NORMAL_FAILED" + | "PAYIN_REFUND_CREATED" + | "PAYIN_REFUND_SUCCEEDED" + | "PAYIN_REFUND_FAILED" + | "PAYOUT_REFUND_CREATED" + | "PAYOUT_REFUND_SUCCEEDED" + | "PAYOUT_REFUND_FAILED" + | "TRANSFER_REFUND_CREATED" + | "TRANSFER_REFUND_SUCCEEDED" + | "TRANSFER_REFUND_FAILED" + | "KYC_CREATED" + | "KYC_VALIDATION_ASKED" + | "KYC_SUCCEEDED" + | "KYC_FAILED" + | "PAYIN_REPUDIATION_CREATED" + | "PAYIN_REPUDIATION_SUCCEEDED" + | "PAYIN_REPUDIATION_FAILED" + | "DISPUTE_DOCUMENT_CREATED" + | "DISPUTE_DOCUMENT_VALIDATION_ASKED" + | "DISPUTE_DOCUMENT_SUCCEEDED" + | "DISPUTE_DOCUMENT_FAILED" + | "DISPUTE_CREATED" + | "DISPUTE_SUBMITTED" + | "DISPUTE_ACTION_REQUIRED" + | "DISPUTE_FURTHER_ACTION_REQUIRED" + | "DISPUTE_CLOSED" + | "DISPUTE_SENT_TO_BANK" + | "TRANSFER_SETTLEMENT_CREATED" + | "TRANSFER_SETTLEMENT_SUCCEEDED" + | "TRANSFER_SETTLEMENT_FAILED" + | "MANDATE_CREATED" + | "MANDATE_FAILED" + | "MANDATE_ACTIVATED" + | "MANDATE_SUBMITTED" + | "PREAUTHORIZATION_PAYMENT_WAITING" + | "PREAUTHORIZATION_PAYMENT_EXPIRED" + | "PREAUTHORIZATION_PAYMENT_CANCELED" + | "PREAUTHORIZATION_PAYMENT_VALIDATED" + | "UBO_DECLARATION_CREATED" + | "UBO_DECLARATION_VALIDATION_ASKED" + | "UBO_DECLARATION_REFUSED" + | "UBO_DECLARATION_VALIDATED"; + + interface EventData { + /** + * The ID of whatever the event is + */ + ResourceId: string; + + /** + * When the event happened + */ + Date: Timestamp; + + /** + * The event type + */ + EventType: EventType; + } + } + + namespace dispute { + type DisputeReasonType = + | "DUPLICATE" + | "FRAUD" + | "PRODUCT_UNACCEPTABLE" + | "UNKNOWN" + | "OTHER" + | "REFUND_CONVERSION_RATE" + | "LATE_FAILURE_INSUFFICIENT_FUNDS" + | "LATE_FAILURE_CONTACT_USER" + | "LATE_FAILURE_BANKACCOUNT_CLOSED" + | "LATE_FAILURE_BANKACCOUNT_INCOMPATIBLE" + | "LATE_FAILURE_BANKACCOUNT_INCORRECT" + | "AUTHORISATION_DISPUTED" + | "TRANSACTION_NOT_RECOGNIZED" + | "PRODUCT_NOT_PROVIDED" + | "CANCELED_REOCCURING_TRANSACTION" + | "REFUND_NOT_PROCESSED"; + + type DisputeStatus = + | "CREATED" + | "PENDING_CLIENT_ACTION" + | "SUBMITTED" + | "PENDING_BANK_ACTION" + | "REOPENED_PENDING_CLIENT_ACTION" + | "CLOSED"; + + type DisputeType = "CONTESTABLE" | "NOT_CONTESTABLE" | "RETRIEVAL"; + + interface DisputeReason { + DisputeReasonType: DisputeReasonType; + DisputeReasonMessage: string; + } + + interface DisputeData extends entityBase.EntityBaseData { + /** + * The initial transaction ID + */ + InitialTransactionId: string; + + /** + * The initial transaction type + */ + InitialTransactionType: transaction.TransactionType; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + + /** + * Info about the reason for the dispute + */ + DisputeReason: DisputeReason; + + /** + * The status of the dispute + */ + Status: DisputeStatus; + + /** + * Used to communicate information about the dispute status to you + */ + StatusMessage: string; + + /** + * The amount of funds that were disputed + */ + DisputedFunds: MoneyData; + + /** + * The amount you wish to contest + */ + ContestedFunds: MoneyData; + + /** + * The type of dispute + */ + DisputeType: DisputeType; + + /** + * The deadline by which you must contest the dispute (if you wish to contest it) + */ + ContestDeadlineDate: Timestamp; + + /** + * The ID of the associated repudiation transaction + */ + RepudiationId: string; + } + + interface SubmitDispute + extends PickPartial {} + + interface UpdateDispute extends PickPartial {} + } + + interface DisputeReason extends dispute.DisputeReason {} + + namespace settlementTransfer { + interface SettlementTransferData extends transaction.TransactionData { + /** + * The nature of the transaction + */ + Nature: "SETTLEMENT"; + + /** + * The ID of the associated repudiation transaction + */ + RepudiationId: string; + + /** + * The initial transaction ID + */ + InitialTransactionId: string; + + /** + * The initial transaction type + */ + InitialTransactionType: transaction.TransactionType; + + /** + * Contains info about the reason for refund + */ + RefundReason: refund.RefundReason; + } + + interface CreateSettlementTransfer + extends PickPartialRequired< + SettlementTransferData, + "Tag", + "AuthorId" | "DebitedFunds" | "Fees" + > {} + } + + namespace transfer { + interface TransferData extends entityBase.EntityBaseData { + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Details about the funds that are being credited (DebitedFunds – Fees = CreditedFunds) + */ + CreditedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * The ID of the wallet that was debited + */ + DebitedWalletId: string; + + /** + * The ID of the wallet where money will be credited + */ + CreditedWalletId: string; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId: string; + + /** + * The nature of the transaction + */ + Nature: transaction.TransactionNature; + + /** + * The status of the transaction + */ + Status: transaction.TransactionStatus; + + /** + * When the transaction happened + */ + ExecutionDate: Timestamp; + + /** + * The result code + */ + ResultCode: string; + + /** + * A verbal explanation of the ResultCode + */ + ResultMessage: string; + + /** + * The type of the transaction + */ + Type: "TRANSFER"; + } + + interface CreateTransfer { + /** + * Custom data that you can add to this item + */ + Tag?: string; + + /** + * A user's ID + */ + AuthorId: string; + + /** + * The user ID who is credited (defaults to the owner of the wallet) + */ + CreditedUserId?: string; + + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * The ID of the wallet that was debited + */ + DebitedWalletId: string; + + /** + * The ID of the wallet where money will be credited + */ + CreditedWalletId: string; + } + } + + namespace PayOut { + interface PayOutData extends Omit { + /** + * The type of the transaction + */ + Type: "PAYOUT"; + + PaymentType: IPayOutPaymentType["BankWire"]; + + /** + * An ID of a Bank Account + */ + BankAccountId: string; + + /** + * A custom reference you wish to appear on the user’s bank statement (your Client Name is already shown). This reference can contain max 12 characters + */ + BankWireRef: string; + } + + interface CreatePayOut { + /** + * A user's ID + */ + AuthorId: string; + + /** + * Information about the funds that are being debited + */ + DebitedFunds: MoneyData; + + /** + * Information about the fees that were taken by the client for this transaction (and were hence transferred to the Client's platform wallet) + */ + Fees: MoneyData; + + /** + * An ID of a Bank Account + */ + BankAccountId: string; + + /** + * The ID of the wallet that was debited + */ + DebitedWalletId: string; + + /** + * A custom reference you wish to appear on the user’s bank statement (your Client Name is already shown). This reference can contain max 12 characters + */ + BankWireRef?: string; + Tag?: string; + } + } + + class Users { + /** + * Create a new user + * @param user + */ + create: MethodOverload & + MethodOverload; + + /** + * Update a user + * @param user + * @param options + */ + update: MethodOverload< + models.UserLegal | user.UpdateUserLegalData, + user.UserLegalData + > & + MethodOverload< + models.UserNatural | user.UpdateUserNaturalData, + user.UserNaturalData + >; + + /** + * Get natural or legal user by ID + * @param userId + * @param options + */ + get: MethodOverload; + + /** + * Get natural user by ID + * @param userId + * @param options + */ + getNatural: MethodOverload; + + /** + * Get legal user by ID + * @param userId + * @param options + */ + getLegal: MethodOverload; + + /** + * Get all users + */ + getAll: NoArgMethodOverload< + Array + >; + + /** + * Create bank account for user + * @param userId + * @param bankAccount + * @param options + */ + createBankAccount: TwoArgsMethodOverload< + string, + bankAccount.USDetails, + bankAccount.USData + > & + TwoArgsMethodOverload< + string, + bankAccount.OtherDetails, + bankAccount.OtherData + > & + TwoArgsMethodOverload< + string, + bankAccount.IBANDetails, + bankAccount.IBANData + > & + TwoArgsMethodOverload & + TwoArgsMethodOverload; + + /** + * Deactivate a bank account + * + * Note that once deactivated, a bank account can't be reactivated afterwards + * @param userId + * @param bankAccountId + * @param options + */ + deactivateBankAccount: TwoArgsMethodOverload; + + /** + * Get all bank accounts for user + * @param userId + * @param options + */ + getBankAccounts: MethodOverload; + + /** + * Get all bank accounts for user + * @param userId + * @param bankAccountId + * @param options + */ + getBankAccount: TwoArgsMethodOverload; + + /** + * Get all wallets accounts for user + */ + getWallets: MethodOverload; + + /** + * Get all transactions for user + * @param userId + * @param options + */ + getTransactions: MethodOverload; + + /** + * Get all cards for user + * @param userId + * @param options + */ + getCards: MethodOverload; + + /** + * Create new KYC document + * @param userId + * @param kycDocument + * @param options + */ + createKycDocument: TwoArgsMethodOverload< + string, + kycDocument.CreateKycDocument, + kycDocument.KycDocumentData + >; + + /** + * Get all KYC documents for user + * @param userId + * @param options + */ + getKycDocuments: MethodOverload; + + /** + * Get KYC document + * @param userId + * @param kycDocumentId + * @param options + */ + getKycDocument: TwoArgsMethodOverload< + string, + string, + kycDocument.KycDocumentData + >; + + /** + * Update status of KYC Document (Currently only allows for submitting the document) + * @param userId + * @param kycDocument + * @param options + */ + updateKycDocument: TwoArgsMethodOverload< + string, + kycDocument.SubmitKycDocument, + kycDocument.KycDocumentData + >; + + /** + * Create page for KYC document + * @param userId + * @param kycDocumentId + * @param kycPage + * @param options + */ + createKycPage: ThreeArgsMethodOverload< + string, + string, + kycDocument.CreateKycPage, + kycDocument.KycDocumentData + >; + + /** + * Create page for KYC document + * @param userId + * @param kycDocumentId + * @param filePath + * @param options + */ + createKycPageFromFile: ThreeArgsMethodOverload< + string, + string, + string, + kycDocument.KycDocumentData + >; + + /** + * Get users's EMoney + * @param userId + * @param options + */ + getEMoney: MethodOverload; + + /** + * Create an UboDeclaration for the user + * @param userId + * @param uboDeclaration + * @param options + */ + createUboDeclaration: TwoArgsMethodOverload< + string, + uboDeclaration.CreateUboDeclaration, + uboDeclaration.UboDeclarationData + >; + + /** + * Get all user preauthorizations + * @param userId + * @param options + */ + getPreAuthorizations: MethodOverload< + string, + cardPreAuthorization.CardPreAuthorizationData[] + >; + } + + /** + * You need to create document in order to upload pages on this document. + * + * 1. The KYC Document Object is a request to validate a required document. There is one request for one Type of document + * 2. Upload a file through a Page. A document should get several pages + * 3. Edit the object Document and set the Status field to "VALIDATION_ASKED" (instead of "CREATED") + * 4. The demand is received by our team. The object is waiting for a "VALIDATED" status + * + * Note that you are not allowed to store KYC documents on your side unless you have permission from the approriate authorities in your country + */ + class KycDocuments { + /** + * Get all KycDocuments + * @param options + */ + getAll: NoArgMethodOverload; + + /** + * Get KycDocument + * @param kycDocumentId + * @param options + */ + get: MethodOverload; + + /** + * Creates temporary URLs where each page of a KYC document can be viewed. + * @param documentId + */ + createKycDocumentConsult: MethodOverload< + string, + any // Unsure of data structure from docs + >; + } + + /** + * An UBO Declaration is an electronic version of the previous KYC document "Shareholder Declaration", in order to declare all the Ultimate Beneficial Owners of a BUSINESS-typed legal User + * (ie the shareholders with >25% of capital or voting rights). + * + * 1. Create each Ultimate Beneficial Owner as a Natural User, who must have a "DECLARATIVE" Capacity. + * 2. Create a new UBO Declaration for your legal user, and link every Ultimate Beneficial Owners created previously thanks to DeclaredUBOs. + * - This list can be empty if your legal user has no Ultimate Beneficial Owner, or no eligible one (ie. no Ultimate Beneficial Owner that owns more than 25% of this company). + * 3. Edit the UBODeclaration object and set the Status field to "VALIDATION_ASKED" (instead of "CREATED") + * 4. The demand is received by our team and once processed, it will either get a "VALIDATED" status, or "REFUSED" with more information provided in the RefusedReasonTypes parameter + * + * Note that UBO declarations are not yet a requirement for your user to be KYC verified and are optional at this stage + */ + class UboDeclarations { + /** + * Retrieves a UBO declaration object from the API. + * @param id + * @param options + */ + get: MethodOverload; + + /** + * Updates a UBO declaration entity. + * @param uboDeclaration Updated UBO declaration entity - must have ID + * @param options + */ + update: MethodOverload< + uboDeclaration.UpdateUboDeclaration, + uboDeclaration.UboDeclarationData + >; + } + + class BankAccounts { + /** + * Retrieve list of transactions for a bank account + * @param bankAccountId + * @param options + */ + getTransactions: MethodOverload; + } + + class Wallets { + /** + * Create new wallet + * @param wallet + * @param options + */ + create: MethodOverload< + wallet.CreateWallet | models.Wallet, + wallet.WalletData + >; + + /** + * Update wallet + * @param wallet + * @param options + */ + update: MethodOverload< + wallet.UpdateWallet | models.Wallet, + wallet.WalletData + >; + + /** + * Get a specific wallet + * @param walletId + */ + get: MethodOverload; + + /** + * Get transactions for the wallet + * @param walletId + * @param options + */ + getTransactions: MethodOverload; + } + + class Cards { + /** + * Get card + * @param cardId + * @param ptions + */ + get: MethodOverload; + + /** + * Gets a list of cards having the same fingerprint. + * The fingerprint is a hash uniquely generated per 16-digit card number. + * + * @param fingerprint The fingerprint hash + */ + getByFingerprint: MethodOverload; + + /** + * Update card (currently only supports deactivation) + * @param card + * @param options + */ + update: MethodOverload; + + /** + * Get list of Transactions of a Card + * @param cardId + * @param options + */ + getTransactions: MethodOverload; + + /** + * Gets list of PreAuthorizations of a Card. + * @param cardId + * @param options + */ + getPreAuthorizations: MethodOverload< + string, + cardPreAuthorization.CardPreAuthorizationData[] + >; + } + + /** + * You need to register a card in order to process a Direct PayIn. Card registration enables you to tokenize a Card. These are the steps to follow: + * + * 1. Create a CardRegistration Object + * 2. Get a PreRegistrationData + * 3. The user posts PreRegistrationData, AccessKey and card details through a form (PHP & JS samples) to the CardRegistrationURL (5. in the diagram) + * 4. Get a RegistrationData back + * 5. Edit the CardRegistration Object (POST method) with the RegistrationData just received + * 6. Get the CardId ready to use into the Direct PayIn Object + * + * - If you don’t want to save the card you must change the field ACTIVE in the card object to false + */ + class CardRegistrations { + /** + * Create new card registration + * @param cardRegistration + * @param options + */ + create: MethodOverload< + cardRegistration.CreateCardRegistration, + cardRegistration.CardRegistrationData + >; + + /** + * Create new card registration + * @param cardRegistrationId + * @param options + */ + get: MethodOverload; + + /** + * Update card registration + * @param cardRegistration + */ + update: MethodOverload< + cardRegistration.UpdateCardRegistration, + cardRegistration.CardRegistrationData + >; + } + + /** + * The PreAuthorization Object ensures the solvency of a registered card for 7 days. The overall process is as follows: + * + * 1. Register a card (CardRegistration) + * 2. Create a PreAuthorization with the CardId. This allows you to charge an amount on a card + * 3. Charge the card through the PreAuthorized PayIn object (Payins/preauthorized/direct) + * + * How does PreAuthorization work? + * - Once the PreAuthorization object is created the Status is "CREATED" until 3D secure validation. + * - If the authorization is successful the status is "SUCCEEDED" if it failed the status is "FAILED". + * - Once Status = "SUCCEEDED" and PaymentStatus = "WAITING" you can charge the card. + * - The Pay-In amount has to be less than or equal to the amount authorized. + */ + class CardPreAuthorizations { + /** + * Create new pre-authorization + * @param cardPreAuthorization + * @param options + */ + create: MethodOverload< + cardPreAuthorization.CreateCardPreAuthorization, + cardPreAuthorization.CardPreAuthorizationData + >; + + /** + * Get data for Card pre-authorization + * @param cardPreAuthorizationId + * @param options + */ + get: MethodOverload; + + /** + * Update pre-authorization object (currently only supports cancellation) + * @param cardPreAuthorization + */ + update: MethodOverload< + cardPreAuthorization.UpdateCardPreAuthorization, + cardPreAuthorization.CardPreAuthorizationData + >; + } + + class PayIns { + /** + * Create new pay-in + * @param payIn + * @param options + */ + create: MethodOverload< + payIn.CreateCardDirectPayIn, + payIn.CardDirectPayInData + > & + MethodOverload< + payIn.CreateCardPreAuthorizedPayIn, + payIn.CardPreAuthorizedPayInData + > & + MethodOverload & + MethodOverload< + payIn.CreateBankWireDirectPayIn, + payIn.BankWireDirectPayInData + >; + + /** + * Get pay-in + * @param payInId + * @param options + */ + get: MethodOverload; + + /** + * Create refund for pay-in object + * @param payInId + * @param refundData + * @param options + */ + createRefund: TwoArgsMethodOverload< + string, + refund.CreatePayInRefund, + refund.RefundData + >; + + /** + * Gets list of Refunds for a PayIn + * @param payInId + * @param options + */ + getRefunds: MethodOverload; + } + + class Refunds { + /** + * Get events + * @param refundId + * @param options + */ + get: MethodOverload; + } + + class Clients { + /** + * Get the client + */ + get: NoArgMethodOverload; + + /** + * Update the client + * @param client + * @param options + */ + update: MethodOverload; + + /** + * Upload client logo from base64 image string + * @param base64Logo + * @param options + */ + uploadLogo: MethodOverload; + + /** + * Upload client logo from file path + * @param filePath + * @param options + */ + uploadLogoFromFile: MethodOverload; + + /** + * Get all client wallets + * @param options + */ + getClientWallets: NoArgMethodOverload; + + /** + * Get a client wallet + * @param fundsType + * @param currency + * @param options + */ + getClientWallet: TwoArgsMethodOverload< + wallet.ClientFundsType, + CurrencyISO, + wallet.ClientWalletData + >; + + /** + * Get client wallets by the type of funds + * @param fundsType + * @param options + */ + getClientWalletsByFundsType: MethodOverload< + wallet.ClientFundsType, + wallet.ClientWalletData[] + >; + + /** + * Get a client wallet's transactions + * @param fundsType + * @param currency + * @param options + */ + getClientWalletTransactions: TwoArgsMethodOverload< + wallet.ClientFundsType, + CurrencyISO, + transaction.TransactionData[] + >; + } + + class PayOuts { + /** + * Create new pay-out + * @param payOut + * @param options + */ + create: MethodOverload; + + /** + * Get payout + * @param payOutId + * @param options + */ + get: MethodOverload; + + /** + * Gets list of Refunds of a PayOut + * @param payOutId + * @param options + */ + getRefunds: MethodOverload; + } + + class Transfers { + /** + * Create new transfer + * @param transfer + * @param options + */ + create: MethodOverload; + + /** + * Get transfer + * @param transferId + * @param options + */ + get: MethodOverload; + + /** + * Create refund for transfer object + * @param transferId + * @param refund + * @param options + */ + createRefund: TwoArgsMethodOverload< + string, + refund.CreateTransferRefund, + refund.RefundData + >; + + /** + * Gets list of Refunds of a Transfer + * @param transferId + * @param options + */ + getRefunds: MethodOverload; + } + + class BankingAliases { + /** + * Create a banking alias + * @param bankingAlias + * @param options + */ + create: MethodOverload< + bankingAlias.CreateIBANBankingAlias, + bankingAlias.IBANBankingAliasData + >; + + /** + * Get a banking alias + * @param bankingAliasId + * @param options + */ + get: MethodOverload; + + /** + * Get all banking aliases + * @param options + */ + getAll: NoArgMethodOverload; + + /** + * Update banking alias + * @param bankingAliasId + * @param options + */ + update: MethodOverload< + Partial>, + bankingAlias.IBANBankingAliasData + >; + + /** + * Deactivate banking alias + * @param bankingAliasId + * @param options + */ + deactivate: MethodOverload; + + /** + * Activate banking alias + * @param bankingAliasId + * @param options + */ + activate: MethodOverload; + } + + class DisputeDocuments { + /** + * Get all KycDocuments + * @param options + */ + getAll: NoArgMethodOverload; + + /** + * Get KycDocument + * @param documentId + * @param options + */ + get: MethodOverload; + + /** + * Creates temporary URLs where each page of a KYC document can be viewed. + * @param documentId + */ + createDisputeDocumentConsult: MethodOverload< + string, + any // Unsure of data structure from docs + >; + } + + class Repudiations { + /** + * Gets list of Refunds of a Repudiation + * @param repudiationId + * @param options + */ + getRefunds: MethodOverload; + } + + class Disputes { + /** + * Get dispute + * @param disputeId + * @param options + */ + get: MethodOverload; + + /** + * Get all disputes + * @param options + */ + getAll: NoArgMethodOverload; + + /** + * Update dispute's tag + * @param dispute + * @param options + */ + update: MethodOverload; + + /** + * Contest dispute + * @param disputeId + * @param contestedFunds + * @param options + */ + contestDispute: TwoArgsMethodOverload< + string, + MoneyData, + dispute.DisputeData + >; + + /** + * This method is used to resubmit a Dispute if it is reopened requiring more docs + * @param disputeId + * @param options + */ + resubmitDispute: MethodOverload; + + /** + * Close dispute + * @param disputeId + * @param options + */ + closeDispute: MethodOverload; + + /** + * Gets dispute's transactions + * @param disputeId + * @param options + */ + getTransactions: MethodOverload; + + /** + * Gets dispute's documents for wallet + * @param walletId + * @param options + */ + getDisputesForWallet: MethodOverload; + + /** + * Gets user's disputes + * @param userId + * @param options + */ + getDisputesForUser: MethodOverload; + + /** + * Gets repudiation + * @param repudiationId + * @param options + */ + getRepudiation: MethodOverload; + + /** + * Creates settlement transfer + * @param settlementTransfer + * @param repudiationId + * @param options + */ + createSettlementTransfer: TwoArgsMethodOverload< + settlementTransfer.CreateSettlementTransfer, + string, + settlementTransfer.SettlementTransferData + >; + + /** + * Gets settlement transfer + * @param settlementTransferId + * @param options + */ + getSettlementTransfer: MethodOverload< + string, + settlementTransfer.SettlementTransferData + >; + + /** + * Gets documents for dispute + * @param disputeId + * @param options + */ + getDocumentsForDispute: MethodOverload< + string, + disputeDocument.DisputeDocumentData[] + >; + + /** + * Update dispute document + * @param disputeId + * @param disputeDocument + * @param options + */ + updateDisputeDocument: TwoArgsMethodOverload< + string, + Partial, + disputeDocument.DisputeDocumentData + >; + + /** + * Creates document for dispute + * @param disputeId + * @param disputeDocument + * @param options + */ + createDisputeDocument: TwoArgsMethodOverload< + string, + disputeDocument.CreateDisputeDocument, + disputeDocument.DisputeDocumentData + >; + + /** + * Creates document's page for dispute + * @param disputeId + * @param disputeDocumentId + * @param disputeDocumentPage + * @param options + */ + createDisputeDocumentPage: ThreeArgsMethodOverload< + string, + string, + disputeDocument.CreateDisputeDocumentPage, + disputeDocument.DisputeDocumentData + >; + + /** + * Creates document's page for dispute from file + * @param disputeId + * @param disputeDocumentId + * @param file + * @param options + */ + createDisputeDocumentPageFromFile: ThreeArgsMethodOverload< + string, + string, + string, + disputeDocument.DisputeDocumentData + >; + + /** + * Retrieve a list of Disputes pending settlement + * @param options + */ + getPendingSettlement: NoArgMethodOverload; + } + + class Events { + /** + * Get events + * @param options + */ + getAll: NoArgMethodOverload; + } + + class Responses { + /** + * Get response from previous call + * @param options + */ + get: NoArgMethodOverload; + } + + class Mandates { + /** + * Create a new Mandate + * @param mandate + * @param options + */ + create: MethodOverload; + + /** + * Get all mandates + * @param options + */ + getAll: NoArgMethodOverload; + + /** + * Get mandate by ID + * @param mandateId + * @param options + */ + get: MethodOverload; + + /** + * Cancel a mandate + * @param mandateId + * @param options + */ + cancel: MethodOverload; + + /** + * Gets user's mandates + * @param userId + * @param options + */ + getMandatesForUser: MethodOverload; + + /** + * Gets bank account mandates + * @param userId + * @param bankAccountId + * @param options + */ + getMandatesForBankAccount: TwoArgsMethodOverload< + string, + string, + mandate.MandateData[] + >; + + /** + * Gets Transactions for a Mandate + * @param mandateId + * @param options + */ + getTransactions: MethodOverload; + } + class Hooks { + /** + * Create new hook + * @param hook + * @param options + */ + create: MethodOverload; + + /** + * Get hook + * @param hookId + * @param options + */ + get: MethodOverload; + + /** + * Save hook + * @param hook + * @param options + */ + update: MethodOverload; + + /** + * Get all hooks + * @param options + */ + getAll: NoArgMethodOverload; + } + + class Reports { + /** + * Create a report + * @param report + * @param options + */ + create: MethodOverload; + + /** + * Get a report + * @param reportId + * @param options + */ + get: MethodOverload; + + /** + * Get all reports + * @param options + */ + getAll: NoArgMethodOverload; + } +} diff --git a/types/mangopay2-nodejs-sdk/mangopay2-nodejs-sdk-tests.ts b/types/mangopay2-nodejs-sdk/mangopay2-nodejs-sdk-tests.ts new file mode 100644 index 0000000000..e1537fce6c --- /dev/null +++ b/types/mangopay2-nodejs-sdk/mangopay2-nodejs-sdk-tests.ts @@ -0,0 +1,722 @@ +import Mangopay = require("mangopay2-nodejs-sdk"); + +// $ExpectError +const invalidConfig: Mangopay.Config = {}; + +/* General Types */ + +const validConfig: Mangopay.Config = { + clientId: "your_client_id", + clientApiKey: "your_client_api_key", + baseUrl: "https://api.mangopay.com" +}; + +const api = new Mangopay(validConfig); // $ExpectType MangoPay +const payIn: Mangopay.models.PayIn = new api.models.PayIn({}); // $ExpectType PayIn +const address: Mangopay.models.Address = new api.models.Address({}); // $ExpectType Address + +const addressData: Mangopay.address.AddressData = { + AddressLine1: "20 T Street", + AddressLine2: "", + City: "London", + Country: "UK", + PostalCode: "FR43 2WE", + Region: "London" +}; + +/* Users */ + +const legalUser = new api.models.UserLegal({ + Name: "MangoPay", + Email: "info@mangopay.com", + LegalPersonType: "BUSINESS", + LegalRepresentativeFirstName: "Mango", + LegalRepresentativeLastName: "Pay", + LegalRepresentativeEmail: "mango@mangopay.com", + HeadquartersAddress: new api.models.Address({ + AddressLine1: "4101 Reservoir Rd NW", + AddressLine2: "", + City: "Washington", + Region: "District of Columbia", + PostalCode: "20007", + Country: "US" + }), + LegalRepresentativeBirthday: 1300186358, + LegalRepresentativeNationality: "FR", + LegalRepresentativeCountryOfResidence: "FR", + Tag: "custom tag" +}); + +api.Users.create(legalUser).then(data => { + const d = data; // $ExpectType UserLegalData + const value = data.PersonType; // $ExpectType "LEGAL" + + console.log(`${legalUser.Name} user created at ${legalUser.CreationDate}`); +}); + +api.Users.create(legalUser, { readResponseHeaders: true }).then(data => { + const d = data; // $ExpectType WithResponse + const value = data.body; // $ExpectType UserLegalData +}); + +api.Users.create( + { + PersonType: "LEGAL", + Name: "MangoPay", + Email: "info@mangopay.com", + LegalPersonType: "BUSINESS", + LegalRepresentativeFirstName: "Mango", + LegalRepresentativeLastName: "Pay", + LegalRepresentativeEmail: "mango@mangopay.com", + HeadquartersAddress: new api.models.Address({ + AddressLine1: "4101 Reservoir Rd NW", + AddressLine2: "", + City: "Washington", + Region: "District of Columbia", + PostalCode: "20007", + Country: "US" + }), + LegalRepresentativeBirthday: 1300186358, + LegalRepresentativeNationality: "FR", + LegalRepresentativeCountryOfResidence: "FR", + Tag: "custom tag" + }, + { headers: {} } +).then(data => { + const d = data; // $ExpectType UserLegalData +}); + +const naturalUser = new api.models.UserNatural({ + Email: "info@mangopay.com", + Birthday: 1300186358, + FirstName: "Sara", + LastName: "McNick", + CountryOfResidence: "GB", + Nationality: "US" +}); + +api.Users.create(naturalUser, {}).then(data => { + const d = data; // $ExpectType UserNaturalData + const value = data.PersonType; // $ExpectType "NATURAL" + return; +}); + +api.Users.create( + { + PersonType: "NATURAL", + Email: "info@mangopay.com", + Birthday: 1300186358, + FirstName: "Sara", + LastName: "McNick", + CountryOfResidence: "GB", + Nationality: "US", + Tag: "tagged-user" + }, + data => { + const d = data; // $ExpectType UserNaturalData + console.log("create", data); + } +); + +api.Users.get("1234").then(data => { + const d = data; // $ExpectType UserLegalData | UserNaturalData + if (data.PersonType === "LEGAL") { + const legalData = data; // $ExpectType UserLegalData + } else { + const naturalData = data; // $ExpectType UserNaturalData + } +}); + +api.Users.getAll().then(users => { + users.forEach(user => { + const d = user; // $ExpectType UserLegalData | UserNaturalData + if (user.PersonType === "LEGAL") { + const legalData = user; // $ExpectType UserLegalData + } else { + const naturalData = user; // $ExpectType UserNaturalData + } + }); +}); + +api.Users.update({ + Id: "1234", + PersonType: "NATURAL", + Email: "info@mangopay.com", + Birthday: 1300186358, + FirstName: "Sara", + LastName: "McNick", + CountryOfResidence: "GB", + Nationality: "US" +}).then(data => { + const d = data; // $ExpectType UserNaturalData +}); + +api.Users.createBankAccount("user-id", { + Type: "GB", + AccountNumber: "12345678", + SortCode: "123456", + OwnerAddress: "", + OwnerName: "" +}).then(data => { + const d = data; // $ExpectType GBData +}); + +api.Users.getBankAccount("user-id", "bankAccount-id").then(data => { + const d = data; // $ExpectType Data +}); + +api.Users.getBankAccounts("user-id").then(data => { + const d = data; // $ExpectType Data[] +}); + +api.Users.deactivateBankAccount("user-id", "bankAccount-id").then(data => { + const d = data; // $ExpectType void +}); + +api.Users.getTransactions("user-id").then(data => { + const d = data; // $ExpectType TransactionData[] +}); + +api.Users.getWallets("user-id").then(data => { + const d = data; // $ExpectType WalletData[] +}); + +api.Users.getCards("user-id").then(data => { + const d = data; // $ExpectType CardData[] +}); + +api.Users.createKycDocument("user-id", { Type: "ADDRESS_PROOF" }).then(data => { + const d = data; // $ExpectType KycDocumentData +}); + +api.Users.getKycDocuments("user-id").then(data => { + const d = data; // $ExpectType KycDocumentData[] +}); + +api.Users.getKycDocument("user-id", "kycDocument-id").then(data => { + const d = data; // $ExpectType KycDocumentData +}); + +api.Users.updateKycDocument("user-id", { Status: "VALIDATION_ASKED" }).then( + data => { + const d = data; // $ExpectType KycDocumentData + } +); + +api.Users.createKycPage("user-id", "kycDocument-id", { + File: "...base64data..." +}).then(data => { + const d = data; // $ExpectType KycDocumentData +}); + +api.Users.createKycPageFromFile( + "user-id", + "kyc-document-id", + "path/to/file" +).then(data => { + const d = data; // $ExpectType KycDocumentData +}); + +// MangoPay. + +api.Users.getEMoney("user-id").then(data => { + const d = data; // $ExpectType EMoneyData +}); + +api.Users.createUboDeclaration("user-id", { DeclaredUBOs: ["user1"] }).then( + data => { + const d = data; // $ExpectType UboDeclarationData + } +); + +api.Users.getPreAuthorizations("user-id").then(data => { + const d = data; // $ExpectType CardPreAuthorizationData[] +}); + +/* KycDocuments */ + +api.KycDocuments.getAll().then(data => { + const d = data; // $ExpectType KycDocumentData[] +}); + +api.KycDocuments.get("kyc-id").then(data => { + const d = data; // $ExpectType KycDocumentData +}); + +api.KycDocuments.createKycDocumentConsult("kyc-id").then(data => { + const d = data; // TODO unsure of expected type +}); + +/* UboDeclarations */ + +api.UboDeclarations.get("ubo-id").then(data => { + const d = data; // $ExpectType UboDeclarationData +}); + +api.UboDeclarations.update({ + Id: "ubo-id", + DeclaredUBOs: ["user1", "user2"] +}).then(data => { + const d = data; // $ExpectType UboDeclarationData +}); + +/* BankAccounts */ + +api.BankAccounts.getTransactions("account-id").then(data => { + const d = data; // $ExpectType TransactionData[] +}); + +/* Wallets */ + +api.Wallets.create({ + Currency: "GBP", + Description: "A description", + Owners: ["user-id"] +}).then(data => { + const d = data; // $ExpectType WalletData +}); + +const wallet = new api.models.Wallet({ + Currency: "GB", + Description: "A description", + Owners: ["user-id"] +}); + +api.Wallets.create(wallet).then(data => { + const d = data; // $ExpectType WalletData +}); + +api.Wallets.update({ + Description: "A description" +}).then(data => { + const d = data; // $ExpectType WalletData +}); + +api.Wallets.get("wallet-id").then(data => { + const d = data; // $ExpectType WalletData +}); + +api.Wallets.getTransactions("wallet-id").then(data => { + const d = data; // $ExpectType TransactionData[] +}); + +/* Cards */ + +api.Cards.get("card-id").then(data => { + const d = data; // $ExpectType CardData +}); + +api.Cards.getByFingerprint("fingerprinthash").then(data => { + const d = data; // $ExpectType CardData[] +}); + +api.Cards.update({ Active: false, Id: "card-id" }).then(data => { + const d = data; // $ExpectType CardData +}); + +api.Cards.getTransactions("card-id").then(data => { + const d = data; // $ExpectType TransactionData[] +}); + +/* CardRegistrations */ + +api.CardRegistrations.create({ + CardType: "BCMC", + Currency: "GBP", + UserId: "user-id" +}).then(data => { + const d = data; // $ExpectType CardRegistrationData +}); + +api.CardRegistrations.get("reg-id").then(data => { + const d = data; // $ExpectType CardRegistrationData +}); + +api.CardRegistrations.update({ RegistrationData: "hmmm" }).then(data => { + const d = data; // $ExpectType CardRegistrationData +}); + +/* CardPreAuthorizations */ + +api.CardPreAuthorizations.create({ + AuthorId: "user", + CardId: "card-id", + DebitedFunds: { Currency: "AUD", Amount: 4000 }, + SecureModeReturnURL: "https://secureurl.com" +}).then(data => { + const d = data; // $ExpectType CardPreAuthorizationData +}); + +api.CardPreAuthorizations.get("auth-id").then(data => { + const d = data; // $ExpectType CardPreAuthorizationData +}); + +api.CardPreAuthorizations.update({ + Id: "auth-id", + PaymentStatus: "CANCELED" +}).then(data => { + const d = data; // $ExpectType CardPreAuthorizationData +}); + +/* Refunds */ + +api.Refunds.get("refund-id").then(data => { + const d = data; // $ExpectType RefundData +}); + +/* PayIns */ + +api.PayIns.create({ + PaymentType: "CARD", + ExecutionType: "DIRECT", + AuthorId: "user-id", + CardId: "card-id", + CreditedWalletId: "wallet-id", + Fees: { Amount: 100, Currency: "GBP" }, + DebitedFunds: { Amount: 2000, Currency: "GBP" }, + SecureModeReturnURL: "https://secure-return.co" +}).then(data => { + const d = data; // $ExpectType CardDirectPayInData +}); + +api.PayIns.create({ + PaymentType: "CARD", + ExecutionType: "WEB", + AuthorId: "user-id", + CreditedWalletId: "wallet-id", + Fees: { Amount: 100, Currency: "GBP" }, + DebitedFunds: { Amount: 2000, Currency: "GBP" }, + ReturnURL: "https://secure-return.co", + Culture: "AD", + CardType: "MAESTRO" +}).then(data => { + const d = data; // $ExpectType CardWebPayInData +}); + +api.PayIns.create({ + PaymentType: "BANK_WIRE", + ExecutionType: "DIRECT", + AuthorId: "user-id", + CreditedWalletId: "wallet-id", + CreditedUserId: "credited-user-id", + DeclaredDebitedFunds: { Amount: 10000, Currency: "GBP" }, + DeclaredFees: { Amount: 500, Currency: "GBP" } +}).then(data => { + const d = data; // $ExpectType BankWireDirectPayInData +}); + +api.PayIns.get("payin-id").then(data => { + const d = data; // $ExpectType PayInData +}); + +api.PayIns.createRefund("payin-id", { AuthorId: "user-id" }).then(data => { + const d = data; // $ExpectType RefundData +}); + +api.PayIns.getRefunds("payin-id").then(data => { + const d = data; // $ExpectType RefundData[] +}); + +/* Clients */ +api.Clients.get().then(data => { + const d = data; // $ExpectType ClientData +}); + +api.Clients.update({ PlatformType: "CROWDFUNDING_DONATION" }).then(data => { + const d = data; // $ExpectType ClientData +}); + +api.Clients.uploadLogo("...logobase64...").then(data => { + const d = data; // $ExpectType ClientData +}); + +api.Clients.uploadLogoFromFile("path/to/file").then(data => { + const d = data; // $ExpectType ClientData +}); + +api.Clients.getClientWallets().then(data => { + const d = data; // $ExpectType ClientWalletData[] +}); + +api.Clients.getClientWallet("CREDIT", "GBP").then(data => { + const d = data; // $ExpectType ClientWalletData +}); + +api.Clients.getClientWalletsByFundsType("FEES").then(data => { + const d = data; // $ExpectType ClientWalletData[] +}); + +api.Clients.getClientWalletTransactions("CREDIT", "GBP").then(data => { + const d = data; // $ExpectType TransactionData[] +}); + +/* PayOuts */ + +api.PayOuts.create({ + Fees: { Amount: 0, Currency: "GBP" }, + AuthorId: "user-id", + DebitedFunds: { Amount: 2000, Currency: "GBP" }, + BankAccountId: "bank-id", + DebitedWalletId: "wallet-id" +}).then(data => { + const d = data; // $ExpectType PayOutData +}); + +api.PayOuts.get("payout-id").then(data => { + const d = data; // $ExpectType PayOutData +}); + +api.PayOuts.getRefunds("payout-id").then(data => { + const d = data; // $ExpectType RefundData[] +}); + +/* Transfers */ + +api.Transfers.create({ + Fees: { Amount: 0, Currency: "GBP" }, + AuthorId: "user-id", + DebitedFunds: { Amount: 2000, Currency: "GBP" }, + DebitedWalletId: "debit-wallet-id", + CreditedWalletId: "credit-wallet-id" +}).then(data => { + const d = data; // $ExpectType TransferData +}); + +api.Transfers.get("transfer-id").then(data => { + const d = data; // $ExpectType TransferData +}); + +api.Transfers.createRefund("transfer-id", { AuthorId: "user-id" }).then( + data => { + const d = data; // $ExpectType RefundData + } +); + +api.Transfers.getRefunds("transfer-id").then(data => { + const d = data; // $ExpectType RefundData[] +}); + +/* BankingAliases */ + +api.BankingAliases.create({ + Country: "GB", + CreditedUserId: "user-id", + OwnerName: "owner-id" +}).then(data => { + const d = data; // $ExpectType IBANBankingAliasData +}); +api.BankingAliases.get("alias-id").then(data => { + const d = data; // $ExpectType IBANBankingAliasData +}); +api.BankingAliases.getAll().then(data => { + const d = data; // $ExpectType IBANBankingAliasData[] +}); +api.BankingAliases.update({ OwnerName: "some-name" }).then(data => { + const d = data; // $ExpectType IBANBankingAliasData +}); +api.BankingAliases.deactivate("alias-id").then(data => { + const d = data; // $ExpectType IBANBankingAliasData +}); +api.BankingAliases.activate("alias-id").then(data => { + const d = data; // $ExpectType IBANBankingAliasData +}); + +/* DisputeDocuments */ + +api.DisputeDocuments.getAll().then(data => { + const d = data; // $ExpectType DisputeDocumentData[] +}); + +api.DisputeDocuments.get("dispute-doc-id").then(data => { + const d = data; // $ExpectType DisputeDocumentData +}); + +api.DisputeDocuments.createDisputeDocumentConsult("dispute-doc-id").then( + data => { + const d = data; // TODO unsure of expected type + } +); + +/* Repudiations */ + +api.Repudiations.getRefunds("repudiation-id").then(data => { + const d = data; // $Expect RefundData[] +}); + +/* Disputes */ + +api.Disputes.get("dispute-id").then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.getAll().then(data => { + const d = data; // $Expect DisputeData[] +}); + +api.Disputes.update({ Tag: "any tags" }).then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.contestDispute("dispute-id", { + Amount: 1000, + Currency: "GBP" +}).then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.resubmitDispute("dispute-id").then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.closeDispute("dispute-id").then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.getTransactions("dispute-id").then(data => { + const d = data; // $Expect TransactionData[] +}); + +api.Disputes.getDisputesForWallet("wallet-id").then(data => { + const d = data; // $Expect DisputeData[] +}); + +api.Disputes.getDisputesForUser("user-id").then(data => { + const d = data; // $Expect DisputeData[] +}); + +api.Disputes.getRepudiation("repudiation-id").then(data => { + const d = data; // $Expect RepudationData +}); + +api.Disputes.createSettlementTransfer( + { + AuthorId: "user-id", + DebitedFunds: { Amount: 1000, Currency: "GBP" }, + Fees: { Amount: 200, Currency: "GBP" } + }, + "repudiation-id" +).then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.getSettlementTransfer("settlement-id").then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.getDocumentsForDispute("dispute-id").then(data => { + const d = data; // $Expect DisputeDocumentData[] +}); + +api.Disputes.updateDisputeDocument("dispute-id", { Tag: "update" }).then( + data => { + const d = data; // $Expect DisputeDocumentData + } +); + +api.Disputes.createDisputeDocument("dispute-id", { + Type: "DELIVERY_PROOF" +}).then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.createDisputeDocumentPage("dispute-id", "dispute-doc-id", { + File: "...base64string..." +}).then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.createDisputeDocumentPageFromFile( + "dispute-id", + "dispute-doc-id", + "path/to/file" +).then(data => { + const d = data; // $Expect DisputeData +}); + +api.Disputes.getPendingSettlement().then(data => { + const d = data; // $Expect DisputeData +}); + +/* Events */ + +api.Events.getAll().then(data => { + const d = data; // $Expect EventData[] +}); + +/* Responses */ + +api.Responses.get().then(data => { + const d = data; // $ExpectType any[] +}); + +/* Mandates */ + +api.Mandates.create({ + BankAccountId: "bank-account-id", + ReturnURL: "https://return-url.com", + Culture: "EN" +}).then(data => { + const d = data; // $ExpectType MandateData +}); + +api.Mandates.getAll().then(data => { + const d = data; // $ExpectType MandateData[] +}); + +api.Mandates.get("mandate-id").then(data => { + const d = data; // $ExpectType MandateData +}); + +api.Mandates.cancel("mandate-id").then(data => { + const d = data; // $ExpectType MandateData +}); + +api.Mandates.getMandatesForUser("user-id").then(data => { + const d = data; // $ExpectType MandateData[] +}); + +api.Mandates.getMandatesForBankAccount("user-id", "bank-account-id").then( + data => { + const d = data; // $ExpectType MandateData[] + } +); +api.Mandates.getTransactions("mandate-id").then(data => { + const d = data; // $ExpectType TransactionData[] +}); + +/* Hooks */ + +api.Hooks.create({ + Url: "https://hook-url.com", + EventType: "DISPUTE_ACTION_REQUIRED" +}).then(data => { + const d = data; // $ExpectType HookData +}); + +api.Hooks.get("hook-id").then(data => { + const d = data; // $ExpectType HookData +}); + +api.Hooks.update({ Id: "hook-id", Url: "https://new-hook.com/hooks" }).then( + data => { + const d = data; // $ExpectType HookData + } +); + +api.Hooks.getAll().then(data => { + const d = data; // $ExpectType HookData[] +}); + +/* Reports */ + +api.Reports.create({ Columns: ["Alias", "AuthorId"] }).then(data => { + const d = data; // $ExpectType ReportData +}); + +api.Reports.get("report-id").then(data => { + const d = data; // $ExpectType ReportData +}); + +api.Reports.getAll().then(data => { + const d = data; // $ExpectType ReportData[] +}); diff --git a/types/mangopay2-nodejs-sdk/tsconfig.json b/types/mangopay2-nodejs-sdk/tsconfig.json new file mode 100644 index 0000000000..5ff752d7e4 --- /dev/null +++ b/types/mangopay2-nodejs-sdk/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noEmit": true, + "lib": ["es6"], + "noUnusedLocals": false, + "noUnusedParameters": false, + "forceConsistentCasingInFileNames": true, + "experimentalDecorators": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "types": [], + "typeRoots": ["../"] + }, + + "files": ["index.d.ts", "types.d.ts", "mangopay2-nodejs-sdk-tests.ts"] +} diff --git a/types/mangopay2-nodejs-sdk/tslint.json b/types/mangopay2-nodejs-sdk/tslint.json new file mode 100644 index 0000000000..c31797feab --- /dev/null +++ b/types/mangopay2-nodejs-sdk/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-redundant-jsdoc": false, + "no-misused-new": false, + "no-empty-interface": false, + "interface-name": false, + "no-unnecessary-class": false + } +} diff --git a/types/mangopay2-nodejs-sdk/types.d.ts b/types/mangopay2-nodejs-sdk/types.d.ts new file mode 100644 index 0000000000..1edb7bd4f2 --- /dev/null +++ b/types/mangopay2-nodejs-sdk/types.d.ts @@ -0,0 +1,565 @@ +/** + * Makes specified keys of an interface Optional. + */ +export type MakeKeysOptional = Omit & + Partial>; + +export type PickPartial = Pick, Par>; + +export type PickPartialRequired< + T, + Par extends keyof T, + Req extends keyof T +> = Pick, Par> & Pick, Req>; + +export type DeepPartial = { [P in keyof T]?: DeepPartial }; + +/** + * Makes specified keys of an interface nullable. + */ +export type MakeKeysNullable = Omit & + { [P in T2]: T1[P] | null }; + +/** + * Makes specified keys of an interface Required. + */ +export type MakeKeysRequired = Omit & + Required>; + +export type Omit = Pick>; + +export type OmitType = Omit; + +export type ValueOf = T[keyof T]; + +export type ApiMethod = + | "authentication_oauth" + | "responses_get" + | "events_all" + | "hooks_create" + | "hooks_all" + | "hooks_get" + | "hooks_save" + | "cardregistration_create" + | "cardregistration_get" + | "cardregistration_save" + | "preauthorization_create" + | "preauthorization_get" + | "preauthorization_save" + | "preauthorizations_get_for_user" + | "card_get" + | "cards_get_by_fingerprint" + | "card_save" + | "card_get_preauthorizations" + | "payins_card-web_create" + | "payins_card-direct_create" + | "payins_preauthorized-direct_create" + | "payins_bankwire-direct_create" + | "payins_directdebit-web_create" + | "payins_directdebit-direct_create" + | "payins_paypal-web_create" + | "payins_get" + | "payins_createrefunds" + | "payouts_bankwire_create" + | "payouts_get" + | "refunds_get" + | "refunds_get_for_repudiation" + | "refunds_get_for_transfer" + | "refunds_get_for_payin" + | "refunds_get_for_payout" + | "transfers_create" + | "transfers_get" + | "transfers_createrefunds" + | "users_createnaturals" + | "users_createlegals" + | "users_createbankaccounts_iban" + | "users_createbankaccounts_gb" + | "users_createbankaccounts_us" + | "users_createbankaccounts_ca" + | "users_createbankaccounts_other" + | "users_all" + | "users_allwallets" + | "users_allbankaccount" + | "users_allcards" + | "users_alltransactions" + | "users_allkycdocuments" + | "users_get" + | "users_getnaturals" + | "users_getlegals" + | "users_getbankaccount" + | "users_deactivate_bankaccount" + | "users_savenaturals" + | "users_savelegals" + | "users_getemoney" + | "wallets_create" + | "wallets_alltransactions" + | "wallets_get" + | "wallets_save" + | "kyc_documents_create" + | "kyc_documents_get" + | "kyc_documents_save" + | "kyc_page_create" + | "kyc_documents_all" + | "kyc_documents_get_alt" + | "kyc_documents_create_consult" + | "disputes_get" + | "disputes_save_tag" + | "disputes_save_contest_funds" + | "dispute_save_close" + | "disputes_get_transactions" + | "disputes_all" + | "disputes_get_for_wallet" + | "disputes_get_for_user" + | "disputes_document_create" + | "disputes_document_page_create" + | "disputes_document_save" + | "disputes_document_get" + | "disputes_document_get_for_dispute" + | "disputes_document_all" + | "disputes_document_create_consult" + | "disputes_repudiation_get" + | "disputes_repudiation_create_settlement" + | "disputes_repudiation_get_settlement" + | "disputes_pending_settlement" + | "reports_transaction_create" + | "reports_wallet_create" + | "reports_get" + | "reports_all" + | "mandates_directdebit-web_create" + | "mandates_get" + | "mandates_cancel" + | "mandates_all" + | "mandates_get_for_user" + | "mandates_get_for_bank_account" + | "clients_get" + | "clients_update" + | "clients_upload_logo" + | "client_wallets_all" + | "client_wallets_get" + | "client_wallets_by_fundsType" + | "client_wallets_transactions" + | "banking_aliases_iban_create" + | "banking_aliases_get" + | "banking_aliases_update" + | "banking_aliases_all" + | "ubo_declaration_create" + | "ubo_declaration_update" + | "ubo_declaration_get" + | "transactions_get_for_mandate" + | "transactions_get_for_card" + | "transactions_get_for_bank_account"; + +export type CountryISO = + | "AD" + | "AE" + | "AF" + | "AG" + | "AI" + | "AL" + | "AM" + | "AO" + | "AQ" + | "AR" + | "AS" + | "AT" + | "AU" + | "AW" + | "AX" + | "AZ" + | "BA" + | "BB" + | "BD" + | "BE" + | "BF" + | "BG" + | "BH" + | "BI" + | "BJ" + | "BL" + | "BM" + | "BN" + | "BO" + | "BQ" + | "BR" + | "BS" + | "BT" + | "BV" + | "BW" + | "BY" + | "BZ" + | "CA" + | "CC" + | "CD" + | "CF" + | "CG" + | "CH" + | "CI" + | "CK" + | "CL" + | "CM" + | "CN" + | "CO" + | "CR" + | "CU" + | "CV" + | "CW" + | "CX" + | "CY" + | "CZ" + | "DE" + | "DJ" + | "DK" + | "DM" + | "DO" + | "DZ" + | "EC" + | "EE" + | "EG" + | "EH" + | "ER" + | "ES" + | "ET" + | "FI" + | "FJ" + | "FK" + | "FM" + | "FO" + | "FR" + | "GA" + | "GB" + | "GD" + | "GE" + | "GF" + | "GG" + | "GH" + | "GI" + | "GL" + | "GM" + | "GN" + | "GP" + | "GQ" + | "GR" + | "GS" + | "GT" + | "GU" + | "GW" + | "GY" + | "HK" + | "HM" + | "HN" + | "HR" + | "HT" + | "HU" + | "ID" + | "IE" + | "IL" + | "IM" + | "IN" + | "IO" + | "IQ" + | "IR" + | "IS" + | "IT" + | "JE" + | "JM" + | "JO" + | "JP" + | "KE" + | "KG" + | "KH" + | "KI" + | "KM" + | "KN" + | "KP" + | "KR" + | "KW" + | "KY" + | "KZ" + | "LA" + | "LB" + | "LC" + | "LI" + | "LK" + | "LR" + | "LS" + | "LT" + | "LU" + | "LV" + | "LY" + | "MA" + | "MC" + | "MD" + | "ME" + | "MF" + | "MG" + | "MH" + | "MK" + | "ML" + | "MM" + | "MN" + | "MO" + | "MP" + | "MQ" + | "MR" + | "MS" + | "MT" + | "MU" + | "MV" + | "MW" + | "MX" + | "MY" + | "MZ" + | "NA" + | "NC" + | "NE" + | "NF" + | "NG" + | "NI" + | "NL" + | "NO" + | "NP" + | "NR" + | "NU" + | "NZ" + | "OM" + | "PA" + | "PE" + | "PF" + | "PG" + | "PH" + | "PK" + | "PL" + | "PM" + | "PN" + | "PR" + | "PS" + | "PT" + | "PW" + | "PY" + | "QA" + | "RE" + | "RO" + | "RS" + | "RU" + | "RW" + | "SA" + | "SB" + | "SC" + | "SD" + | "SE" + | "SG" + | "SH" + | "SI" + | "SJ" + | "SK" + | "SL" + | "SM" + | "SN" + | "SO" + | "SR" + | "SS" + | "ST" + | "SV" + | "SX" + | "SY" + | "SZ" + | "TC" + | "TD" + | "TF" + | "TG" + | "TH" + | "TJ" + | "TK" + | "TL" + | "TM" + | "TN" + | "TO" + | "TR" + | "TT" + | "TV" + | "TW" + | "TZ" + | "UA" + | "UG" + | "UM" + | "US" + | "UY" + | "UZ" + | "VA" + | "VC" + | "VE" + | "VG" + | "VI" + | "VN" + | "VU" + | "WF" + | "WS" + | "YE" + | "YT" + | "ZA" + | "ZM" + | "ZW"; + +export type CurrencyISO = + | "AED" + | "AFN" + | "ALL" + | "AMD" + | "ANG" + | "AOA" + | "ARS" + | "AUD" + | "AWG" + | "AZN" + | "BAM" + | "BBD" + | "BDT" + | "BGN" + | "BHD" + | "BIF" + | "BMD" + | "BND" + | "BOB" + | "BRL" + | "BSD" + | "BTN" + | "BWP" + | "BYN" + | "BZD" + | "CAD" + | "CDF" + | "CHF" + | "CLP" + | "CNY" + | "COP" + | "CRC" + | "CUC" + | "CUP" + | "CVE" + | "CZK" + | "DJF" + | "DKK" + | "DOP" + | "DZD" + | "EGP" + | "ERN" + | "ETB" + | "EUR" + | "FJD" + | "FKP" + | "GBP" + | "GEL" + | "GGP" + | "GHS" + | "GIP" + | "GMD" + | "GNF" + | "GTQ" + | "GYD" + | "HKD" + | "HNL" + | "HRK" + | "HTG" + | "HUF" + | "IDR" + | "ILS" + | "IMP" + | "INR" + | "IQD" + | "IRR" + | "ISK" + | "JEP" + | "JMD" + | "JOD" + | "JPY" + | "KES" + | "KGS" + | "KHR" + | "KMF" + | "KPW" + | "KRW" + | "KWD" + | "KYD" + | "KZT" + | "LAK" + | "LBP" + | "LKR" + | "LRD" + | "LSL" + | "LYD" + | "MAD" + | "MDL" + | "MGA" + | "MKD" + | "MMK" + | "MNT" + | "MOP" + | "MRU" + | "MUR" + | "MVR" + | "MWK" + | "MXN" + | "MYR" + | "MZN" + | "NAD" + | "NGN" + | "NIO" + | "NOK" + | "NPR" + | "NZD" + | "OMR" + | "PAB" + | "PEN" + | "PGK" + | "PHP" + | "PKR" + | "PLN" + | "PYG" + | "QAR" + | "RON" + | "RSD" + | "RUB" + | "RWF" + | "SAR" + | "SBD" + | "SCR" + | "SDG" + | "SEK" + | "SGD" + | "SHP" + | "SLL" + | "SOS" + | "SPL" + | "SRD" + | "STN" + | "SVC" + | "SYP" + | "SZL" + | "THB" + | "TJS" + | "TMT" + | "TND" + | "TOP" + | "TRY" + | "TTD" + | "TVD" + | "TWD" + | "TZS" + | "UAH" + | "UGX" + | "USD" + | "UYU" + | "UZS" + | "VEF" + | "VND" + | "VUV" + | "WST" + | "XAF" + | "XCD" + | "XDR" + | "XOF" + | "XPF" + | "YER" + | "ZAR" + | "ZMW" + | "ZWD"; diff --git a/types/mapbox__geo-viewport/index.d.ts b/types/mapbox__geo-viewport/index.d.ts index 6cfa8638f8..d48321ffb8 100644 --- a/types/mapbox__geo-viewport/index.d.ts +++ b/types/mapbox__geo-viewport/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @mapbox/geo-viewport 0.3 +// Type definitions for @mapbox/geo-viewport 0.4 // Project: https://github.com/mapbox/geo-viewport // Definitions by: Fabio Berta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,6 +10,6 @@ export interface GeoViewport { export type BoundingBox = [number, number, number, number]; -export function viewport(bounds: BoundingBox, dimensions: [number, number], minzoom?: number, maxzoom?: number, tileSize?: number): GeoViewport; +export function viewport(bounds: BoundingBox, dimensions: [number, number], minzoom?: number, maxzoom?: number, tileSize?: number, allowFloat?: boolean): GeoViewport; export function bounds(viewport: { lon: number; lat: number } | [number, number], zoom: number, dimensions: [number, number], tileSize?: number): BoundingBox; diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index dd9cd76640..772f418df3 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -105,6 +105,9 @@ declare namespace massive { term: string; } + type QueryParamTypes = string | number | object; + type QueryParams = QueryParamTypes[] | QueryParamTypes; + interface EntitySpecification { /** A Database. */ db: Database; @@ -442,7 +445,7 @@ declare namespace massive { /** Execute a query. */ query( query: Select | Insert | Update | Delete | string, - params?: string[], + params?: QueryParams, options?: ResultProcessingOptions ): Promise; diff --git a/types/match-sorter/index.d.ts b/types/match-sorter/index.d.ts index e1a7e8efe4..dd4f5bc5a7 100644 --- a/types/match-sorter/index.d.ts +++ b/types/match-sorter/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for match-sorter 2.2 +// Type definitions for match-sorter 2.3 // Project: https://github.com/kentcdodds/match-sorter#readme // Definitions by: Claas Ahlrichs +// Christian Ruigrok // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare namespace matchSorter { namespace rankings { @@ -18,24 +20,13 @@ declare namespace matchSorter { } } -interface MinRanking { - minRanking: number; - key: string; -} - -interface MaxRanking { - maxRanking: number; - key: string; -} - -interface MinMaxRanking { - minRanking: number; - maxRanking: number; - key: string; -} +type ExtendedKeyOptions = { key: string | ((item: T) => string) } & ( + | { minRanking: number } + | { maxRanking: number } + | { threshold: number }); interface Options { - keys?: Array<(string | ((item: T) => string) | MinRanking | MaxRanking | MinMaxRanking)>; + keys?: Array string) | ExtendedKeyOptions>; threshold?: number; keepDiacritics?: boolean; } @@ -47,6 +38,10 @@ interface Options { * @param options - Some options to configure the sorter * @return the new sorted array */ -declare function matchSorter(items: T[], value: string, options?: Options): T[]; +declare function matchSorter( + items: ReadonlyArray, + value: string, + options?: Options +): T[]; export = matchSorter; diff --git a/types/match-sorter/match-sorter-tests.ts b/types/match-sorter/match-sorter-tests.ts index e1496cba9f..a6529f7998 100644 --- a/types/match-sorter/match-sorter-tests.ts +++ b/types/match-sorter/match-sorter-tests.ts @@ -2,129 +2,165 @@ import matchSorter = require('match-sorter'); // # Basic Sample { - const list = ['hi', 'hey', 'hello', 'sup', 'yo']; - matchSorter(list, 'h'); // ['hi', 'hey', 'hello'] - matchSorter(list, 'y'); // ['yo', 'hey'] - matchSorter(list, 'z'); // [] + const list = ['hi', 'hey', 'hello', 'sup', 'yo']; + matchSorter(list, 'h'); // ['hi', 'hey', 'hello'] + matchSorter(list, 'y'); // ['yo', 'hey'] + matchSorter(list, 'z'); // [] } // # Advanced options // ## keys: [string] { - const objList = [ - {name: 'Janice', color: 'Green'}, - {name: 'Fred', color: 'Orange'}, - {name: 'George', color: 'Blue'}, - {name: 'Jen', color: 'Red'}, - ]; - matchSorter(objList, 'g', {keys: ['name', 'color']}); - // [{name: 'George', color: 'Blue'}, {name: 'Janice', color: 'Green'}, {name: 'Fred', color: 'Orange'}] + const objList = [ + { name: 'Janice', color: 'Green' }, + { name: 'Fred', color: 'Orange' }, + { name: 'George', color: 'Blue' }, + { name: 'Jen', color: 'Red' } + ]; + matchSorter(objList, 'g', { keys: ['name', 'color'] }); + // [{name: 'George', color: 'Blue'}, {name: 'Janice', color: 'Green'}, {name: 'Fred', color: 'Orange'}] - matchSorter(objList, 're', {keys: ['color', 'name']}); - // [{name: 'Jen', color: 'Red'}, {name: 'Janice', color: 'Green'}, {name: 'Fred', color: 'Orange'}, {name: 'George', color: 'Blue'}] + matchSorter(objList, 're', { keys: ['color', 'name'] }); + // [{name: 'Jen', color: 'Red'}, {name: 'Janice', color: 'Green'}, {name: 'Fred', color: 'Orange'}, {name: 'George', color: 'Blue'}] } // ### Array of values { - const iceCreamYum = [ - {favoriteIceCream: ['mint', 'chocolate']}, - {favoriteIceCream: ['candy cane', 'brownie']}, - {favoriteIceCream: ['birthday cake', 'rocky road', 'strawberry']}, - ]; - matchSorter(iceCreamYum, 'cc', {keys: ['favoriteIceCream']}); - // [{favoriteIceCream: ['candy cane', 'brownie']}, {favoriteIceCream: ['mint', 'chocolate']}] + const iceCreamYum = [ + { favoriteIceCream: ['mint', 'chocolate'] }, + { favoriteIceCream: ['candy cane', 'brownie'] }, + { favoriteIceCream: ['birthday cake', 'rocky road', 'strawberry'] } + ]; + matchSorter(iceCreamYum, 'cc', { keys: ['favoriteIceCream'] }); + // [{favoriteIceCream: ['candy cane', 'brownie']}, {favoriteIceCream: ['mint', 'chocolate']}] } // ### Nested Keys { - const nestedObjList = [ - {name: {first: 'Janice'}}, - {name: {first: 'Fred'}}, - {name: {first: 'George'}}, - {name: {first: 'Jen'}}, - ]; - matchSorter(nestedObjList, 'j', {keys: ['name.first']}); - // [{name: {first: 'Janice'}}, {name: {first: 'Jen'}}] + const nestedObjList = [ + { name: { first: 'Janice' } }, + { name: { first: 'Fred' } }, + { name: { first: 'George' } }, + { name: { first: 'Jen' } } + ]; + matchSorter(nestedObjList, 'j', { keys: ['name.first'] }); + // [{name: {first: 'Janice'}}, {name: {first: 'Jen'}}] } { - const nestedObjList = [ - {name: [{first: 'Janice'}]}, - {name: [{first: 'Fred'}]}, - {name: [{first: 'George'}]}, - {name: [{first: 'Jen'}]}, - ]; - matchSorter(nestedObjList, 'j', {keys: ['name.0.first']}); - // [{name: {first: 'Janice'}}, {name: {first: 'Jen'}}] - // matchSorter(nestedObjList, 'j', {keys: ['name[0].first']}) does not work + const nestedObjList = [ + { name: [{ first: 'Janice' }] }, + { name: [{ first: 'Fred' }] }, + { name: [{ first: 'George' }] }, + { name: [{ first: 'Jen' }] } + ]; + matchSorter(nestedObjList, 'j', { keys: ['name.0.first'] }); + // [{name: {first: 'Janice'}}, {name: {first: 'Jen'}}] + // matchSorter(nestedObjList, 'j', {keys: ['name[0].first']}) does not work } // ### Property Callbacks { - const list = [{name: 'Janice'}, {name: 'Fred'}, {name: 'George'}, {name: 'Jen'}]; - matchSorter(list, 'j', {keys: [item => item.name]}); - // [{name: 'Janice'}, {name: 'Jen'}] + const list = [ + { name: 'Janice' }, + { name: 'Fred' }, + { name: 'George' }, + { name: 'Jen' } + ]; + matchSorter(list, 'j', { keys: [item => item.name] }); + // [{name: 'Janice'}, {name: 'Jen'}] } // ### Min and Max Ranking { - const tea = [ - {tea: 'Earl Grey', alias: 'A'}, - {tea: 'Assam', alias: 'B'}, - {tea: 'Black', alias: 'C'}, - ]; - matchSorter(tea, 'A', { - keys: ['tea', {maxRanking: matchSorter.rankings.STARTS_WITH, key: 'alias'}], - }); - // without maxRanking, Earl Grey would come first because the alias "A" would be CASE_SENSITIVE_EQUAL - // `tea` key comes before `alias` key, so Assam comes first even though both match as STARTS_WITH - // [{tea: 'Assam', alias: 'B'}, {tea: 'Earl Grey', alias: 'A'},{tea: 'Black', alias: 'C'}] + const tea = [ + { tea: 'Earl Grey', alias: 'A' }, + { tea: 'Assam', alias: 'B' }, + { tea: 'Black', alias: 'C' } + ]; + matchSorter(tea, 'A', { + keys: [ + 'tea', + { maxRanking: matchSorter.rankings.STARTS_WITH, key: 'alias' } + ] + }); + // without maxRanking, Earl Grey would come first because the alias "A" would be CASE_SENSITIVE_EQUAL + // `tea` key comes before `alias` key, so Assam comes first even though both match as STARTS_WITH + // [{tea: 'Assam', alias: 'B'}, {tea: 'Earl Grey', alias: 'A'},{tea: 'Black', alias: 'C'}] } { - const tea = [ - {tea: 'Milk', alias: 'moo'}, - {tea: 'Oolong', alias: 'B'}, - {tea: 'Green', alias: 'C'}, - ]; - matchSorter(tea, 'oo', { - keys: ['tea', {minRanking: matchSorter.rankings.EQUAL, key: 'alias'}], - }); - // minRanking bumps Milk up to EQUAL from CONTAINS (alias) - // Oolong matches as STARTS_WITH - // Green is missing due to no match - // [{tea: 'Milk', alias: 'moo'}, {tea: 'Oolong', alias: 'B'}] + const tea = [ + { tea: 'Milk', alias: 'moo' }, + { tea: 'Oolong', alias: 'B' }, + { tea: 'Green', alias: 'C' } + ]; + matchSorter(tea, 'oo', { + keys: ['tea', { minRanking: matchSorter.rankings.EQUAL, key: 'alias' }] + }); + // minRanking bumps Milk up to EQUAL from CONTAINS (alias) + // Oolong matches as STARTS_WITH + // Green is missing due to no match + // [{tea: 'Milk', alias: 'moo'}, {tea: 'Oolong', alias: 'B'}] +} + +// # key: methods +{ + const tea = [ + { tea: 'Milk', alias: 'moo' }, + { tea: 'Oolong', alias: 'B' }, + { tea: 'Green', alias: 'C' } + ]; + matchSorter(tea, 'oo', { + keys: [ + item => item.tea, + { minRanking: matchSorter.rankings.EQUAL, key: item => item.alias } + ] + }); + // minRanking bumps Milk up to EQUAL from CONTAINS (alias) + // Oolong matches as STARTS_WITH + // Green is missing due to no match + // [{tea: 'Milk', alias: 'moo'}, {tea: 'Oolong', alias: 'B'}] } // ## threshold: number { - const fruit = ['orange', 'apple', 'grape', 'banana']; - matchSorter(fruit, 'ap', {threshold: matchSorter.rankings.NO_MATCH}); - // ['apple', 'grape', 'orange', 'banana'] (returns all items, just sorted by best match) + const fruit = ['orange', 'apple', 'grape', 'banana']; + matchSorter(fruit, 'ap', { threshold: matchSorter.rankings.NO_MATCH }); + // ['apple', 'grape', 'orange', 'banana'] (returns all items, just sorted by best match) - const things = ['google', 'airbnb', 'apple', 'apply', 'app']; - matchSorter(things, 'app', {threshold: matchSorter.rankings.EQUAL}); - // ['app'] (only items that are equal) + const things = ['google', 'airbnb', 'apple', 'apply', 'app']; + matchSorter(things, 'app', { threshold: matchSorter.rankings.EQUAL }); + // ['app'] (only items that are equal) - const otherThings = ['fiji apple', 'google', 'app', 'crabapple', 'apple', 'apply']; - matchSorter(otherThings, 'app', {threshold: matchSorter.rankings.WORD_STARTS_WITH}); - // ['app', 'apple', 'apply', 'fiji apple'] (everything that matches with "word starts with" or better) + const otherThings = [ + 'fiji apple', + 'google', + 'app', + 'crabapple', + 'apple', + 'apply' + ]; + matchSorter(otherThings, 'app', { + threshold: matchSorter.rankings.WORD_STARTS_WITH + }); + // ['app', 'apple', 'apply', 'fiji apple'] (everything that matches with "word starts with" or better) } // ## keepDiacritics: boolean { - const thingsWithDiacritics = [ - 'jalapeño', - 'à la carte', - 'café', - 'papier-mâché', - 'à la mode', - ]; - matchSorter(thingsWithDiacritics, 'aa'); - // ['jalapeño', 'à la carte', 'à la mode', 'papier-mâché'] + const thingsWithDiacritics = [ + 'jalapeño', + 'à la carte', + 'café', + 'papier-mâché', + 'à la mode' + ]; + matchSorter(thingsWithDiacritics, 'aa'); + // ['jalapeño', 'à la carte', 'à la mode', 'papier-mâché'] - matchSorter(thingsWithDiacritics, 'aa', {keepDiacritics: true}); - // ['jalapeño', 'à la carte'] + matchSorter(thingsWithDiacritics, 'aa', { keepDiacritics: true }); + // ['jalapeño', 'à la carte'] - matchSorter(thingsWithDiacritics, 'à', {keepDiacritics: true}); - // ['à la carte', 'à la mode'] + matchSorter(thingsWithDiacritics, 'à', { keepDiacritics: true }); + // ['à la carte', 'à la mode'] } diff --git a/types/material-components-web/index.d.ts b/types/material-components-web/index.d.ts index f1f9874f4b..9e3ca568f1 100644 --- a/types/material-components-web/index.d.ts +++ b/types/material-components-web/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Material Components Web 0.35 +// Type definitions for Material Components Web 0.43 // Project: https://material.io/components/ -// Definitions by: Brent Douglas , Collin Kostichuk +// Definitions by: Brent Douglas , Collin Kostichuk , Arthur Groupp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -25,6 +25,7 @@ import * as base from 'material__base'; import * as checkbox from 'material__checkbox'; import * as chips from 'material__chips'; import * as dialog from 'material__dialog'; +import * as dom from 'material__dom'; import * as drawer from 'material__drawer'; import * as floatingLabel from 'material__floating-label'; import * as formField from 'material__form-field'; @@ -32,6 +33,7 @@ import * as gridList from 'material__grid-list'; import * as iconToggle from 'material__icon-toggle'; import * as linearProgress from 'material__linear-progress'; import * as lineRipple from 'material__line-ripple'; +import * as list from 'material__list'; import * as menu from 'material__menu'; import * as notchedOutline from 'material__notched-outline'; import * as radio from 'material__radio'; diff --git a/types/material__dom/index.d.ts b/types/material__dom/index.d.ts new file mode 100644 index 0000000000..f751696f43 --- /dev/null +++ b/types/material__dom/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for Material Components Web 0.43 +// Project: https://material.io/components/ +// Definitions by: Arthur Groupp +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/** + * @license + * Copyright 2018 Google Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import * as ponyfill from './ponyfill'; + +export {ponyfill}; diff --git a/types/material__dom/ponyfill.d.ts b/types/material__dom/ponyfill.d.ts new file mode 100644 index 0000000000..9725e2704d --- /dev/null +++ b/types/material__dom/ponyfill.d.ts @@ -0,0 +1,2 @@ +export function closest(element: Element, selector: string): Element; +export function matches(element: Element, selector: string): boolean; diff --git a/types/material__dom/tsconfig.json b/types/material__dom/tsconfig.json new file mode 100644 index 0000000000..3f76866c9d --- /dev/null +++ b/types/material__dom/tsconfig.json @@ -0,0 +1,25 @@ +{ + "files": [ + "index.d.ts", + "ponyfill.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/material__dom/tslint.json b/types/material__dom/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/material__dom/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/material__drawer/adapter.d.ts b/types/material__drawer/adapter.d.ts new file mode 100644 index 0000000000..84413fe004 --- /dev/null +++ b/types/material__drawer/adapter.d.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright 2018 Google Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/* eslint no-unused-vars: [2, {"args": "none"}] */ + +/** + * Adapter for MDC Drawer + * + * Defines the shape of the adapter expected by the foundation. Implement this + * adapter to integrate the Drawer into your framework. See + * https://github.com/material-components/material-components-web/blob/master/docs/authoring-components.md + * for more information. + * + * @record + */ +export class MDCDrawerAdapter { + /** + * Adds a class to the root Element. + */ + addClass(className: string): void; + + /** + * Removes a class from the root Element. + */ + removeClass(className: string): void; + + /** + * Returns true if the root Element contains the given class. + */ + hasClass(className: string): boolean; + + elementHasClass(element: Element, className: string): void; + + /** + * Saves the focus of currently active element. + */ + saveFocus(): void; + + /** + * Restores focus to element previously saved with 'saveFocus'. + */ + restoreFocus(): void; + + /** + * Focuses the active / selected navigation item. + */ + focusActiveNavigationItem(): void; + + /** + * Emits a custom event "MDCDrawer:closed" denoting the drawer has closed. + */ + notifyClose(): void; + + /** + * Emits a custom event "MDCDrawer:opened" denoting the drawer has opened. + */ + notifyOpen(): void; + + /** + * Traps focus on root element and focuses the active navigation element. + */ + trapFocus(): void; + + /** + * Releases focus trap from root element which was set by `trapFocus` + * and restores focus to where it was prior to calling `trapFocus`. + */ + releaseFocus(): void; +} diff --git a/types/material__drawer/persistent/constants.d.ts b/types/material__drawer/constants.d.ts similarity index 64% rename from types/material__drawer/persistent/constants.d.ts rename to types/material__drawer/constants.d.ts index 84dcce7f3f..d094c3240b 100644 --- a/types/material__drawer/persistent/constants.d.ts +++ b/types/material__drawer/constants.d.ts @@ -17,14 +17,18 @@ import { MDCStrings } from 'material__base'; export interface cssClasses extends MDCStrings { - ROOT: 'mdc-drawer--persistent'; + ROOT: 'mdc-drawer'; + DISMISSIBLE: 'mdc-drawer--dismissible'; + MODAL: 'mdc-drawer--modal'; OPEN: 'mdc-drawer--open'; - ANIMATING: 'mdc-drawer--animating'; + ANIMATE: 'mdc-drawer--animate'; + OPENING: 'mdc-drawer--opening'; + CLOSING: 'mdc-drawer--closing'; } export interface strings extends MDCStrings { - DRAWER_SELECTOR: '.mdc-drawer--persistent .mdc-drawer__drawer'; - FOCUSABLE_ELEMENTS: 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex], [contenteditable]'; - OPEN_EVENT: 'MDCPersistentDrawer:open'; - CLOSE_EVENT: 'MDCPersistentDrawer:close'; + APP_CONTENT_SELECTOR: '.mdc-drawer-app-content'; + SCRIM_SELECTOR: '.mdc-drawer-scrim'; + CLOSE_EVENT: 'MDCDrawer:closed'; + OPEN_EVENT: 'MDCDrawer:opened'; } diff --git a/types/material__drawer/dismissible/foundation.d.ts b/types/material__drawer/dismissible/foundation.d.ts new file mode 100644 index 0000000000..4bee751d86 --- /dev/null +++ b/types/material__drawer/dismissible/foundation.d.ts @@ -0,0 +1,71 @@ +/** + * @license + * Copyright 2018 Google Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import { MDCDrawerAdapter } from '../adapter'; +import MDCFoundation from 'material__base/foundation'; +import { cssClasses, strings } from '../constants'; + +export class MDCDismissibleDrawerFoundation extends MDCFoundation { + static readonly strings: strings; + static readonly cssClasses: cssClasses; + static readonly defaultAdapter: MDCDrawerAdapter; + + constructor(adapter: MDCDrawerAdapter); + + destroy(): void; + + /** + * Function to open the drawer. + */ + open(): void; + + /** + * Function to close the drawer. + */ + close(): void; + + /** + * Returns true if drawer is in open state. + */ + isOpen(): boolean; + + /** + * Returns true if drawer is animating open. + */ + isOpening(): boolean; + + /** + * Returns true if drawer is animating closed. + */ + isClosing(): boolean; + + /** + * Keydown handler to close drawer when key is escape. + */ + handleKeydown(evt: KeyboardEvent): void; + + /** + * Handles a transition end event on the root element. + */ + handleTransitionEnd(evt: Event): void; +} diff --git a/types/material__drawer/focus-trap.d.ts b/types/material__drawer/focus-trap.d.ts new file mode 100644 index 0000000000..61ceb8fb08 --- /dev/null +++ b/types/material__drawer/focus-trap.d.ts @@ -0,0 +1,81 @@ +/** + * A DOM node, a selector string (which will be passed to + * `document.querySelector()` to find the DOM node), or a function that + * returns a DOM node. + */ +export type FocusTarget = HTMLElement | string | { (): HTMLElement }; + +export interface Options { + /** + * A function that will be called when the focus trap activates. + */ + onActivate?: () => void; + + /** + * A function that will be called when the focus trap deactivates. + */ + onDeactivate?: () => void; + + /** + * By default, when a focus trap is activated the first element in the + * focus trap's tab order will receive focus. With this option you can + * specify a different element to receive that initial focus. + */ + initialFocus?: FocusTarget; + + /** + * By default, an error will be thrown if the focus trap contains no + * elements in its tab order. With this option you can specify a + * fallback element to programmatically receive focus if no other + * tabbable elements are found. For example, you may want a popover's + * `
` to receive focus if the popover's content includes no + * tabbable elements. *Make sure the fallback element has a negative + * `tabindex` so it can be programmatically focused.* + */ + fallbackFocus?: FocusTarget; + + /** + * Default: `true`. If `false`, when the trap is deactivated, + * focus will *not* return to the element that had focus before activation. + */ + returnFocusOnDeactivate?: boolean; + + /** + * Default: `true`. If `false`, the `Escape` key will not trigger + * deactivation of the focus trap. This can be useful if you want + * to force the user to make a decision instead of allowing an easy + * way out. + */ + escapeDeactivates?: boolean; + + /** + * Default: `false`. If `true`, a click outside the focus trap will + * deactivate the focus trap and allow the click event to do its thing. + */ + clickOutsideDeactivates?: boolean; +} + +export type ActivateOptions = Pick; + +export interface DeactivateOptions extends Pick { + returnFocus?: boolean; +} + +export interface FocusTrap { + activate(activateOptions?: ActivateOptions): void; + deactivate(deactivateOptions?: DeactivateOptions): void; + pause(): void; + unpause(): void; +} + +/** + * Returns a new focus trap on `element`. + * + * @param element + * The element to be the focus trap, or a selector that will be used to + * find the element. + */ +export default function focusTrap( + element: HTMLElement | string, + userOptions?: Options +): FocusTrap; diff --git a/types/material__drawer/index.d.ts b/types/material__drawer/index.d.ts index 63cd5d8fda..9980f1c304 100644 --- a/types/material__drawer/index.d.ts +++ b/types/material__drawer/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Material Components Web 0.35 +// Type definitions for Material Components Web 0.43 // Project: https://material.io/components/ -// Definitions by: Brent Douglas , Collin Kostichuk +// Definitions by: Brent Douglas , Collin Kostichuk , Arthur Groupp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -20,8 +20,31 @@ * limitations under the License. */ +import MDCComponent from 'material__base/component'; +import { MDCDismissibleDrawerFoundation } from './dismissible/foundation'; +import { MDCModalDrawerFoundation } from './modal/foundation'; +import { MDCDrawerAdapter } from './adapter'; +import { MDCList, MDCListFoundation } from 'material__list/index'; +import { strings } from './constants'; import * as util from './util'; -export { MDCSlidableDrawerAdapter } from './slidable'; -export { MDCTemporaryDrawer, MDCTemporaryDrawerFoundation } from './temporary'; -export { MDCPersistentDrawer, MDCPersistentDrawerFoundation } from './persistent'; -export { util }; +import createFocusTrap, { FocusTrap } from './focus-trap'; + +export class MDCDrawer extends MDCComponent { + constructor(...args: any[]); + static attachTo(root: Element): MDCDrawer; + + /** + * Returns true if drawer is in the open position. + */ + open: boolean; + + initialize(focusTrapFactory: FocusTrap, listFactory: MDCList): void; + + initialSyncWithDOM(): void; + + destroy(): void; + + getDefaultFoundation(): MDCDismissibleDrawerFoundation | MDCModalDrawerFoundation; +} + +export { MDCDismissibleDrawerFoundation, MDCModalDrawerFoundation, util }; diff --git a/types/material__drawer/modal/foundation.d.ts b/types/material__drawer/modal/foundation.d.ts new file mode 100644 index 0000000000..36ffb30e08 --- /dev/null +++ b/types/material__drawer/modal/foundation.d.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright 2018 Google Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import { MDCDrawerAdapter } from '../adapter'; +import { MDCDismissibleDrawerFoundation } from '../dismissible/foundation'; + +export class MDCModalDrawerFoundation extends MDCDismissibleDrawerFoundation { + /** + * Called when drawer finishes open animation. + */ + opened(): void; + + /** + * Called when drawer finishes close animation. + */ + closed(): void; + + /** + * Handles click event on scrim. + */ + handleScrimClick(): void; +} diff --git a/types/material__drawer/persistent/foundation.d.ts b/types/material__drawer/persistent/foundation.d.ts deleted file mode 100644 index ce596f3c23..0000000000 --- a/types/material__drawer/persistent/foundation.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { MDCSlidableDrawerAdapter, MDCSlidableDrawerFoundation } from '../slidable'; -import { cssClasses, strings } from './constants'; - -export default class MDCPersistentDrawerFoundation extends MDCSlidableDrawerFoundation { - static readonly cssClasses: cssClasses; - - static readonly strings: strings; - - static readonly defaultAdapter: MDCSlidableDrawerAdapter; -} diff --git a/types/material__drawer/persistent/index.d.ts b/types/material__drawer/persistent/index.d.ts deleted file mode 100644 index 920258b2aa..0000000000 --- a/types/material__drawer/persistent/index.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { MDCComponent } from 'material__base'; -import MDCPersistentDrawerFoundation from './foundation'; -import { MDCSlidableDrawerAdapter } from '../slidable'; -import * as util from '../util'; - -export {MDCSlidableDrawerAdapter, MDCPersistentDrawerFoundation, util}; - -export class MDCPersistentDrawer extends MDCComponent { - static attachTo(root: Element): MDCPersistentDrawer; - - open: boolean; - - // Return the drawer element inside the component. - readonly drawer: Element | null; -} diff --git a/types/material__drawer/slidable/adapter.d.ts b/types/material__drawer/slidable/adapter.d.ts deleted file mode 100644 index 3659742558..0000000000 --- a/types/material__drawer/slidable/adapter.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export interface MDCSlidableDrawerAdapter { - addClass(className: string): void; - - removeClass(className: string): void; - - hasClass(className: string): void; - - hasNecessaryDom(): boolean; - - registerInteractionHandler(evt: string, handler: EventListener): void; - - deregisterInteractionHandler(evt: string, handler: EventListener): void; - - registerDrawerInteractionHandler(evt: string, handler: EventListener): void; - - deregisterDrawerInteractionHandler(evt: string, handler: EventListener): void; - - registerTransitionEndHandler(handler: EventListener): void; - - deregisterTransitionEndHandler(handler: EventListener): void; - - registerDocumentKeydownHandler(handler: EventListener): void; - - deregisterDocumentKeydownHandler(handler: EventListener): void; - - setTranslateX(value: number | null): void; - - getFocusableElements(): NodeList; - - saveElementTabState(el: Element): void; - - restoreElementTabState(el: Element): void; - - makeElementUntabbable(el: Element): void; - - notifyOpen(): void; - - notifyClose(): void; - - isRtl(): boolean; - - getDrawerWidth(): number; -} diff --git a/types/material__drawer/slidable/constants.d.ts b/types/material__drawer/slidable/constants.d.ts deleted file mode 100644 index bfae67fa90..0000000000 --- a/types/material__drawer/slidable/constants.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export const FOCUSABLE_ELEMENTS: string; diff --git a/types/material__drawer/slidable/foundation.d.ts b/types/material__drawer/slidable/foundation.d.ts deleted file mode 100644 index 60995e0a95..0000000000 --- a/types/material__drawer/slidable/foundation.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { MDCFoundation } from 'material__base'; -import { MDCSlidableDrawerAdapter } from './adapter'; - -export class MDCSlidableDrawerFoundation extends MDCFoundation { - static readonly defaultAdapter: MDCSlidableDrawerAdapter; - - constructor(adapter: MDCSlidableDrawerAdapter, rootCssClass: string, animatingCssClass: string, openCssClass: string); - - open(): void; - - close(): void; - - isOpen(): boolean; -} diff --git a/types/material__drawer/slidable/index.d.ts b/types/material__drawer/slidable/index.d.ts deleted file mode 100644 index a41d83ad4b..0000000000 --- a/types/material__drawer/slidable/index.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { FOCUSABLE_ELEMENTS } from './constants'; -export { MDCSlidableDrawerFoundation } from './foundation'; -export { MDCSlidableDrawerAdapter } from './adapter'; diff --git a/types/material__drawer/temporary/constants.d.ts b/types/material__drawer/temporary/constants.d.ts deleted file mode 100644 index ef00408a31..0000000000 --- a/types/material__drawer/temporary/constants.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { MDCStrings } from 'material__base'; - -export interface cssClasses extends MDCStrings { - ROOT: 'mdc-drawer--temporary'; - OPEN: 'mdc-drawer--open'; - ANIMATING: 'mdc-drawer--animating'; - SCROLL_LOCK: 'mdc-drawer-scroll-lock'; -} - -export interface strings extends MDCStrings { - DRAWER_SELECTOR: '.mdc-drawer--temporary .mdc-drawer__drawer'; - OPACITY_VAR_NAME: '--mdc-temporary-drawer-opacity'; - FOCUSABLE_ELEMENTS: 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex], [contenteditable]'; - OPEN_EVENT: 'MDCTemporaryDrawer:open'; - CLOSE_EVENT: 'MDCTemporaryDrawer:close'; -} diff --git a/types/material__drawer/temporary/foundation.d.ts b/types/material__drawer/temporary/foundation.d.ts deleted file mode 100644 index adb78d0296..0000000000 --- a/types/material__drawer/temporary/foundation.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { MDCSlidableDrawerFoundation, MDCSlidableDrawerAdapter } from '../slidable'; -import { cssClasses, strings } from './constants'; - -export default class MDCTemporaryDrawerFoundation extends MDCSlidableDrawerFoundation { - static readonly cssClasses: cssClasses; - - static readonly strings: strings; - - static readonly defaultAdapter: MDCSlidableDrawerAdapter; - - open(): void; - - close(): void; -} diff --git a/types/material__drawer/temporary/index.d.ts b/types/material__drawer/temporary/index.d.ts deleted file mode 100644 index c6dd1c9928..0000000000 --- a/types/material__drawer/temporary/index.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { MDCComponent } from 'material__base'; -import MDCTemporaryDrawerFoundation from './foundation'; -import { MDCSlidableDrawerAdapter } from '../slidable'; -import * as util from '../util'; - -export {MDCSlidableDrawerAdapter, MDCTemporaryDrawerFoundation, util}; - -export class MDCTemporaryDrawer extends MDCComponent { - static attachTo(root: Element): MDCTemporaryDrawer; - - open: boolean; - - /* Return the drawer element inside the component. */ - readonly drawer: Element | null; -} diff --git a/types/material__drawer/tsconfig.json b/types/material__drawer/tsconfig.json index 3e2a955de5..2f43565e69 100644 --- a/types/material__drawer/tsconfig.json +++ b/types/material__drawer/tsconfig.json @@ -1,16 +1,11 @@ { "files": [ - "persistent/constants.d.ts", - "persistent/index.d.ts", - "persistent/foundation.d.ts", - "slidable/constants.d.ts", - "slidable/adapter.d.ts", - "slidable/index.d.ts", - "slidable/foundation.d.ts", - "temporary/constants.d.ts", - "temporary/index.d.ts", - "temporary/foundation.d.ts", + "dismissible/foundation.d.ts", + "modal/foundation.d.ts", "util.d.ts", + "adapter.d.ts", + "constants.d.ts", + "focus-trap.d.ts", "index.d.ts" ], "compilerOptions": { @@ -32,4 +27,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/types/material__drawer/util.d.ts b/types/material__drawer/util.d.ts index 052af84e48..fcce26d915 100644 --- a/types/material__drawer/util.d.ts +++ b/types/material__drawer/util.d.ts @@ -14,22 +14,6 @@ * limitations under the License. */ -// Remap touch events to pointer events, if the browser doesn't support touch events. -export function remapEvent(eventName: string, globalObj?: Window): string; +import { FocusTrap } from './focus-trap'; -// Choose the correct transform property to use on the current browser. -export function getTransformPropertyName(globalObj?: Window, forceRefresh?: boolean): string; - -// Determine whether the current browser supports CSS properties. -export function supportsCssCustomProperties(globalObj?: Window): boolean; - -// Determine whether the current browser supports passive event listeners, and if so, use them. -export function applyPassive(globalObj?: Window, forceRefresh?: boolean): boolean | { passive: boolean; }; - -// Save the tab state for an element. -// tslint:disable-next-line:void-return -export function saveElementTabState(el: Element): void; - -// Restore the tab state for an element, if it was saved. -// tslint:disable-next-line:void-return -export function restoreElementTabState(el: Element): void; +export function createFocusTrapInstance(surfaceEl: Element, focusTrapFactory: () => FocusTrap): FocusTrap; diff --git a/types/material__list/adapter.d.ts b/types/material__list/adapter.d.ts new file mode 100644 index 0000000000..3a1b5522d8 --- /dev/null +++ b/types/material__list/adapter.d.ts @@ -0,0 +1,49 @@ +export class MDCListAdapter { + getListItemCount(): number; + getFocusedElementIndex(): number; + setAttributeForElementIndex(index: number, attribute: string, value: string): void; + removeAttributeForElementIndex(index: number, attribute: string): void; + addClassForElementIndex(index: number, className: string): void; + removeClassForElementIndex(index: number, className: string): void; + + /** + * Focuses list item at the index specified. + */ + focusItemAtIndex(index: number): void; + + /** + * Sets the tabindex to the value specified for all button/a element children of + * the list item at the index specified. + */ + setTabIndexForListItemChildren(listItemIndex: number, tabIndexValue: number): void; + + /** + * If the given element has an href, follows the link. + */ + followHref(ele: HTMLAnchorElement): void; + + /** + * Returns true if radio button is present at given list item index. + */ + hasRadioAtIndex(index: number): boolean; + + /** + * Returns true if checkbox is present at given list item index. + */ + hasCheckboxAtIndex(index: number): boolean; + + /** + * Returns true if checkbox inside a list item is checked. + */ + isCheckboxCheckedAtIndex(index: number): boolean; + + /** + * Sets the checked status of checkbox or radio at given list item index. + */ + setCheckedCheckboxOrRadioAtIndex(index: number, isChecked: boolean): void; + + /** + * Returns true when the current focused element is inside list root. + */ + isFocusInsideList(): boolean; +} diff --git a/types/material__list/constants.d.ts b/types/material__list/constants.d.ts new file mode 100644 index 0000000000..f8d0d67273 --- /dev/null +++ b/types/material__list/constants.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2018 Google Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import { MDCStrings } from 'material__base'; + +export interface cssClasses extends MDCStrings { + ROOT: 'mdc-list'; + LIST_ITEM_CLASS: 'mdc-list-item'; + LIST_ITEM_SELECTED_CLASS: 'mdc-list-item--selected'; + LIST_ITEM_ACTIVATED_CLASS: 'mdc-list-item--activated'; +} + +export interface strings extends MDCStrings { + ARIA_ORIENTATION: 'aria-orientation'; + ARIA_ORIENTATION_HORIZONTAL: 'horizontal'; + ARIA_SELECTED: 'aria-selected'; + ARIA_CHECKED: 'aria-checked'; + ARIA_CHECKED_RADIO_SELECTOR: '[role="radio"][aria-checked="true"]'; + ARIA_ROLE_CHECKBOX_SELECTOR: '[role="checkbox"]'; + ARIA_CHECKED_CHECKBOX_SELECTOR: '[role="checkbox"][aria-checked="true"]'; + RADIO_SELECTOR: 'input[type="radio"]:not(:disabled)'; + CHECKBOX_SELECTOR: 'input[type="checkbox"]:not(:disabled)'; + CHECKBOX_RADIO_SELECTOR: 'input[type="checkbox"]:not(:disabled), input[type="radio"]:not(:disabled)'; + CHILD_ELEMENTS_TO_TOGGLE_TABINDEX: '.mdc-list-item button:not(:disabled), .mdc-list-item a'; + FOCUSABLE_CHILD_ELEMENTS: '.mdc-list-item button:not(:disabled), .mdc-list-item a, .mdc-list-item input[type="radio"]:not(:disabled), .mdc-list-item input[type="checkbox"]:not(:disabled)'; + ENABLED_ITEMS_SELECTOR: '.mdc-list-item:not(.mdc-list-item--disabled)'; +} + +export type Index = number | number[]; diff --git a/types/material__list/foundation.d.ts b/types/material__list/foundation.d.ts new file mode 100644 index 0000000000..3823d796ca --- /dev/null +++ b/types/material__list/foundation.d.ts @@ -0,0 +1,72 @@ +import MDCFoundation from 'material__base/foundation'; +import { MDCListAdapter } from './adapter'; +import { strings, cssClasses, Index } from './constants'; + +export const ELEMENTS_KEY_ALLOWED_IN: string[]; + +export class MDCListFoundation extends MDCFoundation { + static readonly strings: strings; + static readonly cssClasses: cssClasses; + static readonly defaultAdapter: MDCListAdapter; + constructor(adapter: MDCListAdapter); + + layout(): void; + + /** + * Sets the private wrapFocus_ variable. + */ + setWrapFocus(value: boolean): void; + + /** + * Sets the isVertical_ private variable. + */ + setVerticalOrientation(value: boolean): void; + + /** + * Sets the isSingleSelectionList_ private variable. + */ + setSingleSelection(value: boolean): void; + + /** + * Sets the useActivatedClass_ private variable. + */ + setUseActivatedClass(useActivated: boolean): void; + + getSelectedIndex(): Index; + + setSelectedIndex(index: Index): void; + + /** + * Focus in handler for the list items. + */ + handleFocusIn(evt: Event, listItemIndex: number): void; + + /** + * Focus out handler for the list items. + */ + handleFocusOut(evt: Event, listItemIndex: number): void; + + /** + * Key handler for the list. + */ + handleKeydown(evt: Event, isRootListItem: boolean, listItemIndex: number): void; + + /** + * Click handler for the list. + */ + handleClick(index: number, toggleCheckbox: boolean): void; + + /** + * Focuses the next element on the list. + */ + focusNextElement(index: number): number; + + /** + * Focuses the previous element on the list. + */ + focusPrevElement(index: number): number; + + focusFirstElement(): number; + + focusLastElement(): number; +} diff --git a/types/material__list/index.d.ts b/types/material__list/index.d.ts new file mode 100644 index 0000000000..22adf832f3 --- /dev/null +++ b/types/material__list/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for Material Components Web 0.43 +// Project: https://material.io/components/ +// Definitions by: Arthur Groupp +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/** + * @license + * Copyright 2016 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import MDCComponent from 'material__base/component'; +import { MDCListFoundation } from './foundation'; +import { MDCListAdapter } from './adapter'; +import { matches } from 'material__dom/ponyfill'; +import { cssClasses, strings, Index } from './constants'; // eslint-disable-line no-unused-vars + +export class MDCList { + constructor(...args: any[]); + static attachTo(root: Element): MDCList; + + destroy(): void; + + initialSyncWithDOM(): void; + + layout(): void; + + /** + * Initialize selectedIndex value based on pre-selected checkbox list items, single selection or radio. + */ + initializeListType(): void; + + vertical: boolean; + readonly listElements: Element[]; + wrapFocus: boolean; + singleSelection: boolean; + selectedIndex: Index; + + getDefaultFoundation(): MDCListFoundation; +} + +export { MDCListFoundation}; diff --git a/types/material__list/tsconfig.json b/types/material__list/tsconfig.json new file mode 100644 index 0000000000..915f471053 --- /dev/null +++ b/types/material__list/tsconfig.json @@ -0,0 +1,27 @@ +{ + "files": [ + "index.d.ts", + "foundation.d.ts", + "adapter.d.ts", + "constants.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/material__list/tslint.json b/types/material__list/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/material__list/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index a8ec6114eb..c72ca68941 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1299,8 +1299,8 @@ declare namespace math { * traversed. The function must return a boolean. */ filter( - x: Matrix | MathArray, - test: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray) | RegExp + x: Matrix | MathArray | string[], + test: ((value: any, index: any, matrix: Matrix | MathArray | string[]) => boolean) | RegExp ): Matrix | MathArray; /** diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 0d21be817e..15d455e427 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -281,6 +281,12 @@ Matrices examples return value * value; }); // returns [1, 4, 9] } + + // filter matrix + { + math.filter([6, -2, -1, 4, 3], function(x) { return x > 0; }); // returns [6, 4, 3] + math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/); // returns ["23", "100", "55"] + } } /* diff --git a/types/memorystream/index.d.ts b/types/memorystream/index.d.ts new file mode 100644 index 0000000000..7ebdddf4bc --- /dev/null +++ b/types/memorystream/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for memorystream 0.3 +// Project: https://github.com/JSBizon/node-memorystream +// Definitions by: bangbang93 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +import { Stream, Duplex } from "stream"; + +type DataType = string | Buffer | Stream; + +interface Options { + readable: boolean; + writeable: boolean; + maxbufsize: number; + bufoverflow: number; + frequence: number; +} + +declare class MemoryStream extends Duplex { + constructor( + data?: DataType | DataType[], + options?: Options, + ); +} + +export = MemoryStream; diff --git a/types/memorystream/memorystream-tests.ts b/types/memorystream/memorystream-tests.ts new file mode 100644 index 0000000000..728e032d88 --- /dev/null +++ b/types/memorystream/memorystream-tests.ts @@ -0,0 +1,8 @@ +import MemoryStream = require('memorystream'); +import { createReadStream } from 'fs'; + +const ms = new MemoryStream(); + +createReadStream('index.ts').pipe(ms); +ms.pipe(process.stdout); +ms.write('it works'); diff --git a/types/memorystream/tsconfig.json b/types/memorystream/tsconfig.json new file mode 100644 index 0000000000..200326520a --- /dev/null +++ b/types/memorystream/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", + "memorystream-tests.ts" + ] +} diff --git a/types/memorystream/tslint.json b/types/memorystream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/memorystream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mnemonic-words/index.d.ts b/types/mnemonic-words/index.d.ts new file mode 100644 index 0000000000..4ce91c08d6 --- /dev/null +++ b/types/mnemonic-words/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for mnemonic-words 1.0 +// Project: https://github.com/sindresorhus/mnemonic-words#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = mnemonicWords; + +declare const mnemonicWords: string[]; diff --git a/types/mnemonic-words/mnemonic-words-tests.ts b/types/mnemonic-words/mnemonic-words-tests.ts new file mode 100644 index 0000000000..a3c5569c8c --- /dev/null +++ b/types/mnemonic-words/mnemonic-words-tests.ts @@ -0,0 +1,5 @@ +import mnemonicWords = require('mnemonic-words'); +import mnemonicWordsJson = require('mnemonic-words/words.json'); + +mnemonicWords; // $ExpectType string[] +mnemonicWordsJson; // $ExpectType string[] diff --git a/types/mnemonic-words/tsconfig.json b/types/mnemonic-words/tsconfig.json new file mode 100644 index 0000000000..44998ff2f3 --- /dev/null +++ b/types/mnemonic-words/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", + "words.json.d.ts", + "mnemonic-words-tests.ts" + ] +} diff --git a/types/mnemonic-words/tslint.json b/types/mnemonic-words/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mnemonic-words/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mnemonic-words/words.json.d.ts b/types/mnemonic-words/words.json.d.ts new file mode 100644 index 0000000000..2d95294802 --- /dev/null +++ b/types/mnemonic-words/words.json.d.ts @@ -0,0 +1,3 @@ +export = mnemonicWords; + +declare const mnemonicWords: string[]; diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 15e21d2b43..a3725382e4 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1022,7 +1022,7 @@ export type Condition = { $caseSensitive?: boolean; $diacraticSensitive?: boolean; }; - $where: Object; + $where?: Object; $geoIntersects?: Object; $geoWithin?: Object; $near?: Object; diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index ca8b7eac91..df4c1f7419 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -57,4 +57,5 @@ declare module 'mongoose' { } import mongoose = require('mongoose'); -export function _(schema: mongoose.Schema): void; +declare function _(schema: mongoose.Schema): void; +export = _; diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 14e965dd5f..9a29c8d347 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -15,6 +15,7 @@ // Norman Perrin // Dan Manastireanu // stablio +// Emmanuel Gautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -737,7 +738,7 @@ declare module "mongoose" { * section schema.js * http://mongoosejs.com/docs/api.html#schema-js */ - class Schema extends events.EventEmitter { + class Schema extends events.EventEmitter { /** * Schema constructor. * When nesting schemas, (children in the example above), always declare @@ -789,8 +790,10 @@ declare module "mongoose" { * Adds an instance method to documents constructed from Models compiled from this schema. * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. */ - method(method: string, fn: Function): this; - method(methodObj: { [name: string]: Function }): this; + method(method: F, fn: T[F]): this; + method(methodObj: { + [F in keyof T]: T[F] + }): this; /** * Gets/sets schema paths. @@ -954,7 +957,9 @@ declare module "mongoose" { static reserved: any; /** Object of currently defined methods on this schema. */ - methods: any; + methods: { + [F in keyof T]: T[F] + }; /** Object of currently defined statics on this schema. */ statics: any; /** Object of currently defined query helpers on this schema. */ @@ -1893,13 +1898,13 @@ declare module "mongoose" { * is an Array. See the examples. */ geometry(object: { type: string, coordinates: any[] }): this; - + /** * Returns the current query options as a JSON object. * @returns current query options */ getOptions(): any; - + /** * Returns the current query conditions as a JSON object. * @returns current query conditions @@ -2901,6 +2906,29 @@ declare module "mongoose" { distinct(field: string, conditions: any, callback?: (err: any, res: any[]) => void): Query & QueryHelpers; + /** + * Makes the indexes in MongoDB match the indexes defined in this model's + * schema. This function will drop any indexes that are not defined in + * the model's schema except the `_id` index, and build any indexes that + * are in your schema but not in MongoDB. + * @param options options to pass to `ensureIndexes()` + * @param callback optional callback + * @return Returns `undefined` if callback is specified, returns a promise if no callback. + */ + syncIndexes(options: object, callback?: (err: any) => void): void; + syncIndexes(options: object): Promise; + + /** + * Lists the indexes currently defined in MongoDB. This may or may not be + * the same as the indexes defined in your schema depending on whether you + * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you + * build indexes manually. + * @param cb optional callback + * @return Returns `undefined` if callback is specified, returns a promise if no callback. + */ + listIndexes(callback: (err: any) => void): void; + listIndexes(): Promise; + /** * Sends ensureIndex commands to mongo for each index declared in the schema. * @param options internal options diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 7d23e6be6b..865b45a64d 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -522,12 +522,15 @@ mongoose.Schema.reserved.hasOwnProperty(''); /* inherited properties */ schema.addListener('e', cb); /* practical examples */ -var animalSchema = new mongoose.Schema({ +interface Animal { + findSimilarTypes(cb: any): Promise +} +var animalSchema = new mongoose.Schema({ name: String, type: String }); -animalSchema.methods.findSimilarTypes = function (cb: any) { - return this.model('Aminal').find({ type: this.type }, cb); +animalSchema.methods.findSimilarTypes = function (cb) { + return this.model('Animal').find({ type: this.type }, cb); }; var Animal: any = mongoose.model('Animal', animalSchema); var dog: any = new Animal({type: 'dog'}); @@ -1633,6 +1636,10 @@ MongoModel.create([{ type: 'jelly bean' }, { MongoModel.distinct('url', { clicks: {$gt: 100}}, function (err, result) { }); MongoModel.distinct('url').exec(cb); +MongoModel.syncIndexes({}); +MongoModel.syncIndexes({}, cb); +MongoModel.listIndexes(); +MongoModel.listIndexes(cb); MongoModel.ensureIndexes({}, cb); MongoModel.find({ name: 'john', age: { $gte: 18 }}); MongoModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) { diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index e38317ae5d..24aeb75050 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for Mongoose 4.7.1 +// Type definitions for Mongoose 4.7.2 // Project: http://mongoosejs.com/ -// Definitions by: simonxca , horiuchi , lukasz-zak +// Definitions by: simonxca +// horiuchi +// lukasz-zak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/mousetrap/index.d.ts b/types/mousetrap/index.d.ts index d55559e3af..07e12a95c7 100644 --- a/types/mousetrap/index.d.ts +++ b/types/mousetrap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Mousetrap 1.6.x // Project: http://craig.is/killing/mice -// Definitions by: Dániel Tar +// Definitions by: Dániel Tar , Alan Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -10,7 +10,7 @@ interface ExtendedKeyboardEvent extends KeyboardEvent { interface MousetrapStatic { (el: Element): MousetrapInstance; - new (el: Element): MousetrapInstance; + new (el?: Element): MousetrapInstance; addKeycodes(keycodes: { [key: number]: string }): void; stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => boolean; bind(keys: string|string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; diff --git a/types/mousetrap/test/index.ts b/types/mousetrap/test/index.ts index fae472b76f..13d1ea5c36 100644 --- a/types/mousetrap/test/index.ts +++ b/types/mousetrap/test/index.ts @@ -49,7 +49,11 @@ Mousetrap.reset(); // event handler to the form element only, instead of the entire document. var element = document.querySelector('form'); var instance = new Mousetrap(element); -instance.bind('mod+s', function(){ console.log('Instance Saved'); }); +instance.bind('mod+s', function () { console.log('Instance Saved'); }); + +// Test that we can create an instance of mousetrap without passing element to the constructor. +var documentInstance = new Mousetrap(); +documentInstance.bind('mod+s', function () { console.log('documentInstance Saved'); }); // Test that the factory method works as well. Mousetrap(element).bind('mod+s', function(){ console.log('Factory Saved'); }); diff --git a/types/navigator-permissions/index.d.ts b/types/navigator-permissions/index.d.ts index a62c7f77ef..ba66b4cb46 100644 --- a/types/navigator-permissions/index.d.ts +++ b/types/navigator-permissions/index.d.ts @@ -21,9 +21,9 @@ declare namespace NavigatorPermissions { * Permission state values. */ type PermissionState = - 'granted' | - 'denied' | - 'prompt'; + 'granted' | + 'denied' | + 'prompt'; /** * The `PermissionStatus` interface of the Permissions API provides the state @@ -54,22 +54,22 @@ declare namespace NavigatorPermissions { * Permission name options. */ type PermissionName = - 'accelerometer' | - 'accessibility-events' | - 'ambient-light-sensor' | - 'background-sync' | - 'camera' | - 'clipboard-read' | - 'clipboard-write' | - 'geolocation' | - 'gyroscope' | - 'magnetometer' | - 'microphone' | - 'midi' | - 'notifications' | - 'payment-handler' | - 'persistent-storage' | - 'push'; + 'accelerometer' | + 'accessibility-events' | + 'ambient-light-sensor' | + 'background-sync' | + 'camera' | + 'clipboard-read' | + 'clipboard-write' | + 'geolocation' | + 'gyroscope' | + 'magnetometer' | + 'microphone' | + 'midi' | + 'notifications' | + 'payment-handler' | + 'persistent-storage' | + 'push'; /** * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query} @@ -103,31 +103,38 @@ declare namespace NavigatorPermissions { } // Map permission names to correctly typed descriptors. - interface NameDescriptorMap { - // ??? Question ???: - // Is there a better way to handle this case and remove repeated code, - // something like - // > { - // [n in N]: D; // this line to cover all basic cases - // // and the custom permission descriptors for midi and push - // } - 'accelerometer': PermissionDescriptor<'accelerometer'>; - 'accessibility-events': PermissionDescriptor<'accessibility-events'>; - 'ambient-light-sensor': PermissionDescriptor<'ambient-light-sensor'>; - 'background-sync': PermissionDescriptor<'background-sync'>; - 'camera': PermissionDescriptor<'camera'>; - 'clipboard-read': PermissionDescriptor<'clipboard-read'>; - 'clipboard-write': PermissionDescriptor<'clipboard-write'>; - 'geolocation': PermissionDescriptor<'geolocation'>; - 'gyroscope': PermissionDescriptor<'gyroscope'>; - 'magnetometer': PermissionDescriptor<'magnetometer'>; - 'microphone': PermissionDescriptor<'microphone'>; - 'notifications': PermissionDescriptor<'notifications'>; - 'payment-handler': PermissionDescriptor<'payment-handler'>; - 'persistent-storage': PermissionDescriptor<'persistent-storage'>; - // These permission descriptors support extra properties - 'midi': MidiPermissionDescriptor; - 'push': PushPermissionDescriptor; + interface QueryNameDescriptorMap { + // ??? Question ???: + // Is there a better way to handle this case and remove repeated code, + // something like + // > { + // [n in N]: D; // this line to cover all basic cases + // // and the custom permission descriptors for midi and push + // } + 'accelerometer': PermissionDescriptor<'accelerometer'>; + 'accessibility-events': PermissionDescriptor<'accessibility-events'>; + 'ambient-light-sensor': PermissionDescriptor<'ambient-light-sensor'>; + 'background-sync': PermissionDescriptor<'background-sync'>; + 'camera': PermissionDescriptor<'camera'>; + 'clipboard-read': PermissionDescriptor<'clipboard-read'>; + 'clipboard-write': PermissionDescriptor<'clipboard-write'>; + 'geolocation': PermissionDescriptor<'geolocation'>; + 'gyroscope': PermissionDescriptor<'gyroscope'>; + 'magnetometer': PermissionDescriptor<'magnetometer'>; + 'microphone': PermissionDescriptor<'microphone'>; + 'notifications': PermissionDescriptor<'notifications'>; + 'payment-handler': PermissionDescriptor<'payment-handler'>; + 'persistent-storage': PermissionDescriptor<'persistent-storage'>; + // These permission descriptors support extra properties + 'midi': MidiPermissionDescriptor; + 'push': PushPermissionDescriptor; + } + + interface RevokeNameDescriptorMap { + 'geolocation': PermissionDescriptor<'geolocation'>; + 'notifications': PermissionDescriptor<'notifications'>; + 'midi': MidiPermissionDescriptor; + 'push': PushPermissionDescriptor; } /** @@ -153,14 +160,14 @@ declare namespace NavigatorPermissions { * unsupported (e.g. `midi`, or `push` with `userVisibleOnly`). * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query} */ - query(permissionDescriptor: NameDescriptorMap[keyof NameDescriptorMap]): Promise; + query(permissionDescriptor: QueryNameDescriptorMap[keyof QueryNameDescriptorMap]): Promise; /** * The `Permissions.revoke()` method of the `Permissions` interface reverts a * currently set permission back to its default state, which is usually `prompt`. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/revoke} */ - revoke(permissionDescriptor: NameDescriptorMap[keyof NameDescriptorMap]): Promise; + revoke(permissionDescriptor: RevokeNameDescriptorMap[keyof RevokeNameDescriptorMap]): Promise; } /** diff --git a/types/navigator-permissions/navigator-permissions-tests.ts b/types/navigator-permissions/navigator-permissions-tests.ts index 918726b23d..e8722d72f0 100644 --- a/types/navigator-permissions/navigator-permissions-tests.ts +++ b/types/navigator-permissions/navigator-permissions-tests.ts @@ -43,3 +43,49 @@ function exampleIgnoreUndefinedCheck() { // Using the ! after permissions will let you bypass the undefined-check nav.permissions!.query({ name: 'microphone' }); } + +function exampleRevokeDoesNotSupportTheSameDescriptorsAsQuery() { + const cameraQueryPromise: Promise = nav.permissions!.query({ name: 'camera' }); + // Revoke only supports a subset of descriptors + // nav.permissions!.revoke({ name: 'camera' }); + // For example name: 'notifications' + const notificationRevocalPromise: Promise = nav.permissions!.revoke({ name: 'notifications' }); +} + +function exampleFromMdnForQueryMethod() { + if (nav.permissions === undefined) { + console.error('Permissions API not supported'); + return; + } + + function showLocalNewsWithGeolocation() { /* Not implemented */ } + function showButtonToEnableLocalNews() { /* Not implemented */ } + // Using .then instead of async-await + nav.permissions.query({ name: 'geolocation' }).then((result) => { + if (result.state === 'granted') { + showLocalNewsWithGeolocation(); + } else if (result.state === 'prompt') { + showButtonToEnableLocalNews(); + } + // Don't do anything if the permission was denied. + }); +} + +function exampleFromMdnForRevokeMethod() { + // Just an example report function I made up + function report(state: NavigatorPermissions.PermissionState) { + switch (state) { + case 'denied': console.error('State: DENIED'); break; + case 'granted': console.log('State: GRANTED'); break; + case 'prompt': console.info('State: PROMPT'); break; + // Using a string that's an invalid state would result in an error from TypeScript + // case 'invalid': console.warn('Type "invalid" is not comparable to type "PermissionState".'); + } + } + // This is a slightly modified example from the MDN revoke method documentation + // https://developer.mozilla.org/en-US/docs/Web/API/Permissions/revoke#Example + // Using .then instead of async-await + nav.permissions!.revoke({ name: 'geolocation' }).then((result) => { + report(result.state); + }); +} diff --git a/types/negative-zero/index.d.ts b/types/negative-zero/index.d.ts new file mode 100644 index 0000000000..80887bad0c --- /dev/null +++ b/types/negative-zero/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for negative-zero 2.0 +// Project: https://github.com/sindresorhus/negative-zero#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = negativeZero; + +declare function negativeZero(input: number): boolean; diff --git a/types/negative-zero/negative-zero-tests.ts b/types/negative-zero/negative-zero-tests.ts new file mode 100644 index 0000000000..d1ec33d84b --- /dev/null +++ b/types/negative-zero/negative-zero-tests.ts @@ -0,0 +1,3 @@ +import negativeZero = require('negative-zero'); + +negativeZero(-0); // $ExpectType boolean diff --git a/types/negative-zero/tsconfig.json b/types/negative-zero/tsconfig.json new file mode 100644 index 0000000000..e1bc860e6b --- /dev/null +++ b/types/negative-zero/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", + "negative-zero-tests.ts" + ] +} diff --git a/types/negative-zero/tslint.json b/types/negative-zero/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/negative-zero/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/new-github-issue-url/index.d.ts b/types/new-github-issue-url/index.d.ts new file mode 100644 index 0000000000..f784a0d85d --- /dev/null +++ b/types/new-github-issue-url/index.d.ts @@ -0,0 +1,81 @@ +// Type definitions for new-github-issue-url 0.1 +// Project: https://github.com/sindresorhus/new-github-issue-url#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export = newGithubIssueUrl; + +/** + * Returns a URL string. + */ +declare function newGithubIssueUrl(options: newGithubIssueUrl.Options): string; + +declare namespace newGithubIssueUrl { + type Without = { [P in Exclude]?: never }; + type XOR = (T | U) extends object ? (Without & U) | (Without & T) : T | U; + + type Options = XOR; + + interface BaseOptions { + /** + * The issue body. + */ + body?: string; + /** + * The issue title. + */ + title?: string; + /** + * Use an [issue template](https://help.github.com/articles/manually-creating-a-single-issue-template-for-your-repository). + * + * For example, if you want to use a template at `ISSUE_TEMPLATE/unicorn.md`, you would specify `unicorn.md` here. + */ + template?: string; + /** + * The labels for the issue. + * + * *Requires the user to have the permission to add labels.* + */ + labels?: string[]; + /** + * The milestone for the issue. + * + * *Requires the user to have the permission to add milestone.* + */ + milestone?: string; + /** + * The user to assign to the issue. + * + * *Requires the user to have the permission to add assignee.* + */ + assignee?: string; + /** + * The projects to add the issue to. + * + * The project reference format is `user/`, for example, if the URL to the project + * is `https://github.com/sindresorhus/some-repo/projects/3`, the project reference would be `some-repo/3`. + * + * *Requires the user to have the permission to add projects.* + */ + projects?: string[]; + } + + interface RepoUrlOptions extends BaseOptions { + /** + * The full URL to the repo. + */ + repoUrl: string; + } + + interface UserRepoOptions extends BaseOptions { + /** + * GitHub username or organization. + */ + user: string; + /** + * GitHub repo. + */ + repo: string; + } +} diff --git a/types/new-github-issue-url/new-github-issue-url-tests.ts b/types/new-github-issue-url/new-github-issue-url-tests.ts new file mode 100644 index 0000000000..c64b1aaa61 --- /dev/null +++ b/types/new-github-issue-url/new-github-issue-url-tests.ts @@ -0,0 +1,54 @@ +import newGithubIssueUrl = require('new-github-issue-url'); + +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-issue-url.git', +}); +// $ExpectType string +newGithubIssueUrl({ + user: 'sindresorhus', + repo: 'new-github-issue-url', +}); +// $ExpectError +newGithubIssueUrl({ + user: 'sindresorhus', +}); +// $ExpectError +newGithubIssueUrl({ + repo: 'new-github-issue-url', +}); +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + body: 'foo', +}); +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + title: 'foo', +}); +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + template: 'unicorn.md', +}); +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + labels: ['foo', 'bar'], +}); +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + milestone: 'foo', +}); +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + assignee: 'sindresorhus', +}); +// $ExpectType string +newGithubIssueUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + projects: ['some-repo/3'], +}); diff --git a/types/new-github-issue-url/tsconfig.json b/types/new-github-issue-url/tsconfig.json new file mode 100644 index 0000000000..3b1da7ee63 --- /dev/null +++ b/types/new-github-issue-url/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "new-github-issue-url-tests.ts" + ] +} diff --git a/types/new-github-issue-url/tslint.json b/types/new-github-issue-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/new-github-issue-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/new-github-release-url/index.d.ts b/types/new-github-release-url/index.d.ts new file mode 100644 index 0000000000..3b1be4b7f2 --- /dev/null +++ b/types/new-github-release-url/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for new-github-release-url 0.1 +// Project: https://github.com/sindresorhus/new-github-release-url#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export = newGithubReleaseUrl; + +/** + * Returns a URL string. + */ +declare function newGithubReleaseUrl(options: newGithubReleaseUrl.Options): string; + +declare namespace newGithubReleaseUrl { + type Without = { [P in Exclude]?: never }; + type XOR = (T | U) extends object ? (Without & U) | (Without & T) : T | U; + + type Options = XOR; + + interface BaseOptions { + /** + * The tag name of the release. + */ + tag?: string; + /** + * The branch name or commit SHA to point the release's tag at, if the tag doesn't already exist. + * @default The default branch + */ + target?: string; + /** + * The title of the release. + * GitHub shows the `tag` name when not specified. + */ + title?: string; + /** + * The description text of the release. + */ + body?: string; + /** + * Whether the release should be marked as a pre-release. + * @default false + */ + isPrerelease?: boolean; + } + + interface RepoUrlOptions extends BaseOptions { + /** + * The full URL to the repo. + */ + repoUrl: string; + } + + interface UserRepoOptions extends BaseOptions { + /** + * GitHub username or organization. + */ + user: string; + /** + * GitHub repo. + */ + repo: string; + } +} diff --git a/types/new-github-release-url/new-github-release-url-tests.ts b/types/new-github-release-url/new-github-release-url-tests.ts new file mode 100644 index 0000000000..9efe4e83db --- /dev/null +++ b/types/new-github-release-url/new-github-release-url-tests.ts @@ -0,0 +1,44 @@ +import newGithubReleaseUrl = require('new-github-release-url'); + +// $ExpectType string +newGithubReleaseUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', +}); +// $ExpectType string +newGithubReleaseUrl({ + user: 'sindresorhus', + repo: 'new-github-release-url', +}); +// $ExpectError +newGithubReleaseUrl({ + user: 'sindresorhus', +}); +// $ExpectError +newGithubReleaseUrl({ + repo: 'new-github-release-url', +}); +// $ExpectType string +newGithubReleaseUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + tag: 'foo', +}); +// $ExpectType string +newGithubReleaseUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + target: 'foo', +}); +// $ExpectType string +newGithubReleaseUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + title: 'foo', +}); +// $ExpectType string +newGithubReleaseUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + body: 'foo', +}); +// $ExpectType string +newGithubReleaseUrl({ + repoUrl: 'https://github.com/sindresorhus/new-github-release-url.git', + isPrerelease: true, +}); diff --git a/types/new-github-release-url/tsconfig.json b/types/new-github-release-url/tsconfig.json new file mode 100644 index 0000000000..62cf729db4 --- /dev/null +++ b/types/new-github-release-url/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "new-github-release-url-tests.ts" + ] +} diff --git a/types/new-github-release-url/tslint.json b/types/new-github-release-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/new-github-release-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next-server/dynamic.d.ts b/types/next-server/dynamic.d.ts index 38a85bf77e..2d06273bd5 100644 --- a/types/next-server/dynamic.d.ts +++ b/types/next-server/dynamic.d.ts @@ -31,7 +31,7 @@ type DynamicComponent

= React.ComponentType

& LoadableComponent; * https://github.com/zeit/next.js/blob/7.0.0/lib/dynamic.js#L55 */ declare function dynamic

( - options: AsyncComponent

| NextDynamicOptions

+ options: AsyncComponentLoader

| AsyncComponent

| NextDynamicOptions

): DynamicComponent

; declare function dynamic

( asyncModule: AsyncComponent

, diff --git a/types/next-server/test/next-server-dynamic-tests.tsx b/types/next-server/test/next-server-dynamic-tests.tsx index b6e0b86fe6..07844cad08 100644 --- a/types/next-server/test/next-server-dynamic-tests.tsx +++ b/types/next-server/test/next-server-dynamic-tests.tsx @@ -20,6 +20,10 @@ const LoadingComponent: React.StatelessComponent = ({ const DynamicComponent = dynamic(asyncComponent); const dynamicComponentJSX = ; +// 1.1 Basic Usage (Loader function) +const DynamicComponent2 = dynamic(() => asyncComponent); +const dynamicComponent2JSX = ; + // 2. With Custom Loading Component const DynamicComponentWithCustomLoading = dynamic(asyncComponent, { loading: LoadingComponent diff --git a/types/nock/index.d.ts b/types/nock/index.d.ts index afebacf1e5..958e97bc15 100644 --- a/types/nock/index.d.ts +++ b/types/nock/index.d.ts @@ -73,7 +73,7 @@ declare namespace nock { filteringRequestBody(regex: RegExp, replace: string): this; filteringRequestBody(fn: (body: string) => string): this; - log(out: () => void): this; + log(out: (message: any, ...optionalParams: any[]) => void): this; persist(flag?: boolean): this; shouldPersist(): boolean; replyContentLength(): this; diff --git a/types/node-emoji/index.d.ts b/types/node-emoji/index.d.ts index 5f4d050fb3..f07b12372c 100644 --- a/types/node-emoji/index.d.ts +++ b/types/node-emoji/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/omnidan/node-emoji#readme // Definitions by: Tristan Jones // styu +// rimiti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export const emoji: { @@ -1362,4 +1363,4 @@ export function unemojify(str: string): string; export function find(emoji: string): Emoji; export function hasEmoji(str: string): boolean; export function strip(str: string): string; -export function replace(str: string, callback: (emoji: Emoji) => string): string; +export function replace(str: string, replacement: ((emoji: Emoji) => string) | string, cleanSpaces?: boolean): string; diff --git a/types/node-emoji/node-emoji-tests.ts b/types/node-emoji/node-emoji-tests.ts index 918cb1e1f5..11e4788936 100644 --- a/types/node-emoji/node-emoji-tests.ts +++ b/types/node-emoji/node-emoji-tests.ts @@ -25,3 +25,7 @@ const hasEmoji: boolean = emoji.hasEmoji('🍕'); const stripped_emoji: string = emoji.strip('⚠️ 〰️ 〰️ low disk space'); const replaced_emoji: string = emoji.replace('⚠️ 〰️ 〰️ low disk space', (emoji) => `${emoji.key}:`); + +const replaced_emoji_with_string: string = emoji.replace('⚠️ 〰️ 〰️ low disk space', 'example'); + +const replaced_emoji_keep_spaces: string = emoji.replace('⚠️ 〰️ 〰️ low disk space', '', false); diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index d2fcddc2d9..1d9b0cb858 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -8,6 +8,7 @@ // Joe Flateau // Nikita Koryabkin // timhwang21 +// supaiku0 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -20,6 +21,7 @@ declare module "node-forge" { type Base64 = string; type Utf8 = string; type OID = string; + type Encoding = "raw" | "utf8"; namespace jsbn { class BigInteger { @@ -430,7 +432,7 @@ declare module "node-forge" { function decodeUtf8(encoded: Utf8): string; function createBuffer(): ByteBuffer; - function createBuffer(input: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer, encode: string): ByteBuffer; + function createBuffer(input: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer, encoding?: Encoding): ByteBuffer; namespace binary { namespace raw { @@ -516,10 +518,11 @@ declare module "node-forge" { function createSignedData(): PkcsSignedData; } + namespace pkcs5 { + function pbkdf2(password: string, salt: string, iterations: number, keySize: number): string; + } + namespace md { - - type Encoding = "raw" | "utf8" - interface MessageDigest { update(msg: string, encoding?: Encoding): MessageDigest; digest(): util.ByteStringBuffer; diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index 62f0718c21..8cb1e54aea 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -222,3 +222,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin return true; }); } + +{ + const key: string = forge.pkcs5.pbkdf2("password", "salt", 1000, 32); +} \ No newline at end of file diff --git a/types/node-telegram-bot-api/index.d.ts b/types/node-telegram-bot-api/index.d.ts index 9d9616b813..d16fd490df 100644 --- a/types/node-telegram-bot-api/index.d.ts +++ b/types/node-telegram-bot-api/index.d.ts @@ -36,6 +36,34 @@ declare namespace TelegramBot { type DocumentMimeType = 'application/pdf' | 'application/zip'; + type MessageType = + 'text' | + 'animation' | + 'audio' | + 'channel_chat_created' | + 'contact' | + 'delete_chat_photo' | + 'document' | + 'game' | + 'group_chat_created' | + 'invoice' | + 'left_chat_member' | + 'location' | + 'migrate_from_chat_id' | + 'migrate_to_chat_id' | + 'new_chat_members' | + 'new_chat_photo' | + 'new_chat_title' | + 'passport_data' | + 'photo' | + 'pinned_message' | + 'sticker' | + 'successful_payment' | + 'supergroup_chat_created' | + 'video' | + 'video_note' | + 'voice'; + type MessageEntityType = 'mention' | 'hashtag' | 'bot_command' | 'url' | 'email' | 'bold' | 'italic' | 'code' | 'pre' | 'text_link' | 'text_mention'; type ParseMode = 'Markdown' | 'HTML'; @@ -887,6 +915,10 @@ declare namespace TelegramBot { user: User; score: number; } + + interface Metadata { + type?: MessageType; + } } declare class TelegramBot extends EventEmitter { @@ -1031,6 +1063,243 @@ declare class TelegramBot extends EventEmitter { answerShippingQuery(shippingQueryId: string, ok: boolean, options?: TelegramBot.AnswerShippingQueryOptions): Promise; answerPreCheckoutQuery(preCheckoutQueryId: string, ok: boolean, options?: TelegramBot.AnswerPreCheckoutQueryOptions): Promise; + + addListener(event: TelegramBot.MessageType | 'message', listener: (message: TelegramBot.Message, metadata: TelegramBot.Metadata) => void): this; + + addListener(event: 'callback_query', listener: (query: TelegramBot.CallbackQuery) => void): this; + + addListener(event: 'inline_query', listener: (query: TelegramBot.InlineQuery) => void): this; + + addListener(event: 'chosen_inline_result', listener: (result: TelegramBot.ChosenInlineResult) => void): this; + + addListener( + event: 'channel_post' | 'edited_message' | 'edited_message_text' | 'edited_message_caption' | 'edited_channel_post' | 'edited_channel_post_text' | 'edited_channel_post_caption', + listener: (message: TelegramBot.Message) => void + ): this; + + addListener(event: 'shipping_query', listener: (query: TelegramBot.ShippingQuery) => void): this; + + addListener(event: 'pre_checkout_query', listener: (query: TelegramBot.PreCheckoutQuery) => void): this; + + addListener(event: 'polling_error' | 'webhook_error' | 'error', listener: (error: Error) => void): this; + + on(event: TelegramBot.MessageType | 'message', listener: (message: TelegramBot.Message, metadata: TelegramBot.Metadata) => void): this; + + on(event: 'callback_query', listener: (query: TelegramBot.CallbackQuery) => void): this; + + on(event: 'inline_query', listener: (query: TelegramBot.InlineQuery) => void): this; + + on(event: 'chosen_inline_result', listener: (result: TelegramBot.ChosenInlineResult) => void): this; + + on( + event: 'channel_post' | 'edited_message' | 'edited_message_text' | 'edited_message_caption' | 'edited_channel_post' | 'edited_channel_post_text' | 'edited_channel_post_caption', + listener: (message: TelegramBot.Message) => void + ): this; + + on(event: 'shipping_query', listener: (query: TelegramBot.ShippingQuery) => void): this; + + on(event: 'pre_checkout_query', listener: (query: TelegramBot.PreCheckoutQuery) => void): this; + + on(event: 'polling_error' | 'webhook_error' | 'error', listener: (error: Error) => void): this; + + once(event: TelegramBot.MessageType | 'message', listener: (message: TelegramBot.Message, metadata: TelegramBot.Metadata) => void): this; + + once(event: 'callback_query', listener: (query: TelegramBot.CallbackQuery) => void): this; + + once(event: 'inline_query', listener: (query: TelegramBot.InlineQuery) => void): this; + + once(event: 'chosen_inline_result', listener: (result: TelegramBot.ChosenInlineResult) => void): this; + + once( + event: 'channel_post' | 'edited_message' | 'edited_message_text' | 'edited_message_caption' | 'edited_channel_post' | 'edited_channel_post_text' | 'edited_channel_post_caption', + listener: (message: TelegramBot.Message) => void + ): this; + + once(event: 'shipping_query', listener: (query: TelegramBot.ShippingQuery) => void): this; + + once(event: 'pre_checkout_query', listener: (query: TelegramBot.PreCheckoutQuery) => void): this; + + once(event: 'polling_error' | 'webhook_error' | 'error', listener: (error: Error) => void): this; + + prependListener(event: TelegramBot.MessageType | 'message', listener: (message: TelegramBot.Message, metadata: TelegramBot.Metadata) => void): this; + + prependListener(event: 'callback_query', listener: (query: TelegramBot.CallbackQuery) => void): this; + + prependListener(event: 'inline_query', listener: (query: TelegramBot.InlineQuery) => void): this; + + prependListener(event: 'chosen_inline_result', listener: (result: TelegramBot.ChosenInlineResult) => void): this; + + prependListener( + event: 'channel_post' | 'edited_message' | 'edited_message_text' | 'edited_message_caption' | 'edited_channel_post' | 'edited_channel_post_text' | 'edited_channel_post_caption', + listener: (message: TelegramBot.Message) => void + ): this; + + prependListener(event: 'shipping_query', listener: (query: TelegramBot.ShippingQuery) => void): this; + + prependListener(event: 'pre_checkout_query', listener: (query: TelegramBot.PreCheckoutQuery) => void): this; + + prependListener(event: 'polling_error' | 'webhook_error' | 'error', listener: (error: Error) => void): this; + + prependOnceListener(event: TelegramBot.MessageType | 'message', listener: (message: TelegramBot.Message, metadata: TelegramBot.Metadata) => void): this; + + prependOnceListener(event: 'callback_query', listener: (query: TelegramBot.CallbackQuery) => void): this; + + prependOnceListener(event: 'inline_query', listener: (query: TelegramBot.InlineQuery) => void): this; + + prependOnceListener(event: 'chosen_inline_result', listener: (result: TelegramBot.ChosenInlineResult) => void): this; + + prependOnceListener( + event: 'channel_post' | 'edited_message' | 'edited_message_text' | 'edited_message_caption' | 'edited_channel_post' | 'edited_channel_post_text' | 'edited_channel_post_caption', + listener: (message: TelegramBot.Message) => void + ): this; + + prependOnceListener(event: 'shipping_query', listener: (query: TelegramBot.ShippingQuery) => void): this; + + prependOnceListener(event: 'pre_checkout_query', listener: (query: TelegramBot.PreCheckoutQuery) => void): this; + + prependOnceListener(event: 'polling_error' | 'webhook_error' | 'error', listener: (error: Error) => void): this; + + removeListener(event: TelegramBot.MessageType | 'message', listener: (message: TelegramBot.Message, metadata: TelegramBot.Metadata) => void): this; + + removeListener(event: 'callback_query', listener: (query: TelegramBot.CallbackQuery) => void): this; + + removeListener(event: 'inline_query', listener: (query: TelegramBot.InlineQuery) => void): this; + + removeListener(event: 'chosen_inline_result', listener: (result: TelegramBot.ChosenInlineResult) => void): this; + + removeListener( + event: 'channel_post' | 'edited_message' | 'edited_message_text' | 'edited_message_caption' | 'edited_channel_post' | 'edited_channel_post_text' | 'edited_channel_post_caption', + listener: (message: TelegramBot.Message) => void + ): this; + + removeListener(event: 'shipping_query', listener: (query: TelegramBot.ShippingQuery) => void): this; + + removeListener(event: 'pre_checkout_query', listener: (query: TelegramBot.PreCheckoutQuery) => void): this; + + removeListener(event: 'polling_error' | 'webhook_error' | 'error', listener: (error: Error) => void): this; + + off(event: TelegramBot.MessageType | 'message', listener: (message: TelegramBot.Message, metadata: TelegramBot.Metadata) => void): this; + + off(event: 'callback_query', listener: (query: TelegramBot.CallbackQuery) => void): this; + + off(event: 'inline_query', listener: (query: TelegramBot.InlineQuery) => void): this; + + off(event: 'chosen_inline_result', listener: (result: TelegramBot.ChosenInlineResult) => void): this; + + off( + event: 'channel_post' | 'edited_message' | 'edited_message_text' | 'edited_message_caption' | 'edited_channel_post' | 'edited_channel_post_text' | 'edited_channel_post_caption', + listener: (message: TelegramBot.Message) => void + ): this; + + off(event: 'shipping_query', listener: (query: TelegramBot.ShippingQuery) => void): this; + + off(event: 'pre_checkout_query', listener: (query: TelegramBot.PreCheckoutQuery) => void): this; + + off(event: 'polling_error' | 'webhook_error' | 'error', listener: (error: Error) => void): this; + + removeAllListeners( + event: + TelegramBot.MessageType | + 'message' | + 'callback_query' | + 'inline_query' | + 'chosen_inline_result' | + 'channel_post' | + 'edited_message' | + 'edited_message_text' | + 'edited_message_caption' | + 'edited_channel_post' | + 'edited_channel_post_text' | + 'edited_channel_post_caption' | + 'shipping_query' | + 'pre_checkout_query' | + 'polling_error' | + 'webhook_error' | + 'error' + ): this; + + listeners( + event: + TelegramBot.MessageType | + 'message' | + 'callback_query' | + 'inline_query' | + 'chosen_inline_result' | + 'channel_post' | + 'edited_message' | + 'edited_message_text' | + 'edited_message_caption' | + 'edited_channel_post' | + 'edited_channel_post_text' | + 'edited_channel_post_caption' | + 'shipping_query' | + 'pre_checkout_query' | + 'polling_error' | + 'webhook_error' | + 'error' + ): Array<(data: any, metadata?: TelegramBot.Metadata) => void>; + + rawListeners( + event: + TelegramBot.MessageType | + 'message' | + 'callback_query' | + 'inline_query' | + 'chosen_inline_result' | + 'channel_post' | + 'edited_message' | + 'edited_message_text' | + 'edited_message_caption' | + 'edited_channel_post' | + 'edited_channel_post_text' | + 'edited_channel_post_caption' | + 'shipping_query' | + 'pre_checkout_query' | + 'polling_error' | + 'webhook_error' | + 'error' + ): Array<(data: any, metadata?: TelegramBot.Metadata) => void>; + + eventNames(): Array< + TelegramBot.MessageType | + 'message' | + 'callback_query' | + 'inline_query' | + 'chosen_inline_result' | + 'channel_post' | + 'edited_message' | + 'edited_message_text' | + 'edited_message_caption' | + 'edited_channel_post' | + 'edited_channel_post_text' | + 'edited_channel_post_caption' | + 'shipping_query' | + 'pre_checkout_query' | + 'polling_error' | + 'webhook_error' | + 'error' + >; + + listenerCount( + event: + TelegramBot.MessageType | + 'message' | + 'callback_query' | + 'inline_query' | + 'chosen_inline_result' | + 'channel_post' | + 'edited_message' | + 'edited_message_text' | + 'edited_message_caption' | + 'edited_channel_post' | + 'edited_channel_post_text' | + 'edited_channel_post_caption' | + 'shipping_query' | + 'pre_checkout_query' | + 'polling_error' | + 'webhook_error' | + 'error' + ): number; } export = TelegramBot; diff --git a/types/node-telegram-bot-api/node-telegram-bot-api-tests.ts b/types/node-telegram-bot-api/node-telegram-bot-api-tests.ts index 49368e74ec..b2d7cea2e6 100644 --- a/types/node-telegram-bot-api/node-telegram-bot-api-tests.ts +++ b/types/node-telegram-bot-api/node-telegram-bot-api-tests.ts @@ -92,3 +92,63 @@ MyTelegramBot.answerShippingQuery('shippingQueryId', true, { shipping_options: [ }] }] }); MyTelegramBot.answerPreCheckoutQuery('preCheckoutQueryId', true, { error_message: 'Bar' }); +MyTelegramBot.addListener('message', (message: TelegramBot.Message, { type }) => { }); +MyTelegramBot.addListener('callback_query', (query: TelegramBot.CallbackQuery) => { }); +MyTelegramBot.addListener('inline_query', (query: TelegramBot.InlineQuery) => { }); +MyTelegramBot.addListener('chosen_inline_result', (result: TelegramBot.ChosenInlineResult) => { }); +MyTelegramBot.addListener('channel_post', (message: TelegramBot.Message) => { }); +MyTelegramBot.addListener('shipping_query', (query: TelegramBot.ShippingQuery) => { }); +MyTelegramBot.addListener('pre_checkout_query', (query: TelegramBot.PreCheckoutQuery) => { }); +MyTelegramBot.addListener('polling_error', (error: Error) => { }); +MyTelegramBot.on('message', (message: TelegramBot.Message, { type }) => { }); +MyTelegramBot.on('callback_query', (query: TelegramBot.CallbackQuery) => { }); +MyTelegramBot.on('inline_query', (query: TelegramBot.InlineQuery) => { }); +MyTelegramBot.on('chosen_inline_result', (result: TelegramBot.ChosenInlineResult) => { }); +MyTelegramBot.on('channel_post', (message: TelegramBot.Message) => { }); +MyTelegramBot.on('shipping_query', (query: TelegramBot.ShippingQuery) => { }); +MyTelegramBot.on('pre_checkout_query', (query: TelegramBot.PreCheckoutQuery) => { }); +MyTelegramBot.on('polling_error', (error: Error) => { }); +MyTelegramBot.once('message', (message: TelegramBot.Message, { type }) => { }); +MyTelegramBot.once('callback_query', (query: TelegramBot.CallbackQuery) => { }); +MyTelegramBot.once('inline_query', (query: TelegramBot.InlineQuery) => { }); +MyTelegramBot.once('chosen_inline_result', (result: TelegramBot.ChosenInlineResult) => { }); +MyTelegramBot.once('channel_post', (message: TelegramBot.Message) => { }); +MyTelegramBot.once('shipping_query', (query: TelegramBot.ShippingQuery) => { }); +MyTelegramBot.once('pre_checkout_query', (query: TelegramBot.PreCheckoutQuery) => { }); +MyTelegramBot.once('polling_error', (error: Error) => { }); +MyTelegramBot.prependListener('message', (message: TelegramBot.Message, { type }) => { }); +MyTelegramBot.prependListener('callback_query', (query: TelegramBot.CallbackQuery) => { }); +MyTelegramBot.prependListener('inline_query', (query: TelegramBot.InlineQuery) => { }); +MyTelegramBot.prependListener('chosen_inline_result', (result: TelegramBot.ChosenInlineResult) => { }); +MyTelegramBot.prependListener('channel_post', (message: TelegramBot.Message) => { }); +MyTelegramBot.prependListener('shipping_query', (query: TelegramBot.ShippingQuery) => { }); +MyTelegramBot.prependListener('pre_checkout_query', (query: TelegramBot.PreCheckoutQuery) => { }); +MyTelegramBot.prependListener('polling_error', (error: Error) => { }); +MyTelegramBot.prependOnceListener('message', (message: TelegramBot.Message, { type }) => { }); +MyTelegramBot.prependOnceListener('callback_query', (query: TelegramBot.CallbackQuery) => { }); +MyTelegramBot.prependOnceListener('inline_query', (query: TelegramBot.InlineQuery) => { }); +MyTelegramBot.prependOnceListener('chosen_inline_result', (result: TelegramBot.ChosenInlineResult) => { }); +MyTelegramBot.prependOnceListener('channel_post', (message: TelegramBot.Message) => { }); +MyTelegramBot.prependOnceListener('shipping_query', (query: TelegramBot.ShippingQuery) => { }); +MyTelegramBot.prependOnceListener('pre_checkout_query', (query: TelegramBot.PreCheckoutQuery) => { }); +MyTelegramBot.prependOnceListener('polling_error', (error: Error) => { }); +MyTelegramBot.removeListener('message', (message: TelegramBot.Message, { type }) => { }); +MyTelegramBot.removeListener('callback_query', (query: TelegramBot.CallbackQuery) => { }); +MyTelegramBot.removeListener('inline_query', (query: TelegramBot.InlineQuery) => { }); +MyTelegramBot.removeListener('chosen_inline_result', (result: TelegramBot.ChosenInlineResult) => { }); +MyTelegramBot.removeListener('channel_post', (message: TelegramBot.Message) => { }); +MyTelegramBot.removeListener('shipping_query', (query: TelegramBot.ShippingQuery) => { }); +MyTelegramBot.removeListener('pre_checkout_query', (query: TelegramBot.PreCheckoutQuery) => { }); +MyTelegramBot.removeListener('polling_error', (error: Error) => { }); +MyTelegramBot.off('message', (message: TelegramBot.Message, { type }) => { }); +MyTelegramBot.off('callback_query', (query: TelegramBot.CallbackQuery) => { }); +MyTelegramBot.off('inline_query', (query: TelegramBot.InlineQuery) => { }); +MyTelegramBot.off('chosen_inline_result', (result: TelegramBot.ChosenInlineResult) => { }); +MyTelegramBot.off('channel_post', (message: TelegramBot.Message) => { }); +MyTelegramBot.off('shipping_query', (query: TelegramBot.ShippingQuery) => { }); +MyTelegramBot.off('pre_checkout_query', (query: TelegramBot.PreCheckoutQuery) => { }); +MyTelegramBot.off('polling_error', (error: Error) => { }); +MyTelegramBot.removeAllListeners('message'); +MyTelegramBot.listeners('message'); +MyTelegramBot.rawListeners('message'); +MyTelegramBot.listenerCount('message'); diff --git a/types/node-xlsx/index.d.ts b/types/node-xlsx/index.d.ts new file mode 100644 index 0000000000..bd500d8a4e --- /dev/null +++ b/types/node-xlsx/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for node-xlsx 0.12 +// Project: https://github.com/mgcrea/node-xlsx#readme +// Definitions by: chenc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/** + * parsing a xlsx from file/buffer, outputs an object of worksheets + * @param mixed file path or buffer + * @param options options is for xlsx + * @returns worksheets data, like: { name: 'worksheets', data: [[1,2,3],['1', '2','word']] } + */ +export declare function parse( + mixed: string | ArrayBuffer, + options?: {} +): Array<{ + name: string; + data: Array<[]>; +}>; + +/** + * building a xlsx + * @param worksheets worksheets data, like:{ name: 'worksheets', data: [[1,2,3],['1', '2','word']] } + * @param options spannig multiple rows A1:A4 + * @returns returns a buffer of worksheets + */ +export declare function build( + worksheets: Array<{ name: string; data: any[][] }>, + options?: {} +): ArrayBuffer; +declare const _default: { + parse: typeof parse; + build: typeof build; +}; +export default _default; diff --git a/types/node-xlsx/node-xlsx-tests.ts b/types/node-xlsx/node-xlsx-tests.ts new file mode 100644 index 0000000000..f9dffcad47 --- /dev/null +++ b/types/node-xlsx/node-xlsx-tests.ts @@ -0,0 +1,8 @@ +import { build } from 'node-xlsx'; +const data = [ + [1, 2, 3], + [true, false, null, 'sheetjs'], + ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'], + ['baz', null, 'qux'], +]; +const buffer = build([{ name: 'mySheetName', data }]); diff --git a/types/node-xlsx/tsconfig.json b/types/node-xlsx/tsconfig.json new file mode 100644 index 0000000000..915d266284 --- /dev/null +++ b/types/node-xlsx/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", + "node-xlsx-tests.ts" + ] +} diff --git a/types/node-xlsx/tslint.json b/types/node-xlsx/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-xlsx/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/npm-email/index.d.ts b/types/npm-email/index.d.ts new file mode 100644 index 0000000000..055a68f8af --- /dev/null +++ b/types/npm-email/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for npm-email 3.0 +// Project: https://github.com/sindresorhus/npm-email#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = npmEmail; + +/** + * Get the email of an npm user. + * + * @param username npm username to look up. + * @returns A promise for the user's email address. + */ +declare function npmEmail(username: string): Promise; diff --git a/types/npm-email/npm-email-tests.ts b/types/npm-email/npm-email-tests.ts new file mode 100644 index 0000000000..b0640c73e3 --- /dev/null +++ b/types/npm-email/npm-email-tests.ts @@ -0,0 +1,3 @@ +import npmEmail = require('npm-email'); + +npmEmail('sindresorhus'); // $ExpectType Promise diff --git a/types/npm-email/tsconfig.json b/types/npm-email/tsconfig.json new file mode 100644 index 0000000000..985ed0472a --- /dev/null +++ b/types/npm-email/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", + "npm-email-tests.ts" + ] +} diff --git a/types/npm-email/tslint.json b/types/npm-email/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-email/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/npm-keyword/index.d.ts b/types/npm-keyword/index.d.ts new file mode 100644 index 0000000000..94c8af9f13 --- /dev/null +++ b/types/npm-keyword/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for npm-keyword 5.0 +// Project: https://github.com/sindresorhus/npm-keyword#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = npmKeyword; + +/** + * Get a list of npm packages with a certain keyword. + * + * @param keyword One or more keywords. Only matches packages that have *all* the given keywords. Example: `['string', 'camelcase']` + * @returns A promise for a list of packages having the specified keyword in their package.json `keyword` property. + */ +declare function npmKeyword( + keyword: string | string[], + options?: npmKeyword.Options +): Promise; + +declare namespace npmKeyword { + /** + * @param keyword One or more keywords. Only matches packages that have *all* the given keywords. Example: `['string', 'camelcase']` + * @returns A promise for a list of package names. Use this if you don't need the description as it's faster. + */ + function names(keyword: string | string[], options?: Options): Promise; + + /** + * @param keyword One or more keywords. Only matches packages that have *all* the given keywords. Example: `['string', 'camelcase']` + * @returns A promise for the count of packages. + */ + function count(keyword: string | string[]): Promise; + + interface Options { + /** + * Limits the amount of results. + * @default 250 + */ + size?: number; + } + + interface PackageDescriptor { + name: string; + description: string; + } +} diff --git a/types/npm-keyword/npm-keyword-tests.ts b/types/npm-keyword/npm-keyword-tests.ts new file mode 100644 index 0000000000..17418bdb04 --- /dev/null +++ b/types/npm-keyword/npm-keyword-tests.ts @@ -0,0 +1,7 @@ +import npmKeyword = require('npm-keyword'); + +npmKeyword('gulpplugin'); // $ExpectType Promise +npmKeyword('gulpplugin', { size: 10 }); // $ExpectType Promise +npmKeyword.names('gulpplugin'); // $ExpectType Promise +npmKeyword.names('gulpplugin', { size: 10 }); // $ExpectType Promise +npmKeyword.count('gulpplugin'); // $ExpectType Promise diff --git a/types/npm-keyword/tsconfig.json b/types/npm-keyword/tsconfig.json new file mode 100644 index 0000000000..b0c0fed33d --- /dev/null +++ b/types/npm-keyword/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", + "npm-keyword-tests.ts" + ] +} diff --git a/types/npm-keyword/tslint.json b/types/npm-keyword/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-keyword/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/npm-run-path/index.d.ts b/types/npm-run-path/index.d.ts new file mode 100644 index 0000000000..6a052e0450 --- /dev/null +++ b/types/npm-run-path/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for npm-run-path 2.0 +// Project: https://github.com/sindresorhus/npm-run-path#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = npmRunPath; + +/** + * Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries. + */ +declare function npmRunPath(options?: npmRunPath.Options): string; + +declare namespace npmRunPath { + function env(options?: EnvOptions): ProcessEnv; + + interface Options { + /** + * Working directory. + */ + cwd?: string; + /** + * PATH to be appended. + * Set it to an empty string to exclude the default [PATH](https://github.com/sindresorhus/path-key). + * @default PATH + */ + path?: string; + } + + interface EnvOptions { + /** + * Working directory. + */ + cwd?: string; + /** + * Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct + * [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use + * in the `child_process` options. + */ + env?: ProcessEnv; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } +} diff --git a/types/npm-run-path/npm-run-path-tests.ts b/types/npm-run-path/npm-run-path-tests.ts new file mode 100644 index 0000000000..4cff236373 --- /dev/null +++ b/types/npm-run-path/npm-run-path-tests.ts @@ -0,0 +1,16 @@ +/// + +import childProcess = require('child_process'); +import npmRunPath = require('npm-run-path'); + +npmRunPath(); // $ExpectType string +npmRunPath({ cwd: '/foo' }); // $ExpectType string +npmRunPath({ path: '/usr/local/bin' }); // $ExpectType string + +npmRunPath.env(); // $ExpectType ProcessEnv +npmRunPath.env({ cwd: '/foo' }); // $ExpectType ProcessEnv +npmRunPath.env({ env: process.env }); // $ExpectType ProcessEnv + +childProcess.execFileSync('foo', { + env: npmRunPath.env(), +}); diff --git a/types/npm-run-path/tsconfig.json b/types/npm-run-path/tsconfig.json new file mode 100644 index 0000000000..d6738a23ca --- /dev/null +++ b/types/npm-run-path/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", + "npm-run-path-tests.ts" + ] +} diff --git a/types/npm-run-path/tslint.json b/types/npm-run-path/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-run-path/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/npm-user-packages/index.d.ts b/types/npm-user-packages/index.d.ts new file mode 100644 index 0000000000..99ed62012f --- /dev/null +++ b/types/npm-user-packages/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for npm-user-packages 3.0 +// Project: https://github.com/kevva/npm-user-packages#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = npmUserPackages; + +/** + * Get packages by a npm user. + * @param username User to fetch packages from. + */ +declare function npmUserPackages(username: string): Promise; + +declare namespace npmUserPackages { + interface PackageData { + author: { + email?: string; + name: string; + url?: string; + username?: string; + }; + date: string; + description: string; + keywords: string[]; + links: { + bugs?: string; + homepage?: string; + npm: string; + repository?: string; + }; + maintainers: Array<{ + email: string; + username: string; + }>; + name: string; + publisher: { + email: string; + username: string; + }; + scope: string; + version: string; + } +} diff --git a/types/npm-user-packages/npm-user-packages-tests.ts b/types/npm-user-packages/npm-user-packages-tests.ts new file mode 100644 index 0000000000..509e82a16b --- /dev/null +++ b/types/npm-user-packages/npm-user-packages-tests.ts @@ -0,0 +1,3 @@ +import npmUserPackages = require('npm-user-packages'); + +npmUserPackages('kevva'); // $ExpectType Promise diff --git a/types/npm-user-packages/tsconfig.json b/types/npm-user-packages/tsconfig.json new file mode 100644 index 0000000000..5650f12560 --- /dev/null +++ b/types/npm-user-packages/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", + "npm-user-packages-tests.ts" + ] +} diff --git a/types/npm-user-packages/tslint.json b/types/npm-user-packages/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-user-packages/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/npm-user/index.d.ts b/types/npm-user/index.d.ts new file mode 100644 index 0000000000..2d03c12c0c --- /dev/null +++ b/types/npm-user/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for npm-user 3.0 +// Project: https://github.com/sindresorhus/npm-user#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = npmUser; + +declare function npmUser(name: string): Promise; + +declare namespace npmUser { + interface UserData { + name: string | null; + avatar: string | null; + email: string | null; + github: string | null; + twitter: string | null; + } +} diff --git a/types/npm-user/npm-user-tests.ts b/types/npm-user/npm-user-tests.ts new file mode 100644 index 0000000000..1d63de27ef --- /dev/null +++ b/types/npm-user/npm-user-tests.ts @@ -0,0 +1,11 @@ +import npmUser = require('npm-user'); + +npmUser('sindresorhus').then(user => { + user; // $ExpectType UserData + + user.name; // $ExpectType string | null + user.avatar; // $ExpectType string | null + user.email; // $ExpectType string | null + user.github; // $ExpectType string | null + user.twitter; // $ExpectType string | null +}); diff --git a/types/npm-user/tsconfig.json b/types/npm-user/tsconfig.json new file mode 100644 index 0000000000..1e5c1d464f --- /dev/null +++ b/types/npm-user/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", + "npm-user-tests.ts" + ] +} diff --git a/types/npm-user/tslint.json b/types/npm-user/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-user/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/nuka-carousel/index.d.ts b/types/nuka-carousel/index.d.ts deleted file mode 100644 index 97edd08a6d..0000000000 --- a/types/nuka-carousel/index.d.ts +++ /dev/null @@ -1,288 +0,0 @@ -// Type definitions for nuka-carousel 4.4 -// Project: https://github.com/FormidableLabs/nuka-carousel -// Definitions by: Roman Charugin -// Alex Smith -// matt-sungwook -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import * as React from 'react'; - -export default class Carousel extends React.Component {} - -export type CarouselCellAlignProp = 'left' | 'center' | 'right'; - -export type CarouselHeightModeProp = 'first' | 'current' | 'max'; - -export type CarouselSlidesToScrollProp = number | 'auto'; - -export type CarouselSlideWidthProp = string | number; - -export interface CarouselSlideRenderControlProps { - /** - * Space between slides, as an integer, but reflected as px - */ - cellSpacing: number; - /** - * Current slide index - */ - currentSlide: number; - /** - * Current frame width (px) - */ - frameWidth: number; - /** - * Go to X slide method - * @param index Slide's index to go - */ - goToSlide: (index: number) => void; - /** - * Go to the next slide method - */ - nextSlide: () => void; - /** - * Go to the previous slide method - */ - previousSlide: () => void; - /** - * Total amount of slides - */ - slideCount: number; - /** - * Slides to scroll at once - */ - slidesToScroll: number; - /** - * Slides to show at once - */ - slidesToShow: number; - /** - * Current slide width (px) - */ - slideWidth: number; - /** - * Infinite mode enabled - */ - wrapAround: boolean; -} - -export type CarouselRenderControl = (props: CarouselSlideRenderControlProps) => JSX.Element; - -export interface CarouselProps { - /** - * Hook to be called after a slide is changed - * @param prevSlide Index of the previous slide - */ - afterSlide?: (prevSlide: number) => void; - /** - * Autoplay mode active - * @default false - */ - autoplay?: boolean; - /** - * Interval for autoplay iteration (ms) - * @default 3000 - */ - autoplayInterval?: number; - /** - * Hook to be called before a slide is changed - * @param currentSlide Index of the current slide - * @param endSlide Index of the last slide - */ - beforeSlide?: (currentSlide: number, endSlide: number) => void; - /** - * When displaying more than one slide, - * sets which position to anchor the current slide to - */ - cellAlign?: CarouselCellAlignProp; - /** - * Space between slides, as an integer, but reflected as px - */ - cellSpacing?: number; - /** - * Additional className - */ - className?: string; - /** - * When set to true, disable keyboard controls - * @default false - */ - disableKeyboardControls?: boolean; - /** - * Enable mouse swipe/dragging - */ - dragging?: boolean; - /** - * Animation easing function - * @see https://github.com/d3/d3-ease - */ - easing?: string; - /** - * Animation easing function when swipe exceeds edge - * @see https://github.com/d3/d3-ease - */ - edgeEasing?: string; - /** - * Used to set overflow style property on slider frame - * @default 'hidden' - */ - frameOverflow?: string; - /** - * Used to set the margin of the slider frame. - * Accepts any string dimension value such as "0px 20px" or "500px" - * @example '0px 20px' - * @example '500px' - */ - framePadding?: string; - /** - * Change the height of the slides based either on the first slide, - * the current slide, or the maximum height of all slides. - */ - heightMode?: CarouselHeightModeProp; - /** - * Initial height of the slides (px) - */ - initialSlideHeight?: number; - /** - * Initial width of the slides (px) - */ - initialSlideWidth?: number; - /** - * Window onResize callback - */ - onResize?: () => void; - /** - * Pause autoPlay when mouse is over carousel - * @default true - */ - pauseOnHover?: boolean; - /** - * Function for rendering top left control - */ - renderTopLeftControls?: CarouselRenderControl; - /** - * Function for rendering top center control - */ - renderTopCenterControls?: CarouselRenderControl; - /** - * Function for rendering top right control - */ - renderTopRightControls?: CarouselRenderControl; - /** - * Function for rendering center left control - */ - renderCenterLeftControls?: CarouselRenderControl; - /** - * Function for rendering center center control - */ - renderCenterCenterControls?: CarouselRenderControl; - /** - * Function for rendering center right control - */ - renderCenterRightControls?: CarouselRenderControl; - /** - * Function for rendering bottom left control - */ - renderBottomLeftControls?: CarouselRenderControl; - /** - * Function for rendering bottom center control - */ - renderBottomCenterControls?: CarouselRenderControl; - /** - * Function for rendering bottom right control - */ - renderBottomRightControls?: CarouselRenderControl; - /** - * Manually set the index of the slide to be shown - */ - slideIndex?: number; - /** - * Slides to scroll at once. Set to "auto" - * to always scroll the current number of visible slides - */ - slidesToScroll?: CarouselSlidesToScrollProp; - /** - * Slides to show at once - */ - slidesToShow?: number; - /** - * Manually set slideWidth - * @example '20px' - * @example 0.8 - */ - slideWidth?: CarouselSlideWidthProp; - /** - * Animation duration - */ - speed?: number; - /** - * Enable touch swipe/dragging - */ - swiping?: boolean; - /** - * Enable the slides to transition vertically - */ - vertical?: boolean; - /** - * Used to hardcode the slider width - * @example '80%' - * @example '500px' - */ - width?: string; - /** - * Sets infinite wrapAround mode - * @default false - */ - wrapAround?: boolean; - /** - * Used to remove all controls at once. Overwrites the render[Top, Right, Bottom, Left]CenterControls() - * @default false - */ - withoutControls?: boolean; -} - -export interface CarouselState { - /** - * Current slide index - */ - currentSlide: number; - /** - * Is dragging enabled - */ - dragging: boolean; - /** - * Easing function name - */ - easing: string; - /** - * Current frame width - */ - frameWidth: number; - /** - * Current left value - */ - isWrappingAround: boolean; - left: number; - pauseOnHover: boolean; - resetWrapAroundPosition: boolean; - /** - * Total amount of slides - */ - slideCount: number; - /** - * Slides to scroll at once - */ - slidesToScroll: number; - /** - * Current slide width - */ - slideWidth: CarouselSlideWidthProp; - /** - * Current top value - */ - top: number; - /** - * Is infinite mode enabled - */ - wrapToIndex: boolean; -} diff --git a/types/nuka-carousel/nuka-carousel-tests.tsx b/types/nuka-carousel/nuka-carousel-tests.tsx deleted file mode 100644 index 03df5e6251..0000000000 --- a/types/nuka-carousel/nuka-carousel-tests.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import * as React from 'react'; -import { render } from 'react-dom'; - -import Carousel, { CarouselProps } from 'nuka-carousel'; - -const props: CarouselProps = { - afterSlide: () => {}, - autoplay: true, - autoplayInterval: 5000, - beforeSlide: () => {}, - cellAlign: 'center', - cellSpacing: 500, - dragging: true, - easing: 'easePoly', - edgeEasing: 'easePolyInOut', - framePadding: '100px', - heightMode: 'max', - initialSlideHeight: 200, - initialSlideWidth: 500, - onResize: () => {}, - renderTopLeftControls: () =>